Friday, September 24, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Check if Column is Vector Type

Posted: 24 Sep 2021 09:06 AM PDT

I am trying to determine if a column is a vector type, but am running into issues.

After I run a model and create a dataframe called predictions, there is a field called probability.

When I run this code to see the datatype if shows a vector.

predictions.schema['probability'].dataType  Out[128]: VectorUDT  

Then when I run this I get a false returned

predictions.schema["probability"].dataType == 'VectorUDT'  Out[129]: False  

So I tried this

dict(predictions.dtypes)['probability'] == 'vector'  Out[130]: True  

However, when I try to use that in my dataframe I get an error stating TypeError: unhashable type: 'Column'

.withColumn('test',   when(dict(predictions.dtypes)['probability'] == 'vector',1)                             .otherwise(0)) \  

Looking For A Way To Add A Voice Message & Integrate Into HighLevel

Posted: 24 Sep 2021 09:06 AM PDT

I use Twilio to integrate into a HighLevel account. In HighLevel, I was attempting to utilize my own recording for calls that are being recorded. The issue is that since this is a Spanish-Speaking line, when we use the automated voice, the language does not sound good.

HighLevel does not have a way to upload your own recording, so I was thinking of using the Studio flow in Twillio to set that up. The issue is that if I switch over the incoming calls from the webhook to my studio flow, it breaks the integration and the number no longer works. I was wondering if there was a way to set this up so I still have my full webhook integration back into the HighLevel system and use my own voice recording.

Thank you

fs.mkdir not creating directory nor giving error

Posted: 24 Sep 2021 09:06 AM PDT

The following code does not create a new directory, nor does it output any err

const fs = require('fs-extra');  fs.mkdir(dirPath, { recursive: true }, (err) => {              if (err) {                  console.log("ERR: When attempting to mkdir", err)              } else {                  console.log("MKDIR made " + dirPath);              }              cb(null, dirPath)          })  

I would expect the directory to be created... or an error.

When I console.log(err) I find that the value of err is null.

How can I ensure this directory has been created?

Printing an output using pandas .groupby to include keys that equalled to 0?

Posted: 24 Sep 2021 09:06 AM PDT

I'm trying to get an output that includes every key, even if the is an equivalent value of 0.

import pandas as pd    df = pd.read_csv('climate_data_Dec2017.csv')    wind_direction = df['Direction of maximum wind gust']  is_on_a_specific_day = df['Date'].str.contains("12-26")  specific_day = df[is_on_a_specific_day]    grouped_by_date = specific_day.groupby('Direction of maximum wind gust')  number_record_by_date = grouped_by_date.size()    print(number_record_by_date)  

The current output looks like this right now:

E      4  ENE    2  ESE    1  NE     1  NNE    1  NNW    1  SE     3  SSE    3  SW     1  

But I'm trying to get it to include other directions too. ie

E      4  ENE    2  ESE    1  N      0  NE     1  NNE    1  NNW    1  NW     0  S      0  SE     3  SSE    3  SW     1  ...  

Is there any way to get my code to include it? I tried to group it by the wind direction dataframe rather than the specific_day dataframe, but going down that route, I'm stuck on what to do next. Any pointers would be great! Thanks

Flutter remove duplicate array by value

Posted: 24 Sep 2021 09:05 AM PDT

I have an array that has the same name value I just need to check if the same value comes it will delete it.

My data looks like

[{'name':'Rameez', 'data': [{'age': 1, 'number': 2}]}, {'name':'XYZ', 'data': [{'age': 1, 'number': 2}]}, {'name':'Rameez', 'data': [{'age': 1, 'number': 2}]}];  

I want to show it like this no duplicate name

Expected output dataaa = [{'name':'Rameez', 'data': [{'age': 1, 'number': 2}]}, {'name':'XYZ', 'data': [{'age': 1, 'number': 2}]}];  

Kafka design question with duplicate events

Posted: 24 Sep 2021 09:05 AM PDT

I have this architecture with Kafka that I would like to figure what is the best way to solve it.

I have two Kafka Producers to avoid Single point of failure, that are subscribed each to a external service, and when this service send the callback, both are generating the exactly same event.

Then I have a consumer subscribed to that Topic, that consume the events duplicated.

Possible Solutions: Use some distributed clutter like Akka distributed data, to communicate producers, and only send one event.

Or make my consumer idempotent and being able to consume duplicated events without conflicts.

There's any other alternative to this?

Regards

Vector to Set conversion

Posted: 24 Sep 2021 09:05 AM PDT

In Python we can convert List to Set using function set() and we can also do other conversions using functions like set() list() etc.

nums[:] = sorted(set(nums))
return len(nums)

Is it possible to do so in C++?

Push list with 4 rows to bottom

Posted: 24 Sep 2021 09:05 AM PDT

I want to have this list at the bottom of the screen. I know that there are only 4 Rows (or 5). I tried to use UITableView.appearance().contentInset.top = … But the value depends on the screenHeight, the rowHeight and the safeArea. When I tried to use this after onAppeared() the largeTitle changed to inLine. I also set the TableView to UiTableView.appearance().scrollingEnabled = false I don't know how to archive it. I would like to have the title always large and the screen not scrollable. Thanks for any help.

var body:some View{      NavigationView{         List{             Text(„hi")             Text(„hi")             Text(„hi")             Text(„hi")         }         .navigationBarTitle(„Hi", displayMode: .large)      }  }  

could you help me to make a code to permute arrays in c

Posted: 24 Sep 2021 09:05 AM PDT

Given an array a[n] of size n and another array p[n] of equal size. Write a function that permutes the elements of a based on p. Example: a = [10, 100, 1000] p = [1, 2, 0]

Let `ap` be considered the permuted array.  As the first element of `p` is 1, element 1 of `ap` is the first element of `a`.  As the second element of `p` is 2, element 2 of `ap` is the second element of `a`.  Since the third element of `p` is 0, the 0th element of `ap` is the third element of `a`.  The permuted array is as follows:      ap = [1000, 10, 100]  

Note: the size of ap is n and all its elements are integers from 0 to n-1. Note: the indexing of the arrays starts at 0.

Example 2:      a = [10, 100, 1000, 10000, 100000]               0 1 2 3 4        p = [1, 4, 2, 0, 3]             0 1 2 3 4          ap = [10000, 10, 1000, 1000, 100000, 100] 0 1 1 2 3 4                    0 1 2 3 4  

How to change html meter element background color with tailwind

Posted: 24 Sep 2021 09:05 AM PDT

How can I change the meter background color using tailwind?

I'd like to apply a color defined in my tailwind theme.

is it possible?

Thanks!

How can I make the the google chart animation start only when it comes into view when scrolled?

Posted: 24 Sep 2021 09:05 AM PDT

Hi I want to know how can I make the google chart animation only start when scrolled and when it comes into view.

  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>    <div id="chart_div"></div>      google.charts.load('current', {packages: ['corechart', 'bar']});  google.charts.setOnLoadCallback(drawMultSeries);    function drawMultSeries() {    var data = google.visualization.arrayToDataTable([      ['City', '2010 Population', '2000 Population'],      ['New York City, NY', 8175000, 8008000],      ['Los Angeles, CA', 3792000, 3694000],      ['Chicago, IL', 2695000, 2896000],      ['Houston, TX', 2099000, 1953000],      ['Philadelphia, PA', 1526000, 1517000]    ]);     var options = {                  animation: {              duration: 2000,              startup: true //This is the new option          },             };        var chart = new google.visualization.BarChart(document.getElementById('chart_div'));    chart.draw(data, options);  }  

How to retreive a java script value that does not have a subclass

Posted: 24 Sep 2021 09:06 AM PDT

I am trying to retreive a value from a java script that does not have a subclass. In this case, I am trying to retreive the "Today" value

<div class="jobsearch-JobMetadataFooter">       <div>Today</div>  

can it be done? If so, how?

DateTime::__construct(): Failed to parse time string (from) at position 0 (f): The timezone could not be found in the database

Posted: 24 Sep 2021 09:06 AM PDT

I am getting this error

DateTime::__construct(): Failed to parse time string (from) at position 0 (f): The timezone could not be found in the database

I tried to different methods to solve this error. but not successfully at all.

$from = null;  $to = null;    try{      if ($request->input('from') || $request->input('to')) {            if ($request->input('from')) {              $from = Carbon::createFromFormat('Y-m-d', $request->input('from'))->toDateString();          }          if ($request->input('to')) {              $to = Carbon::createFromFormat('Y-m-d', $request->input('to'))->toDateString();          }            $validator = Validator::make(              [                  'from' => $from,                  'to'   => $to              ],              [                  'from' => 'required|date|date_format:Y-m-d',                  'to'   => 'required|date|date_format:Y-m-d|after_or_equal:from',              ]          );          if ($validator->fails()) {              return \Redirect::back()                  ->with(array('flash_message' => "Please Enter Correct Date Format"));          }      }  } catch (\Exception $e)  {      \Log::debug("Time invalid ");  }  

issue is fire in here i think $validator->fails()

anyone have an idea about this?

Postgraphile "Only `POST` requests are allowed." error

Posted: 24 Sep 2021 09:05 AM PDT

I have Postgres running locally. I can access the database locally with psql postgres:///reviewapp and with \dt I can see a few tables.

If I run npx postgraphile -c "postgres:///reviewapp" I dont get any errors in the terminal:

PostGraphile v4.12.4 server listening on port 5000 🚀      ‣ GraphQL API:         http://localhost:5000/graphql    ‣ GraphiQL GUI/IDE:    http://localhost:5000/graphiql (RECOMMENDATION: add '--enhance-graphiql')    ‣ Postgres connection: postgres:///reviewapp    ‣ Postgres schema(s):  public    ‣ Documentation:       https://graphile.org/postgraphile/introduction/    ‣ Node.js version:     v14.15.5 on darwin x64    ‣ Join Mark in supporting PostGraphile development: https://graphile.org/sponsor/    * * *  

However when I go to http://localhost:5000/graphql I have an error on the screen: {"errors":[{"message":"Only POST requests are allowed."}]}

Changing dropdown selected item in jquery not changing text?

Posted: 24 Sep 2021 09:05 AM PDT

I have a dropdownlist and I am trying to change the selected item but the text is not changing. I am assuming it's because I am doing it client side but I once I've changed the selected item I am un sure how to change the text in the dropdownlist.

JQuery Code: -

            function setPhotoStage(photoStageId) {                  $("[id*=drpPhotoStages] option").each(function () {                      if ($(this).val() == photoStageId) {                          $(this).attr('selected', 'selected');                          alert($(this).val());                      } else {                          $(this).removeAttr('selected');                      }                  });              }

The code above is selecting the correct item in the list if I click on it but not changing it on the form: - enter image description here

Here is the code when I inspect the dropdown. Some how I need to change the filter-option-inner-inner to the newly selected text: -

enter image description here

Any help please, I've looked everywhere and cannot find a solution.

Concating $_ in Pattern for regular expression in PowerShell

Posted: 24 Sep 2021 09:06 AM PDT

I want to use the $_ in a Pattern in Powershell. I have the following script but it doesn't work

Get-Content ..\myfile.txt | ForEach-Object {          $counter=(gc *.log | Select-String -Pattern '$_\/Directory\/Cars\/Sign.jpg')  }  

If I run the script, in lines of the myfile.txt which I know there is some ocurrences according to the Pattern it finds 0, so how I must write the $_ in the pattern?.

Thanks so much

How to achieve 'goBack' in React-Navigation/Drawer 6

Posted: 24 Sep 2021 09:06 AM PDT

I'm having problem in implementing 'goBack' function in React-navigation/drawer 6 ("@react-navigation/drawer": "^6.1.4", precisely).

I was able to perfectly achieve it in react-navigation/drawer 5 with the following codes:

<Drawer.Navigator>      <Drawer.Screen           ....          options={{            header: ({ scene }) => {              const { options } = scene.descriptor;              const title = options.headerTitle;                return (                  <MyHeader                     title={title}                    iconName={"menu"}                     goback={                      ()=>scene.descriptor.navigation.goBack()}                  />                );            },          }}        />  </Drawer.Navigator>  

The same revised codes for react-navigation/drawer 6 (as shown below) will take me back to the initial screen (and not on previous screen). It will also give a warning and error message.

<Drawer.Navigator>      <Drawer.Screen           ....          options={{            header: ({ navigation, route, options }) => {                const title = getHeaderTitle(options, route.name);                return (                  <MyHeader                     title={title}                    iconName={"menu"}                     goback={                      ()=>navigation.goBack()}                  />                );            },          }}        />  </Drawer.Navigator>  

Please, how can I achieve this 'goBack' in react-navigation/drawer 6?

VSCode - custom snippet to create multiple different lines from selected C++ declaration

Posted: 24 Sep 2021 09:05 AM PDT

I have a line:

int INTVAR;  

I would like to highlight this line, and run a snippet which automatically creates the following set of three lines in place of the single line above.

int INTVAR;  int intvar() {return INTVAR;}  void intvar(int val){INTVAR = val;}  

That is, a function that it a getter/setter for the variable should automatically be generated. The variable name will always be in full capital letters. The getter/setter name should be the same except that they will always be in lower case.

int could also be a double, char, etc.

ETA:

What I have tried/know so far: Instead of highlighting the line, the following appears more straightforward where I just type the declaration once and the getters/setters are automatically added.

"int var set get":{      "prefix": "intsetget",      "body":[          "int ${1:VARNM};",          "int ${1:/downcase}(){return ${1};}",          "void ${1:/downcase}(int val){${1} = val;}"      ]  }  

This almost gets the job done, except that the downcase for setter and getter name does not work.

Custom post type menu in admin with CPT+term as submenus

Posted: 24 Sep 2021 09:06 AM PDT

I am trying to create a menu for a CPT. Requirements:

  1. (SOLVED)Create menu without link. So far I used the slug for the menú javascript:void()with the key "registro-digital". That prevents link to anywhere from created menu and ensures an unique slug:
add_menu_page(          __( 'Registro digital', 'peslam_cecr' ),          __( 'Registro digital', 'peslam_cecr' ),          'administrator',          'javascript:void("peslam-registro-digital")',          '',          'dashicons-media-document',          1      );  
  1. (UNSOLVED, HELP!!)Do not show the submenu created automatically "Registro digital" I tried "remove_submenu_page" with no luck since the parent and the submenu are the same...Result should be:

menu view

  1. (UNSOLVED, HELP!!) In the submenus are shown the CTP wit "entrada" term and the CPT with "salida" term. Everything looks ok until you try to search o filter and the filter and the search return the result for the CPT without the term filtering. The code used to create them:
 add_submenu_page(          'javascript:void("peslam-registro-digital")',          __( 'Entradas', 'peslam_cecr' ),          __( 'Entradas', 'peslam_cecr' ),          'administrator',          'edit.php?&post_type=registro_digital&tipo_registro=entrada'      );        add_submenu_page(          'javascript:void("peslam-registro-digital")',          __( 'Salidas', 'peslam_cecr' ),          __( 'Salidas', 'peslam_cecr' ),          'administrator',          'edit.php?&post_type=registro_digital&tipo_registro=salida'      );  

EXAMPLE: The URL for the entry "entrada" is "edit.php?&post_type=registro_digital&tipo_registro=salida", but if I search the URL goes to the search without "&tipo_registro=salida" what is all the point!!

Any ideas?? Thanks very much!!!

UPDATE 1

For number 3 I found a workaround catching the request URI when coming from "entradas" o "salidas" page, adding query var and redirecting:

function redireccion_registros_correcta( $query ) {      if( !is_admin() ) {          return;      }        global $pagenow;      global $typenow;        if ( $pagenow == "edit.php" && $typenow == "registro_digital" ){            //URL de procedencia          $url_parse = wp_parse_url( $_SERVER["HTTP_REFERER"] );          wp_parse_str( $url_parse['query'], $parameters_query ); //Almacenamos los parámetros de la query en el array $parameters_query            //URL de destino          $es_url_correcta = get_query_var('tipo_registro'); //Si la URL destino tiene esa query_var            if (in_array('entrada', $parameters_query) && !$es_url_correcta) {              $url_corrected = add_query_arg( ['tipo_registro' => 'entrada'] );              if ( wp_redirect( $url_corrected ) ) {                  exit;              }          } else if (in_array('salida', $parameters_query)) {              $url_corrected = add_query_arg( ['tipo_registro' => 'salida'] );              if ( wp_redirect( $url_corrected ) ) {                  exit;              }          }          return;      } else {          return;      }  }  add_action( 'pre_get_posts', 'redireccion_registros_correcta' );  

Still need help with number 2, though! (make dissappear submenu for main menu) And honestly all this look a bit "dirty" I would appreciate other approaches for the whole.

There are 4 fields based on its values combination we have to filter the data in Mulesoft

Posted: 24 Sep 2021 09:05 AM PDT

There are 4 fields based on its values combination we have to filter the data in Mulesoft. Example:

Input payload 1:

{
"Msg": {
"Code": "abc",
"Chcode": "123",
"Dcode": "55",
"Type": "pqr"
} }

Input payload 2:

{
"Msg": {
"Code": "klm",
"Chcode": "789",
"Dcode": "32",
"Type": "xyz"
} }

Input payload 3:

{
"Msg": {
"Code": "klm",
"Chcode": "456",
"Dcode": "22",
"Type": "shi"
} }

Filter condition: Input payload should match with Code, Chcode, Dcode and Type.
Example: Input payload should contain Code=abc, Chcode=123, Dcode=55, Type=pqr

Code Chcode Dcode Type
abc 123 55 pqr
ghl 456 22 shi
ghi 276 3u foh

The input payload 1 matches the first row in filter condition like code,Chcode,Dcode and Type are same. So that record should be filtered for processing. Input payload 3 matches with Chcode,Dcode and Type but not with Code so this record is to be ignored.

Like these above combinations, there are 45 combinations, how to filter this type of records in Mulesoft.

How to validate a custom component with vee-validate 3?

Posted: 24 Sep 2021 09:05 AM PDT

I'm trying to get vee-validate to work on a custom component.
Vee-validate works on other non-custom components.
The v-model on the DatePickerInput component works (the value is updated in the parent component).

The problem: no error messages are shown and the "errors" value stays empty:

<validation-provider      v-slot="{ errors }"      :name="$t('StartDate')"      rules="required">    <div>{{ errors }}</div>    <DatePickerInput        v-model="startDate"        :label="$t('StartDate')"        :error-messages="errors" />  </validation-provider>  

The DatePickerInput component is created like this (I removed some properties that seem unrelated):

<template>    <v-menu v-model="showMenu">      <template v-slot:activator="{ on, attrs }">        <v-text-field            v-model="date"            :label="label"            :error-messages="errorMessages"            prepend-icon="mdi-calendar"            v-bind="attrs"            v-on="on"            @click:prepend="showMenu = !showMenu"></v-text-field>      </template>      <v-date-picker          :value="isoDate"          @input="(isoDate) => this.date = isoDate"></v-date-picker>    </v-menu>  </template>    <script>  export default {    props: ['value', 'label', 'error-messages'],    data() {      return {        date: this.value,        showMenu: false,      }    },    computed: {      isoDate() {        return new Date(this.date).toISOString().substr(0, 10)      },    },    watch: {      date: {        handler(date) { this.handleInput(date) },      },    },    methods: {      handleInput(e) { this.$emit('input', e) },    },  }  </script>  

Why are errors not shown?

Create all possible combinations of non-NA values for each group ID

Posted: 24 Sep 2021 09:06 AM PDT

Similar to this question but with an added twist:

Given the following data frame:

txt <- "ID    Col1    Col2    Col3    Col4          1     6       10      NA      NA          1     5       10      NA      NA          1     NA      10      15      20          2     17      25      NA      NA          2     13      25      NA      NA          2     NA      25      21      34          2     NA      25      35      40"  DF <- read.table(text = txt, header = TRUE)    DF    ID Col1 Col2 Col3 Col4  1  1    6   10   NA   NA  2  1    5   10   NA   NA  3  1   NA   10   15   20  4  2   17   25   NA   NA  5  2   13   25   NA   NA  6  2   NA   25   21   34  7  2   NA   25   35   40  

I wish to collapse the rows by group ID (analogous to Col2 in this example), and when more than 1 combination is present per group, to return all combinations, as so:

  ID Col1 Col2 Col3 Col4  1  1    6   10   15   20  2  1    5   10   15   20  3  2   17   25   21   34  4  2   13   25   21   34  5  2   17   25   35   40  6  2   13   25   35   40  

Importantly, down the road I'll need this to work on non-numerical data. Any suggestions? Thanks!

convert UNIX epoch time to ISO8601 in a stream of data with perl

Posted: 24 Sep 2021 09:05 AM PDT

I'm using an API with curl --write-out '\n%{http_code}\t=%{time_total}s\n' that provides the date information about the fields in UNIX Epoch time instead of ISO8601, which makes it difficult to understand what's going on.

Sample Input:

{"message":"Domains list","list":[{"domain":"example.org","created":"1443042000","regtill":"1632430800"}]}  200 =0.126406s  
{"list":[{"d":"abc","c":"1443042000"},{"d":"xyz","c":"1000000000"}]}  200 =0.126406s  

Is there a way to find in this stream of data anything that looks like a UNIX Epoch time (e.g., representing the recent times (any 10-digit number in quotes should do (1000000000 is 2001-09-09 as per env TZ=GMT-3 date -r1000000000 +%Y-%m-%dT%H%M%S%z with BSD date(1)))), and convert it all to ISO8601-like dates, with a small shell script snippet in perl or BSD awk without any extensive dependencies to do the transformation?

Desired Output (with or without timezone offsets):

{"message":"Domains list","list":[      {"domain":"example.org","created":"2015-09-24T000000+0300","regtill":"2021-09-24T000000+0300"}]}  200 =0.126406s  
{"list":[      {"d":"abc","c":"2015-09-24T000000+0300"},      {"d":"xyz","c":"2001-09-09T044640+0300"}]}  200 =0.126406s  

Calculate masklen from netmask string in PostgreSQL

Posted: 24 Sep 2021 09:06 AM PDT

I know this question has been asked before for different languages, but as far as I can see it relies on flow control ("for loops") and/or esoteric Perl functions.

So in PostgreSQL, I'm trying to write a database migration to convert our network information stored as text into proper inet types. Suppose my 'Foo' table has two columns, "address" which stores the IP address itself, and "netmask" which stores the "netmask" (e.g. '255.255.255.0'). I want to insert these into the single 'ip' field of a new 'Bar' table as a single inet-type column.

So far what I've got is pretty straightforward for converting the IP, but I'm struggling on the mask length. I assume it'll look something like:

INSERT INTO bar(ip)      SELECT set_masklen(address::inet, calculate_masklen_from_netmask(netmask))      FROM foo  ;  

... but I have no idea how to define that function calculate_masklen_from_netmask since I can't use flow control structures in a statement-based language.

RestTemplate.exchange() DELETE dropping request body

Posted: 24 Sep 2021 09:06 AM PDT

I'm experiencing a strange problem with the method below.

@Override  public String deleteToEe(String body) {           logger.debug("Request body");      logger.debug(body);      HttpHeaders headers = new HttpHeaders();      headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);      headers.add("partner", "test");      headers.add("api_key", "certxxxx");      HttpEntity<String> request = new HttpEntity<String>(body, headers);      ResponseEntity<String> result = null;      try {          result = restTemplate.exchange(targetUrl, HttpMethod.DELETE, request, String.class);      } catch (RestClientException e) {          // TODO Auto-generated catch block          e.printStackTrace();      }      return result.getBody();  }  

When I trigger this method through hitting the controller request mapping through Postman, it works. But when testers triggers this method through their integration tests, or when I trigger this method using curl

curl -X DELETE -H "Accept: application/json" -H "Content-type: application/json" -d "{"userName": "21", "courseId": "104882_bfaculty3_1024", "isbn": "9780323055", "schoolUserId": "1234" }" http://localhost:8080//api/provision  

I get a null pointer exception at this point in the code

result = restTemplate.exchange(targetUrl, HttpMethod.DELETE, request, String.class);  

I've breakpointed the code and looks like we have a request body but for some reason it' being dropped at the restTemplate.exchange() call. Anyone seen something like this before?

How do you change ansible_default_ipv4?

Posted: 24 Sep 2021 09:06 AM PDT

I'd like to change ansible_default_ipv4 to point to eth1 instead of eth0. Can I do this in either the playbook or via the --extra-vars option?

How do I save my data internally?

Posted: 24 Sep 2021 09:06 AM PDT

I am trying to create a "To Do List" and I have everything complete, except for saving the data. I am fairly new and wondering if anybody could show me how to accomplish saving data internally.

Here is my code:

Main_ToDoList.java

public class Main_ToDoList extends Activity implements OnClickListener  {  private Button btnAdd;  private EditText et;  private ListView lv;  ArrayList<String> list = new ArrayList<String>();  ArrayAdapter<String> adapter;    final Context context = this;    @Override  protected void onCreate(Bundle savedInstanceState)  {      super.onCreate(savedInstanceState);      setContentView(R.layout.main_activity);        btnAdd = (Button)findViewById(R.id.addTaskBtn);      btnAdd.setOnClickListener(this);      et = (EditText)findViewById(R.id.editText);      adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);        // set the lv variable to your list in the xml      lv=(ListView)findViewById(R.id.list);      lv.setAdapter(adapter);        // set ListView item listener      lv.setOnItemClickListener(new AdapterView.OnItemClickListener()      {          @Override          public void onItemClick(AdapterView<?> parent, View view, final int position, long id)          {              AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);              alertDialogBuilder.setTitle("Confirm Delete");              alertDialogBuilder.setMessage("Sure you want to delete?");              alertDialogBuilder.setCancelable(false);              alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener()              {                  @Override                  public void onClick(DialogInterface dialogInterface, int i)                  {                      adapter.remove(adapter.getItem(position));                  }              });              alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener()              {                  @Override                  public void onClick(DialogInterface dialogInterface, int i)                  {                      dialogInterface.cancel();                  }              });              AlertDialog alertDialog = alertDialogBuilder.create();              alertDialog.show();          }      });  }  public void onClick(View v)  {      String input = et.getText().toString();      if(input.length() > 0)      {          adapter.add(input);          et.setText("");      }  }  @Override  public boolean onCreateOptionsMenu(Menu menu)  {      // Inflate the menu; this adds items to the action bar if it is present.      getMenuInflater().inflate(R.menu.main__to_do_list, menu);      return true;  }   }  

How would I go about saving the data I enter? Thanks!

Shift elements in a linked list in java

Posted: 24 Sep 2021 09:06 AM PDT

I have to shift all of the tokens left by one position in a Linked List.

Here's my code for the method:

private LLNode<E> head;     // the first node in the list  private LLNode<E> tail;     // the last node in the list    public void shiftLeft()  {      LLNode<E> temp = new LLNode<E>();      temp = head;      head = head.next;      tail.next = temp;  }    /*from main method  TopSpinLinkedList<Integer> ll = new TopSpinLinkedList<Integer>(numTokens, spinSize);    //fills LinkedList with tokens  for(int i = 1; i <= numTokens; i++) {      ll.add(i);  }  */  

A nullpointer error appears during runtime when I call the method. Any help would be appreciated. Thanks.

How does one wait for an Internet Explorer 9 frame to load using VBA Excel?

Posted: 24 Sep 2021 09:06 AM PDT

There are many online resources that illustrate using Microsoft Internet Explorer Controls within VBA Excel to perform basic IE automation tasks. These work when the webpage has a basic construct. However, when webpages contain multiple frames they can be difficult to work with.

I need to determine if an individual frame within a webpage has completely loaded. For example, this VBA Excel code opens IE, loads a webpage, loops thru an Excel sheet placing data into the webpage fields, executes search, and then returns the IE results data to Excel (my apologies for omitting the site address).

The target webpage contains two frames:

1) The searchbar.asp frame for search value input and executing search

2) The searchresults.asp frame for displaying search results

In this construct the search bar is static, while the search results change according to input criteria. Because the webpage is built in this manner, the IEApp.ReadyState and IEApp.Busy cannot be used to determine IEfr1 frame load completion, as these properties do not change after the initial search.asp load. Therefore, I use a large static wait time to avoid runtime errors as internet traffic fluctuates. This code does work, but is slow. Note the 10 second wait after the cmdGO statement. I would like to improve the performance by adding solid logic to determine the frame load progress.

How do I determine if an autonomous frame has finished loading?

' NOTE: you must add a VBA project reference to "Internet Explorer Controls"  ' in order for this code to work  Dim IEapp As Object  Dim IEfr0 As Object  Dim IEfr1 As Object    ' Set new IE instance  Set IEapp = New InternetExplorer    ' With IE object  With IEapp      ' Make visible on desktop      .Visible = True      ' Load target webpage      .Navigate "http://www.MyTargetWebpage.com/search.asp"      ' Loop until IE finishes loading      While .ReadyState <> READYSTATE_COMPLETE          DoEvents      Wend  End With    ' Set the searchbar.asp frame0  Set IEfr0 = IEapp.Document.frames(0).Document     ' For each row in my worksheet  For i = 1 To 9999                        ' Input search values into IEfr0 (frame0)      IEfr0.getElementById("SearchVal1").Value = Cells(i, 5)      IEfr0.getElementById("SearchVal2").Value = Cells(i, 6)        ' Execute search      IEfr0.all("cmdGo").Click                ' Wait a fixed 10sec      Application.Wait (Now() + TimeValue("00:00:10"))        ' Set the searchresults.asp frame1      Set IEfr1 = IEapp.Document.frames(1).Document        ' Retrieve webpage results data      Cells(i, 7) = Trim(IEfr1.all.Item(26).innerText)      Cells(i, 8) = Trim(IEfr1.all.Item(35).innerText)    Next  

Find html element nearest to position (relative or absolute)

Posted: 24 Sep 2021 09:06 AM PDT

Given absolute or relative position (top & left) is there any way to get the nearest html element to these co-ordinates?

Or alternately, is there any way to craft a selector (or use some jQuery construct) to enumerate elements and then find which is closes to the provided co-ordinates? Assume that the set of elements is small and finite.

No comments:

Post a Comment