text:
Q: Robotium isn't scrolling to a text view I have the following layout in my fragment and activity:

As you can see, Robotium fills in the text for the EditText views. It also scrolls to and fills in the "Team" field which follows the "Player Name". However, there is a Spinner after that, with an appropriate label in a textView, and solo.searchForText() doesn't scroll down to put it into view. Is this because of the split Action Bar? What can I do to remedy this problem in my tests?
The relevant code that attempts to access the Spinner:
        Spinner playerPositionSpinner = (Spinner) solo.getView(R.id.player_position_text);
        @SuppressWarnings("unchecked")
        ArrayAdapter<CharSequence> playerPositionAdapter = (ArrayAdapter<CharSequence>) playerPositionSpinner
                .getAdapter();
        int newIndex = playerPositionAdapter.getPosition(card
                .getPlayerPosition());
        int currIndex = playerPositionSpinner.getSelectedItemPosition();

        boolean isPositionVisible = solo.searchText(
                solo.getString(R.string.player_position_label), true);
        solo.waitForView(R.id.player_position_text);

        boolean isConditionVisible = solo.searchText(solo.getString(R.string.condition_label),
                false);
        int index = -1;
        if (!isConditionVisible && isPositionVisible) {
            index = 0;
        }
        if (isPositionVisible && isConditionVisible) {
            index = 1;
        }

        Assert.assertFalse("Invalid index", index == -1);
        solo.pressSpinnerItem(index, newIndex - currIndex);

The XML layout for the form fragment:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@id/scroll_card_details"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:stretchColumns="1" >

        <TableRow>

            <CheckBox
                android:id="@id/autograph"
                android:text="@string/autograph_label"
                android:layout_span="2" />
        </TableRow>

        <TableRow>

            <TextView
                android:text="@string/condition_label"
                android:textStyle="bold" />

            <Spinner
                android:id="@id/condition"
                android:hint="@string/condition_hint"
                android:singleLine="true" />
        </TableRow>

        <TableRow>

            <TextView
                android:text="@string/brand_label"
                android:textStyle="bold" />

            <AutoCompleteTextView
                android:id="@id/brand_text"
                android:completionThreshold="1"
                android:hint="@string/brand_hint"
                android:inputType="textCapWords"
                android:selectAllOnFocus="true"
                android:singleLine="true" >

                <requestFocus />
            </AutoCompleteTextView>
        </TableRow>

        <TableRow>

            <TextView
                android:text="@string/year_label"
                android:textStyle="bold" />

            <EditText
                android:id="@id/year_text"
                android:hint="@string/year_hint"
                android:inputType="number"
                android:selectAllOnFocus="true"
                android:singleLine="true" />
        </TableRow>

        <TableRow>

            <TextView
                android:text="@string/number_label"
                android:textStyle="bold" />

            <EditText
                android:id="@id/number_text"
                android:hint="@string/number_hint"
                android:inputType="number"
                android:selectAllOnFocus="true"
                android:singleLine="true" />
        </TableRow>

        <TableRow>

            <TextView
                android:text="@string/value_label"
                android:textStyle="bold" />

            <EditText
                android:id="@id/value_text"
                android:hint="@string/value_hint"
                android:inputType="numberDecimal"
                android:selectAllOnFocus="true"
                android:singleLine="true" />
        </TableRow>

        <TableRow>

            <TextView
                android:text="@string/count_label"
                android:textStyle="bold" />

            <EditText
                android:id="@id/count_text"
                android:hint="@string/count_hint"
                android:inputType="number"
                android:selectAllOnFocus="true"
                android:singleLine="true" />
        </TableRow>

        <TableRow>

            <TextView
                android:text="@string/player_name_label"
                android:textStyle="bold" />

            <AutoCompleteTextView
                android:id="@id/player_name_text"
                android:completionThreshold="1"
                android:hint="@string/player_name_hint"
                android:inputType="textCapWords"
                android:selectAllOnFocus="true"
                android:singleLine="true" />
        </TableRow>

        <TableRow>

            <TextView
                android:text="@string/team_label"
                android:textStyle="bold" />

            <AutoCompleteTextView
                android:id="@id/team_text"
                android:completionThreshold="1"
                android:hint="@string/team_hint"
                android:inputType="textCapWords"
                android:selectAllOnFocus="true"
                android:singleLine="true" />
        </TableRow>

        <TableRow>

            <TextView
                android:text="@string/player_position_label"
                android:textStyle="bold" />

            <Spinner
                android:id="@id/player_position_text"
                android:hint="@string/player_position_hint"
                android:singleLine="true" />
        </TableRow>

    </TableLayout>

</ScrollView>

A: Apparently Robotium finds the Ad, instead of the ScrollView. Robotium doesn't know how to deal with it and just ignores it instead of causing any error.
I ending up writing my own function to do the scrolling:
public static void scrollDown(final ScrollView scrollView) {
    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.arrowScroll(ScrollView.FOCUS_DOWN);
        }
    });
}

A: Have you tried:
solo.pressSpinnerItem(0, 1);

The first parameter is the index of the spinner to use and the second parameter is the item in the spinner to select.


text:
Q: Apache Storm Flux Simple KafkaSpout --> KafkaBolt NullPointerException I'm using Apache Storm 0.10.0-beta1 and started converting some topologies to Flux. I decided to start with a simple topology that reads from a Kafka queue and writes to a different Kafka queue. I get this error, which I am having a difficult time figuring out what is wrong.  The topology yaml file follows the error.
Parsing file: /Users/frank/src/mapper/mapper.yaml
388  [main] INFO  o.a.s.f.p.FluxParser - loading YAML from input stream...
391  [main] INFO  o.a.s.f.p.FluxParser - Not performing property substitution.
391  [main] INFO  o.a.s.f.p.FluxParser - Not performing environment variable substitution.
466  [main] INFO  o.a.s.f.FluxBuilder - Detected DSL topology...
Exception in thread "main" java.lang.NullPointerException
at org.apache.storm.flux.FluxBuilder.canInvokeWithArgs(FluxBuilder.java:561)
at org.apache.storm.flux.FluxBuilder.findCompatibleConstructor(FluxBuilder.java:392)
at org.apache.storm.flux.FluxBuilder.buildObject(FluxBuilder.java:288)
at org.apache.storm.flux.FluxBuilder.buildSpout(FluxBuilder.java:361)
at org.apache.storm.flux.FluxBuilder.buildSpouts(FluxBuilder.java:349)
at org.apache.storm.flux.FluxBuilder.buildTopology(FluxBuilder.java:84)
at org.apache.storm.flux.Flux.runCli(Flux.java:153)
at org.apache.storm.flux.Flux.main(Flux.java:98)

Topology yaml:
name: "mapper-topology"
config:
  topology.workers: 1
  topology.debug: true
  kafka.broker.properties.metadata.broker.list: "localhost:9092"
  kafka.broker.properties.request.required.acks: "1"
  kafka.broker.properties.serializer.class: "kafka.serializer.StringEncoder"

# component definitions
components:
  - id: "topicSelector"
    className: "storm.kafka.bolt.selector.DefaultTopicSelector"
    constructorArgs:
      - "schemaq"
  - id: "kafkaMapper"
    className: "storm.kafka.bolt.mapper.FieldNameBasedTupleToKafkaMapper"

# spout definitions
spouts:
  - id: "kafka-spout"
    className: "storm.kafka.SpoutConfig"
    parallelism: 1
    constructorArgs:
      - ref: "zkHosts"
      - "mapperq"
      - "/mapperq"
      - "id-mapperq"
    properties:
      - name: "forceFromStart"
        value: true
      - name: "scheme"
        ref: "stringMultiScheme"

# bolt definitions
bolts:
  - id: "kafka-bolt"
    className: "storm.kafka.bolt.KafkaBolt"
    parallelism: 1
configMethods:
  - name: "withTopicSelector"
    args: [ref: "topicSelector"]
  - name: "withTupleToKafkaMapper"
    args: [ref: "kafkaMapper"]

# streams
streams:
  - name: "kafka-spout --> kafka-bolt"
    from: "kafka-spout"
    to: "kafka-bolt"
    grouping:
      type: SHUFFLE

And here is the command:
storm jar /Users/frank/src/mapper/target/mapper-0.1.0-SNAPSHOT-standalone.jar org.apache.storm.flux.Flux --local mapper.yaml

A: spout classname should be storm.kafka.KafkaSpout, not storm.kafka.SpoutConfig. You should define SpoutConfig to "components" section, and let spout refer this.
You can refer https://github.com/apache/storm/blob/master/external/flux/flux-examples/src/main/resources/kafka_spout.yaml to see how to setup KafkaSpout from flux.

redpajama_set_name: RedPajamaStackExchange


text:
Q: react address lookup issue with changing final input value I am building an address lookup functionality for an app, and my previous 2 questions have thus far, been unable to garner an answer. I am on the last step, and need to figure this out, so I turn to you stack overflow.
I start with an input, a button and a target input:
<input type='text' name='postcode-lookup' onChange={this.postcodeChange} />

<button onClick={this.searchPostcode}>Search</button>

<input type='text' name='target-for-data' />

Easy enough. Now for the functions attached to both of those elements:
postcodeChange = {e} => {
    this.setState({'postcode': e.target.value});
}

searchPostcode = () => {
    this.setState({'visible': true});

    if(this.state.postcode.length . 0){
        Axios.get('postcode look up api here')
        .then(response => {
            this.setState({'response': response.data});
        })
    }
}

Ok here, we have 3 state items: postcode, which we will set to an empty string '', visible, which is initially set to true, and response, which is an empty array, that we then populate with the response data of address objects.
My next step, was to display those addresses, so inside the render, I set a const that maps over the response array like so:
const result = this.state.response.map((item) => {
    if(this.state.visible === true){
        return(

{item.address1Field}

        )
    }else {

    }
})

Ok, so when we click the button, it will return a p tag filled with address data from the array. This also has a function, which is where my problem lies.
Inside of this function I set the visible state item to false, so that the addresses disappear. Easy enough.
But how do I then take the address that I clicked on, and populate it into the original input we started with?
I have tried many things, from setting the state in addressClick, targeting the innerHTML, e.target.value, e.target.innerHTML, and so on and so on for hours.
Any takers? Ideas?


text:
Q: SELECT the matching condition value along with the result from a multiple condition WHERE clause on the same column I think this is a pretty simple question but I can't figure out the right search terms to search this. This question is the most similar I could find, but it's the opposite of what I'm trying to do.
I have a query like this :
SELECT * FROM table WHERE column LIKE "val1%" OR column LIKE "val2%" OR column LIKE "val3%", ...so..on..and..on

Since it's an OR, only some of them will give matches from the column.
How can I return the matching LIKE clause with the query itself ? Like this :
SELECT *, (val1 or val2 or val3 - the matched val) FROM table WHERE column LIKE "val1%" OR column LIKE "val2%" OR column LIKE "val3%", ...so..on..and..on

Since the matching is by wildcard "%", I need to get the exact value that got the match.
If the table is this :

name
age

Mike
1

John
2

Michael
3

Milinda
4

And if the query is :
SELECT *, (the matched value) FROM table WHERE name LIKE "Mik%" OR name LIKE "Mic%" OR name LIKE "mia%"

It would return :

name
age
match

Mike
1
Mik

Michael
3
Mic

Is this possible purely with an SQLite query ? I know this can be done later after obtaining the results, but want to remove that redundancy since SQLite will already be matching anyway.
Note: The table is very large. 100,000+ rows. So performance is a big factor to get result as fast as possible. Also the OR conditions can be 5 or 10 or 15+

A: You may use a case expresssion. See working fiddle below:
Schema (SQLite v3.30)
CREATE TABLE my_table (
  `name` VARCHAR(7),
  `age` INTEGER
);

INSERT INTO my_table
  (`name`, `age`)
VALUES
  ('Mike', '1'),
  ('John', '2'),
  ('Michael', '3'),
  ('Milinda', '4');

Query #1
SELECT
     *,
     CASE
         WHEN  name LIKE "Mik%" THEN "Mik"
         WHEN  name LIKE "Mic%" THEN "Mic"
         WHEN  name LIKE "mia%" THEN "mia"
     END as matched_value
FROM
     my_table
WHERE
    name LIKE "Mik%" OR
    name LIKE "Mic%" OR
    name LIKE "mia%";

name
age
matched_value

Mike
1
Mik

Michael
3
Mic

View on DB Fiddle

A: Create a CTE with all the match strings that you have and join to the table:
WITH cte(match) AS (VALUES ('Mik'), ('Mic'))
SELECT t.*, c.match
FROM tablename t INNER JOIN cte c
ON t.name LIKE c.match || '%'

See the demo.


text:
Q: How do I change my "1" into "Period" in C#? This is the current output from my program:
Numbers in the table are in Millions
-------------------------------------------
1          4          5          6
-------------------------------------------
7          131.6      140.7      150.4
8          136.9      147.7      159.4
9          142.3      155.1      168.9
10         148        162.9      179.1
-------------------------------------------

My intention for variable i is to keep it in the first line, so I just lock the value in 1. But I want to change the display as seen above to the string, "Period", instead of 1.
Code:
//header
listBoxResult.Items.Add("Numbers in the table are in Millions");
listBoxResult.Items.Add("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
for (int i = 1; i <= 1; i++)
{
    string headerRow = i.ToString();
    for (int j = interestStart; j <= interestEnd; j++)
    {
        headerRow += "\t" + j;
    }
    listBoxResult.Items.Add(headerRow);
}
listBoxResult.Items.Add("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
//calculation

How can I do this?


text:
Q: Python - read from a remote logfile that is updated frequently I have a logfile that is written constantly on a remote networking device (F5 bigip). I have a Linux hopping station from where I can fetch that log file and parse it. I did find a solution that would implement a "tail -f" but I cannot use nice or similar to keep my script running after I log out. What I can do is to run a cronjob and copy over the file every 5 min let's say. I can process the file I downloaded but the next time I copy it it will contain a lot of common data, so how do I process only what is new? Any help or sugestions are welcome!

A: Two possible (non-python) solutions for your problems. If you want to keep a script running on your machine after logout, check nohup in combination with & like:
nohup my_program & > /dev/null
On a linux machine you can extract the difference between the two files with
grep -Fxv -f old.txt new.txt > dif.txt
This might be slow if the file is large. The dif.txt file will only contain the new stuff and can be inspected by your program. There also might be a solution involving diff.


text:
Q: Slicing array into 2 parts I have an array of N elements.
x = [ 1  , 2, ....... , N]

How can i split it into 8:2 arrays?
The first array should have 80% elements and the second rest.

A: In order to calculate the ratio, you need to first find the length of the list x:
len(x)

To find 80% of the list, multiply the length by 80%:
len(x)*.8

This will return a float. You need to convert it into an int for list slicing:
int(len(x)*.8)

Next you need to slice the list. Here is a good resource on the basics of list slicing. It will look something like this:
x[:int(len(x)*.8)]

See if you can figure out how to make the second list for the remaining 20%.

A: first enter any list
x=[1,2,3....n]
then do this function
y=(Len(x) * 4) // 5
then split it to 2 lists
a=x[0:y]
b=x[-(Len(x)-y):]


text:
Q: schema does not exist error with Postgresql and Texticle I tried to configure Texticle and ran into this error on migration. Error msg is referring to the line I marked with <<<<
PGError: ERROR:  schema "half_links" does not exist
:       CREATE VIEW searches AS
    SELECT items.id AS searchable_id, items.name AS term,
      CAST('Item' AS varchar) AS searchable_type
    FROM items
    UNION
    SELECT half_links.id AS searchable_id, half_links.item.name AS term,     <<<<
      CAST('HalfLink' AS varchar) AS searchable_type
    FROM half_links

This is my migration
class CreateSearches < ActiveRecord::Migration
  def self.up
   ActiveRecord::Base.connection.execute <<-SQL
    CREATE VIEW searches AS
     SELECT items.id AS searchable_id, items.name AS term,
       CAST('Item' AS varchar) AS searchable_type
     FROM items
     UNION
     SELECT half_links.id AS searchable_id, half_links.item.name AS term,
       CAST('HalfLink' AS varchar) AS searchable_type
     FROM half_links
   SQL
 end

and models
:half_link belongs_to :item
:item has_many :half_links

Im running this on my localhost PSQL. How can I get around this?

A: The error is in the second select. half_links.item.name makes Postgres assume that half_links is a schema name (the correct syntax is ..)
Seeing how your associations are, I guess you mean to get the name of the items belonging to half_links.
Since Postgres have no idea on how the Rails associations works, you need to get the data yourself:
CREATE VIEW searches AS
     SELECT items.id AS searchable_id, items.name AS term,
       CAST('Item' AS varchar) AS searchable_type
     FROM items
     UNION
     SELECT half_links.id AS searchable_id, items.name AS term,
       CAST('HalfLink' AS varchar) AS searchable_type
     FROM half_links join items on half_links.item_id = items.id

This is assuming that the foreign key in half_links to items are called item_id which it should be if you created the tables using Rails migration.
Additionally, this will only show the half_links that actually have an item associated to it, if there can be ones that don't have an item, then change the join to outer join. Term will in those cases be NULL.


text:
Q: Vector out of bounds while reading a TXT file I'm trying to read the values of a .TXT file and store these values in various vectors (the values in the file are separated by a comma, I'm using .Split () method to get these values), the problem that is appearing to me is that my vector aux is exceeding the limit after the first writing.
The code:
String[] iltxt = new String[49];
String[] ertxt = new String[49];
String[] tcsetxt = new String[49];
String[] arttxt = new String[49];
String[] rmtxt  = new String[49];
String[] burtxt  = new String[49];
String[] toftxt = new String[49];
String[] atgtxt = new String[49];
String[] nrtxt = new String[49];
String[] hlab27txt = new String[49];
String[] djtxt = new String[49];
String[] dltxt = new String[49];
String[] rctxt = new String[49];
String[] dctxt = new String[49];
String[] mobtxt = new String[49];
String[] dtstxt = new String[49];
String[] sintxt = new String[49];
String[] diagnosticotxt = new String[49];
String[] aux = new String[18];
int cont = 1;
      try {
      FileReader arq = new FileReader("File.txt");
      BufferedReader lerArq = new BufferedReader(arq);
      String linha = lerArq.readLine();
      aux = linha.split(",");
      //STORES THE VALUES OF THE FIRST LINE INTO THE VECTORS
      dltxt[0] = aux[0];
      rctxt[0] = aux[1];
      dctxt[0] = aux[2];
      mobtxt[0] = aux[3];
      dtstxt[0] = aux[4];
      iltxt[0] = aux[5];
      ertxt[0] = aux[6];
      tcsetxt[0] = aux[7];
      arttxt[0] = aux[8];
      rmtxt[0] = aux[9];
      burtxt[0] = aux[10];
      toftxt[0] = aux[11];
      sintxt[0] = aux[12];
      atgtxt[0] = aux[13];
      nrtxt[0] = aux[14];
      hlab27txt[0] = aux[15];
      djtxt[0] = aux[16];
      diagnosticotxt[0] = aux[17];
      //CLEAN THE VECTOR AUX TO THE NEXT READ
      aux = null;
      while (linha != null) {
            //READ THE VALUES OF THE SECOND TO THE LAST LINE AND STORES INTO THE VECTORS
            linha = lerArq.readLine();
            aux = linha.split(",");
            dltxt[cont] = aux[0];
            rctxt[cont] = aux[1];
            dctxt[cont] = aux[2];
            mobtxt[cont] = aux[3];
            dtstxt[cont] = aux[4];
            iltxt[cont] = aux[5];
            ertxt[cont] = aux[6];
            tcsetxt[cont] = aux[7];
            arttxt[cont] = aux[8];
            rmtxt[cont] = aux[9];
            burtxt[cont] = aux[10];
            toftxt[cont] = aux[11];
            sintxt[cont] = aux[12];
            atgtxt[cont] = aux[13];
            nrtxt[cont] = aux[14];
            hlab27txt[cont] = aux[15];
            djtxt[cont] = aux[16];
            diagnosticotxt[cont] = aux[17];
            //CLEAN THE AUX VECTOR
            aux = null;
            //INCREMENT THE COUNTER TO SAVE VALUES IN THE NEXT POSITIONS OF THE VECTORS
            cont++;
      }
      arq.close();
      } catch (IOException e) {
            System.err.printf("Error while open the file: %s.\n",
            e.getMessage());
      }

The values of the TXT File:
Sim,Sim,Sim,Ilimitado,Sim,Ausente,Moderado,Moderado,Não,Não,Não,Não,Não,Não,Não,Negativo,Não,Espondilite Anquilosante

Não,Não,Não,Normal,Não,Ausente,Moderado,Não,Sim,Não,Não,Não,Não,Sim,Não,Não,Não,Artrite de Gota

Não,Não,Não,Limitado,Não,Ausente,Moderado,Não,Não,Não,Não,Sim,Não,Sim,Não,Não,Não,Artrite de Gota

Não,Não,Não,Normal,Não,Moderado,Importante,Moderado,Não,Não,Não,Não,Não,Sim,Não,Não,Não,Artrite Reumatica

Não,Não,Não,Limitado,Não,Muito Importante,Muito Importante,Importante,Sim,Não,Não,Sim,Sim,Sim,Não,Não,Não,Artrite de Gota

Não,Não,Não,Limitado,Não,Moderado,Muito Importante,Não,Sim,Não,Não,Não,Sim,Sim,Não,Não,Não,Artrite Reumática

Sim,Não,Sim,Normal,Sim,Moderado,Importante,Importante,Não,Não,Não,Não,Não,Não,Não,Positivo,Não,Espondilite Anquilosante

Sim,Sim,Sim,Limitado,Sim,Moderado,Importante,Não,Não,Não,Não,Não,Não,Não,Não,Positivo,Não,Espondilite Anquilosante

Não,Não,Não,Limitado,Não,Muito Importante,Ausente,Não,Sim,Não,Não,Não,Sim,Sim,Não,Não,Não,Artrite de Gota

Não,Não,Não,Limitado,Não,Importante,Ausente,Leve,Sim,Sim,Não,Não,Sim,Sim,Não,Negativo,Não,Artrite Reumatica

Sim,Não,Não,Normal,Não,Leve,Muito Importante,Não,Não,Não,Não,Não,Não,Não,Não,Negativo,Não,Espondilite Anquilosante

Não,Não,Não,Normal,Não,Leve,Importante,Não,Sim,Sim,Não,Não,Sim,Sim,Não,Não,Não,Artrite Reumática

Sim,Não,Não,Normal,Não,Moderado,Ausente,Não,Sim,Não,Não,Não,Sim,Sim,Não,Positivo,Não,Espondilite Anquilosante

Não,Não,Não,Limitado,Não,Importante,Ausente,Moderado,Sim,Sim,Não,Não,Sim,Sim,Não,Não,Sim,Artrite Reumatica

Sim,Sim,Não,Normal,Sim,Ausente,Moderado,Leve,Não,Sim,Não,Não,Não,Não,Não,Positivo,Não,Espondilite Anquilosante

Sim,Não,Sim,Normal,Não,Ausente,Importante,Não,Não,Não,Não,não,Não,Não,Não,Positivo,Não,Espondilite Anquilosante

Não,Não,Não,Normal,Não,Importante,Ausente,Não,Não,Não,Sim,Não,Não,Sim,Sim,Não,Não,Artrite Reumatica

Sim,Sim,Não,Normal,Não,Leve,Importante,Importante,Não,Não,Não,Não,Não,Não,Não,Positivo,Não,Espondilite Anquilosante

Não,Não,Não,Limitado,Não,Moderado,Moderado,Moderado,Sim,Não,Não,Não,Não,Sim,Não,Não,Não,Artrite de Gota

Não,Não,Não,Limitado,Não,Importante,Importante,Moderado,Sim,Não,Sim,Sim,Sim,Sim,Não,Não,Não,Artrite de Gota

Não,Não,Não,Normal,Não,Importante,Importante,Não,Sim,Sim,Sim,Sim,Não,Sim,Não,Não,Não,Artrite de Gota

Sim,Sim,Não,Normal,Sim,Ausente,Importante,Importante,Não,Sim,Não,Não,Não,Sim,Não,Positivo,Não,Espondilite Anquilosante

Não,Não,Não,Normal,Não,Importante,Moderado,Não,Sim,Não,Sim,Sim,Sim,Sim,Não,Não,Não,Artrite de Gota

Não,Não,Não,Limitado,Não,Moderado,Ausente,Não,Não,Não,Sim,Sim,Não,Não,Não,Não,Não,Artrite de Gota

Não,Não,Não,Normal,Não,Importante,Importante,Não,Sim,Não,Não,Não,Sim,Sim,Não,Negativo,Não,Artrite Reumatica

Não,Não,Não,Limitado,Não,Importante,Moderado,Moderado,Sim,Não,Não,Não,Sim,Sim,Não,Não,Não,Artrite Reumatica

Sim,Não,Não,Normal,Não,Moderado,Importante,Não,Não,Não,Não,Não,Não,Não,Não,Positivo,Não,Espondilite Anquilosante

Não,Não,Não,Limitado,Não,Ausente,Ausente,Não,Sim,Não,Não,Não,Sim,Sim,Não,Negativo,Não,Artrite Reumática

Sim,Sim,Não,Limitado,Sim,Leve,Importante,Não,Não,Sim,Não,Não,Não,Não,Não,Negativo,Não,Espondilite Anquilosante

Não,Não,Não,Limitado,Não,Importante,Moderado,Não,Sim,Sim,Não,Não,Sim,Sim,Não,Não,Não,Artrite Reumatica

Sim,Sim,Não,Limitado,Não,Importante,Moderado,Não,Não,Não,Não,Não,Não,Não,Não,Positivo,Não,Espondilite Anquilosante

Sim,Não,Não,Normal,Não,Ausente,Moderado,Moderado,Não,Não,Não,Não,Não,Sim,Não,Não,Não,Artrite de Gota

Não,Não,Não,Limitado,Não,Moderado,Moderado,Não,Sim,Sim,Sim,Sim,Sim,Sim,Não,Não,Não,Artrite de Gota

Sim,Sim,Não,Limitado,Sim,Importante,Muito Importante,Importante,Sim,Sim,Não,Não,Sim,Sim,Não,Não,Não,Artrite Reumatica

Não,Não,Não,Limitado,Não,Muito Importante,Ausente,Moderado,Sim,Sim,Não,Não,Sim,Sim,Sim,Não,Não,Artrite Reumática

Não,Não,Não,Limitado,Não,Leve,Moderado,Não,Sim,Não,Não,Não,Sim,Sim,Não,Não,Não,Artrite Reumatica

Não,Não,Não,Limitado,Não,Moderado,Não,Sim,Não,Não,Sim,Não,Sim,Não,Não,Não,Artrite de Gota

Sim,Sim,Sim,Limitado,Não,Moderado,Muito Importante,Moderado,Sim,Não,Não,Não,Não,Sim,Não,Positivo,Sim,Espondilite Anquilosante

Não,Não,Não,Normal,Não,Leve,Importante,Não,Sim,Não,Não,Sim,Sim,Sim,Não,Não,Não,Artrite de Gota

Sim,Não,Não,Normal,Não,Ausente,Moderado,Moderado,Não,Não,Não,Não,Não,Sim,Não,Positivo,Não,Espondilite Anquilosante

Sim,Sim,Não,Normal,Não,Ausente,Ausente,Não,Não,Sim,não,Não,Não,Sim,não,Não,Não,Artrite Reumatica

Sim,Sim,Sim,Normal,Não,Ausente,Importante,Não,Não,Não,Não,Não,Não,Não,Não,Positivo,Não,Espondilite Anquilosante

Sim,Não,Não,Normal,Sim,Moderado,Importante,Não,Não,Sim,Não,Não,Não,Não,Não,Positivo,Não,Espondilite Anquilosante

Não,Não,Não,Limitado,Não,Leve,Importante,Não,Sim,Sim,Não,Não,Sim,Sim,Não,Não,Não,Artrite Reumatica

Não,Não,Não,Limitado,Não,Leve,Moderado,Não,Sim,Sim,Não,Não,Sim,Sim,Não,Não,Não,Artrite Reumatica

Não,Não,Não,Limitado,Não,Moderado,Importante,Não,Sim,Não,Não,Não,Sim,Sim,Não,Não,Não,Artrite Reumatica

Não,Não,Não,Normal,Não,Importante,Importante,Não,Não,Sim,Não,Não,Não,Sim,Não,Não,Não,Artrite Reumatica

Sim,Não,Não,Normal,Não,Leve,Importante,Não,Sim,Não,Não,Não,Sim,Sim,Não,Não,Não,Artrite de Gota

Não,Não,Não,Normal,não,Moderado,Importante,Não,Não,Sim,Não,não,Não,Sim,Não,Não,Não,Artrite Reumatica

The error that appears while executing the code:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1

The line of the error:
rctxt[cont] = aux[1];

Someone knows how to fix this? (Sorry about some words in portugues, I am from Brazil)

A: Looks like some of the lines do not have any text (empty lines).
The split on these lines will not produce an 18 length Strings array.
try
if (arr.length < 18)
   continue;

Also as mentioned above, having an Object that encapsulates this data would make you code a lot more readable.
Edit
For clarification
You have this code
 while (linha != null) {
        linha = lerArq.readLine();
        aux = linha.split(",");

now check the size of the aux array and if not 18 then skip this line
    if (aux.length < 18) {
       System.err.println (linha + " does not have enough values");
       continue;
    }

A: The exception happens because you seperated the lines with empty lines and you
do not check if there are actually 18 tokens.
Either you remove those empty lines or you add a condition like so:
linha = lerArq.readLine();

aux = linha.split(",");
if(aux.length != 18)
    continue;

Also you have a little problem with one of your lines (35). That line has just 17 tokens and causes the next ArrayOutOfBoundsException if you do not use the condition but remove the empty lines in your File.txt


text:
Q: INSERT INTO / SELECT DISTINCT results in primary key violation for a SYS_GUID I had some problems bulk inserting data from another table into a new one. The target looked somewhat like this:
CREATE TABLE TEST_T (
      T_GUID RAW(16) DEFAULT SYS_GUID() NOT NULL,
      T_VAL1 NUMBER(10) NOT NULL,
      T_VAL2 VARCHAR2(10) NOT NULL,
      PRIMARY KEY (T_GUID)
)

The simplified version of the statement I intended to fill it with data:
INSERT INTO TEST_T (T_VAL1, T_VAL2)
SELECT DISTINCT
     CAST(SUBSTR(zip_code, 1,1) AS NUMBER) as  t_val1,
     zip_code as t_val2
FROM OTHER_TABLE_T
WHERE ...
ORDER BY t_val1

As I'm not providing a T_GUID valued, I would've assumed that I get one provided by the SYS_GUID function for each new line. But something is going wrong, and I get a uniqueness constraint violation for the primary key.
If I remove the DISTINCT, the statement succeeds, but I get lots of duplicate entries. And, of course, if I explicitly provide a SYS_GUID() call in my SELECT, that has exactly the same result.
Now I found that if I simply put another SELECT around mine, it works out alright, no constraint violations and the distinct rows get inserted:
INSERT INTO ...
SELECT x.* FROM (
    SELECT DISTINCT ...
) x

So where do the duplicate guids come from? If the full set of rows doesn't have problems, why would removing rows via distinct cause trouble? As SYS_GUID creates a unique identifier for each call, I could only imagine that in the distinct case it only gets called once for the whole clause, which is solved by the surrounding wrapping SELECT. I'd be very happy if someone could explain how the execution differs in that case.

A: Try something like this:
insert into test_t(t_guid, t_val1, t_val2)
  select sys_guid(), t_val1, t_val2
    from (select distinct to_number(substr(zip_code, 1, 1)) as t_val1, zip_code as t_val2
            from other_table_t
           where ...)

A: Replace CAST with to_number() and add guid. Test your select first, then insert...:
SELECT DISTINCT
    sys_guid() guid
    To_Number(SUBSTR(zip_code, 1,1)) as  t_val1,
    zip_code as t_val2
 FROM OTHER_TABLE_T
/

Distinct GUID example:
SELECT sys_guid() gid, deptno
  FROM
 (
 SELECT distinct deptno FROM scott.emp
 )
ORDER BY deptno
/

GID                                 DEPTNO
-------------------------------------------
DC9B9132492C1A45E04011AC3EEB463A    10
DC9B9132492B1A45E04011AC3EEB463A    20
DC9B9132492A1A45E04011AC3EEB463A    30


text:
Q: grep with ^ (caret) doesn't work in the first line I would like to catch all section part with 'grep' command. However, I can't match my expression to the file in the first line but does well in the other line. I found the problem may be related to the file type but I don't know how to solve it if I'm not allowed to modify the file type. I'm begging for a solution.Thanks.
$> file test.ini
test.ini: UTF-8 Unicode (with BOM) text

$> cat test.ini
[isp_info]
reg_img_widthm1 = 100
[isp_blc0]
reg_blc_enable = 0
[isp_dpc0]
reg_dpc_enable = 0

$> grep '^\[.*]$' test.ini
[isp_blc0]
[isp_dpc0]

However
$> file test.ini.ascii
test.ini.ascii: ASCII text

$> cat test.ini.ascii
[isp_info]
reg_img_widthm1 = 100
[isp_blc0]
reg_blc_enable = 0
[isp_dpc0]
reg_dpc_enable = 0

$> grep '^\[.*]$' test.ini.ascii
[isp_info]
[isp_blc0]
[isp_dpc0]

A: If do not mind the BOM included in the first result, you may add an optional BOM pattern at the start of the regex:
grep -E $'^(\xEF\xBB\xBF)?\[.*]$' file

Or BRE POSIX compliant:
grep $'^\(\xEF\xBB\xBF\)\{0,1\}\[.*]$' file

Pattern details

*

*^ - start of a string

*(\xEF\xBB\xBF)? (= \(\xEF\xBB\xBF\)\{0,1\} BRE) - an optional sequence of UTF8 BOM symbols

*\[ -  a [

*.* - any 0+ chars

*] - a ] char

*$ - end of the line

Alternatively, remove BOM and run your grep command:
sed '1s/^\xEF\xBB\xBF//' file | grep '^\[.*]$'


text:
Q: Trouble printing over the internet through router to private network I am trying to send a print job from anywhere to a home network via its public IP address (I tried with and without a port number added ex. 40.230.2.2:9100), normal port number for RAW being 9100. I have a port forward setup on the router (which is a Verizon router/fiber modem) and still unable on my Windows 10 machine from outside the private network to "see" the printer for driver setup. I also created a port forward for SNMP to no success, yet when I forward port 80 to the printer I can pull its admin screen up from a browser. What am I missing to print from outside a private network? Also how might I setup printing through IPP, using the printer URI?

A: Windows cant see your printer in the internet, you must show it...

*

*go to devices & printers on control panel

*select any printer

*select from window menu printer server properties

*go to ports tab

*add standard tcp port witch global IP (to router with port forwarding)

*install manually printer or connect to net with printer and install it ( disconnect from net with printer)

*go to printer properties

*select tab ports

*select added port, apply

*go to general tab and try print test page

The printer must have configured correct gateway
to IPP printer forward 631 port
ports from article How Network Printing Works  :
Service Name                             UDP                 TCP
Services for Macintosh (uses AppleTalk)  201, 202, 204, 206  201, 202, 204, 206
Internet Printing Protocol (uses HTTP)   80                  80
NWLink (uses IPX/SPX)                    213                 213
LPDSVC (accepts LPR)                     515                 515
LPR Port (sends LPR)                     721-731, >1023      721-731, >1023
Server (using SMB)                       137, 138            139
Server (using RPC)                       530                 530
Standard Port Monitor (using SNMP)       161, 162            161, 162
Standard Port Monitor (using LPR)        > 1023              > 1023
Standard Port Monitor (using RAW)        2000, 2501-2503,    2000, 2501, 2503,
                                         3001, 6869, >=9100  3001, 6869, >=9100


text:
Q: Is it possible to create an Azure Service Principal with the Pulumi? I have a Pulumi Python code that creates some Azure resources. Insted of I user User Account to create resource, I created an Azure Service Principal with Powershell and authenticate with the below method:
pulumi config set azure-native:clientId <clientID>
pulumi config set azure-native:clientSecret <clientSecret> --secret
pulumi config set azure-native:tenantId <tenantID>
pulumi config set azure-native:subscriptionId <subscriptionID>

Now, I want to know Is it possible to create an Azure Service Principal with Pulumi and after that authenticate with Service Principal has been created?
Other Question, Is it the true way?
Edit:
As these documents Service Principal
My code is:
import pulumi
from pulumi.output import Output
import pulumi_azure_native as azure_native
import pulumi_azuread as azuread

current = azuread.get_client_config()
example_application = azuread.Application("exampleApplication",
                                          display_name="example",
                                          owners=[current.object_id])
example_service_principal = azuread.ServicePrincipal("exampleServicePrincipal",
                                                     application_id=example_application.application_id,
                                                     app_role_assignment_required=False,
                                                     owners=[current.object_id])

I received this error. Also I install with pip install pulumi-azuread
 ModuleNotFoundError: No module named 'pulumi_azuread'

A: You certainly can, using the Service Principal resource as part of the Azure Active Directory Provider.
You'll need to define an application first, but in typescript it would look something like:
import * as azuread from "@pulumi/azuread";

const application = new azuread.Application(`application`, {
      displayName: `application`,
});

const servicePrincipal = new azuread.ServicePrincipal(`servicePrincipal`, {
      applicationId: application.applicationId,
});


text:
Q: iOS: Why custom view controller? So far I came across many developers are using Custom view controllers instead of .xib file often. Can anyone tell me that which one is the best way? using custom or static?

A: It's your wish, use what ever you feel is easy for you. I prefer custom , because it gives me much more freedom to play with my custom views. Yes it is much more laborious , but you have more control over it(what i personally feel).
It would be great if you elaborate your question...
here is a small example where i used custom. The data to create views (like textfields , buttons etc) was being provided to me in form of XML (from server). So this XML can be changed any time at server end. which means  if my view is rendering 3 textfields today, on changing xml it shows 10 textfields. So if your view is not static or fixed, you should use custom method.
In IN SHORT - fixed or static view -use xib (you can use custom also). in case of dynamic,you can (should) do it programmatically.

A: if you are designing UI with code (not using Xib/Stotyboard) this will be good when you create UI dynamically so then you need not to spend more time on changes. what ever we use for development (Code/Xib/Storyboard) nothing will be changed in performance. As per user/developer comfort we will go for it. Suppose there are lot of UI need to be displayed few at the time viewdidload and rest after some button action then usually at the initially stage itself Xib and Story board will load all of them and hides un wanted and as per actions it will show the hidden UI. i feel coding is better for me.


text:
Q: FileEasy-Upload-Script path I need a good and easy php file upload system with admin panel to manage the uploads.
i found this: FileEasy-Upload-Script (https://github.com/asadhaider/FileEasy-Upload-Script)
It look very awesome, but there is one problem, and its the path.
I need to have it on http://example.com/upload file but it keep sending me to domain.com ???
Any one can help?
Here is the link of my upload system uhttp://wewrap.dk/upload/
The guy who uploaded that system is not responsing :-(
(sorry my english)

A: <?php
$connection=mysqli_connect("localhost","root","","imgup");
if(isset($_POST['create_post'])){
    $post_image = $_FILES['image']['name'];
    $post_image_temp = $_FILES['image']['tmp_name'];
    move_uploaded_file($post_image_temp, "images/$post_image");
    $query = "INSERT INTO img(post_image) ";
    $query .= "VALUES('{$post_image}')";
    $create_post_query = mysqli_query($connection, $query);
}
?>
<form action="fileup.php" method="post" enctype="multipart/form-data">

        <label for="post_image">Post Image</label>
        <input type="file"  name="image">
        <input type="submit" name="create_post" value="Publish">

</form>

A: this is an awsome tutorial for file upload using ajax you must try this https://www.youtube.com/watch?v=EraNFJiY0Eg


text:
Q: Does spring-rsocket support return a RejectedSetupException in @ConnectMapping annotated method? I follow the spring-rsocket-demo project to complete my code. I add some authentication logic in my server side code as follows. You can see I throw a exception in the after the authentication logic 'CLIENT.add(requester)'. I execute the test method in spring-rsocket-demo project called 'testRequestGetsResponse' and I find I can't receive the exception. How to process setup payload in @ConnectMapping annotated method and return a RejectedSetupException if need.

        requester.rsocket()
                .onClose()
                .doFirst(() -> {
                    // Add all new clients to a client list
                    log.info("Client: {} CONNECTED.", client);
                    //throw Exception during process setup payload
                    //my authentication code.
                    try {
//                        CLIENTS.add(requester);
                        throw new RuntimeException();
                    } catch (Exception exception) {
                        throw exception;
                    }
                })
                .doOnError(error -> {
                    // Warn when channels are closed by clients
                    log.warn("Channel to client {} CLOSED", client);
                })
                .doFinally(consumer -> {
                    // Remove disconnected clients from the client list
                    CLIENTS.remove(requester);
                    log.info("Client {} DISCONNECTED", client);
                })
                .subscribe();

A: You should define your @ConnectionMapping method as following:
@ConnectionMapping
Mono<Void> handleSetup(@Payload String payload) {
   // Add all new clients to a client list
   log.info("Client: {} CONNECTED.", client);
   boolean isAuthenticated = ... //my authentication code.
   if (!isAuthenticated) {
     //throw Exception during process setup payload
     return Mono.error(new RejectedSetupException("connection is not authenticated"));
   }

   // add client if it is authenticated
   CLIENTS.add(requester);

   requester.rsocket()
            .onClose()
            .doFinally(consumer -> {
               // Remove disconnected clients from the client list
               CLIENTS.remove(requester);
               log.info("Client {} DISCONNECTED", client);
            })
            .subscribe();

   return Mono.empty();
}

As you may see from the code above, if a connection does not pass the authentication, it returns a Mono.error with an appropriate error


text:
Q: How to force winCE to see SD/MMC card after startup I am working on the software for a new instrument that interacts with some scientific equipment.  The user interface is via Windows CE pocket PC (Windows CE 600 V3.01 Build 195).  The instrument is setup with one end of a flex cable always plugged into the SD card slot on the PC.  The cable runs into the instrument, and the other end plugs into a mounted SD card when it is present.  The SD card contains a chip for use with the instrument, as well as software/firmware updates as needed and a data file pertaining to the chip.  I have a c# software application that is run when WinCE boots.  This application checks for the presence of the SDMMC card as it depends on data related to the accompanying chip for certain functionality.
My problem:  If the SD card is inserted into the other end of the flex cable when WinCE boots, winCE detects the card's presence and the \SDMMC folder is created allowing software to read the data.  If only the flex cable is plugged in, but the SDMMC card is NOT present at the other end, Windows does not create the folder.  This I expect.  But our field engineers will swap the card in and out for various reasons to replace the chip while the software is active. This is a problem if windows is booted before the card is inserted. Because of the flex cable, WinCE never detects that the card has been inserted. It also never detects that it was removed.
The software polls the SD card every 5 seconds.  The firmware can tell via the setting of bits if the card is inserted, and it relays this info to software.  If the card had previously been absent, is now detected, but the \SDMMC folder is not present, I'd like software to trigger WinCE to attempt detection again.  I thought about using registry values but am not clear the presense of the HKEY_LOCAL_MACHINE SDMMc value can be written.  I"m also not quite sure what the values mean.  Can these be reset?  I see the Storage Manager Registry would define this as below:
[HKEY_LOCAL_MACHINE\System\StorageManager\Profiles\SDMMC]
"Name"="SD MMC device"
"Folder"="SD Card

Is there someway to read/write this registry to poke winCE to see that a card has been inserted at the other end of the cable?  AM I totally off base with this thought?  Is there some other way to do this?
I apologize for the long question.  I generally play at the application level.  Googling this issue has not given me the answers I need, though perhaps I don't know enough to ask the right questions.  Thanks for any help you can give me.
UPDATE:  I'm still trying to find a resolution to this problem.  My current thought is to force Windows CE to re-enumerate the device when my instrument firmware detects the card has been inserted.  MY code polls firmware to receive notice of this in my c# application.  For my instrument/application the SD Card is always in "Dsk2:".  When the c# application receives notice the SD Card has been inserted it calls a method that does the following:
CODE
     hDevice = CreateFile("\\Dsk2:", (0x80000000) | (0x40000000), 0,
        IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

     if (hDevice == INVALID_HANDLE_VALUE)
     {
        int hDeviceError = Marshal.GetLastWin32Error();
        // THis is an error - call GetLastERror to find
        // out what happened.
        using (StreamWriter bw = new StreamWriter(File.Open(App.chipDebugFile, FileMode.Append)))
        {
           String iua = "DevDriverInterface: error from CreateFile: " + hDeviceError.ToString();
           bw.WriteLine(iua);
        }
        return false;
     }

     bResult = DeviceIoControl(hDevice,
        IOCTL_DISK_UPDATE_PROPERTIES,
        null,
        0,
        null,
        0,
        ref nBytesReturned,
        nOverLapped);

/CODE
IN the above, the CreateFile() call fails with error 55: "The Specified network resource or device is no longer available".
MY questions:  Is what I'm trying to do reasonable to re-enumerate the device?  Does the CreateFile error indicate I should make an ActivateDevice() call instead?  I see an example here:  Problems getting a device driver to load at startup - WM6.1  of someone calling ActivateDevice() from c# code and wonder if that would take care of the problem of getting WIndows CE to recognize that an SD card is now inserted.  Can anyone help me understand what parameters to send to window's ActivateDevice() command?  Am I offbase with this approach?
This is all new territory for me and I appreciate any help you can provide.  Thanks.

A: For anyone interested, here is the code that fixed the problem.  This method is called when the firmware detects the SD card has either been inserted or deleted after power up.  In essence, it unloads/loads the device driver:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
 public struct DEVMGR_DEVICE_INFORMATION
 {
  public uint dwSize;
  public IntPtr hDevice;
  public IntPtr hParentDevice;
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 6)]
  public string szLegacyName;
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
  public string szDeviceKey;
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
  public string szDeviceName;
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
  public string szBusName;
}

public enum DeviceSearchType : int
{
  DeviceSearchByLegacyName = 0,
  DeviceSearchByDeviceName = 1,
  DeviceSearchByBusName = 2,
  DeviceSearchByGuid = 3,
  DeviceSearchByParent = 4
}
class DevDriverInterface
{
  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  public struct SECURITY_ATTRIBUTES
  {
     public int nLength;
     public IntPtr lpSecurityDescriptor;
     public bool bInheritHandle;
  }

  [DllImport("coredll.dll", SetLastError = true)]
  public extern static int ActivateDeviceEx(string device, IntPtr regEnts,
     UInt32 cRegEnts, IntPtr devKey);

  [DllImport("coredll.dll", SetLastError = true)]
  public extern static bool DeactivateDevice(int handle);

  [DllImport("coredll.dll", SetLastError = true)]
  public static extern int FindFirstDevice(DeviceSearchType
  searchType, IntPtr searchParam, ref DEVMGR_DEVICE_INFORMATION pdi);

  // Constructor
  public DevDriverInterface() { }

  public bool MountSDCardDrive()
  {
     const int INVALID_HANDLE_VALUE = -1;

     string mRegPath1 = "";
     int handle = INVALID_HANDLE_VALUE;
     DeviceSearchType searchType = DeviceSearchType.DeviceSearchByDeviceName;

     DEVMGR_DEVICE_INFORMATION di = new DEVMGR_DEVICE_INFORMATION();
     di.dwSize = (uint)Marshal.SizeOf(typeof(DEVMGR_DEVICE_INFORMATION));

     String searchParamString = "SDH1";

     IntPtr searchParam = Marshal.StringToBSTR(searchParamString);

     handle = FindFirstDevice(searchType, searchParam, ref di);

     if (handle == INVALID_HANDLE_VALUE)
     {
        // Failure - print error
        int hFindFirstDeviceError = Marshal.GetLastWin32Error();
        using (StreamWriter bw = new StreamWriter(File.Open(App.chipDebugFile,
            FileMode.Append)))
        {
           String iua = "DevDriverInterface: error from FindFirstDevice: " +
                  hFindFirstDeviceError.ToString();
           bw.WriteLine(iua);
        }
        return false;
     }
     else
     {
        mRegPath1 = di.szDeviceKey;
        bool deactBool = DeactivateDevice((int) di.hDevice);
        if (deactBool == false)
        {
           using (StreamWriter bw = new StreamWriter(File.Open(App.chipDebugFile,
              FileMode.Append)))
           {
              String iua = "DevDriverInterface: DeactivateDevice: returned false -
                          FAILED";
              bw.WriteLine(iua);
           }
           return false;
        }

        Thread.Sleep(50);
        // Call ActiveDevice to setup the device driver
        handle = ActivateDeviceEx(mRegPath1, IntPtr.Zero, 0, IntPtr.Zero);
        if (handle == INVALID_HANDLE_VALUE)
        {
           // Failure - print error
           int hActivateDeviceError = Marshal.GetLastWin32Error();

           using (StreamWriter bw = new StreamWriter(File.Open(App.chipDebugFile,
              FileMode.Append)))
           {
              String iua = "DevDriverInterface: error from ActivateDevice: " +
                     hActivateDeviceError.ToString();
              bw.WriteLine(iua);
           }
           return false;
        }

     }

     return true;
  }

}; // end class

A: The problem was resolved with some help from my colleagues at Advantech.  They provided me with a small c++ executable that verified  loading/unloading the device driver would trigger wince to recognize that an SD card had been inserted. My problem then became getting this to work in my c# application.  With some help from this thread (my own posting):
c# FindFirstDevice Marshaling
I was able to get this to work by calling FindFirstDevice() using "SDH1" as the string identifying the device, and then calling DeactivateDevice()/ActivateDeviceEX().  If anyone is interested in the specific code I can post that later (I'm at home now and the code is on my work laptop).

A: Let's look at the order of events in a properly functioning system.

*

*The device boots and load the SD/MMC driver

*A card is inserted into the card slot

*A hardware interrupt occurs (maybe a power detect, maybe a data - this is OEM dependent)

*An interrupt handler notified the SDMMC driver that a card is present

*The driver queries the card type

*The proper function driver (storage, etc) is loaded (or notified in the case of storage)

*The function driver does it's work to expose the hardware to the OS and applications

The problem for you is that #3 isn't happening properly on boot if a card is already in the slot. This is not uncommon in platform development for SD or USB - the interrupt handler has to be functional and unmasked before the slot is powered.
It's very difficult to create a software workaround for this, especially if the OAL (the part of the OS developed by the hardware manufacturer, not Microsoft) is a black box.  I assume that it is in this case.
To be clear, this is definitely a platform bug. The first course of action should be to talk to the support group at the device OEM, tell them they have a bug and see if you can get them to fix it.
If that fails (if you don't buy many devices, or the device is old, getting support is....challenging) then I'd suggest digging into the platform SDMMC driver to see if there might be any way to get into the middle of the process.  I've never tried (I've always been on the OEM side of this and just fixed the driver or platform code), so I'm not sure if there even is a solution, but it's worth a look.
The source code is freely available if you download and install the evaluation version of Platform Builder (be sure to select the 'install source' option).  It's all C, and it's not a lot of fun to try to browse, but as the saying goes, "Use the Source, Luke."


text:
Q: Why can't I download a midi file with python requests? I'm trying to download a series of classical music midi files with python and the requests library.  Unfortunately, I can't seem to actually download the midi files themselves.  The only thing I'm downloading is HTML files. I have searched SO and tried some other solutions, such as this post, and this post, but both solutions didn't work for me.
Here is the code I've written:
from bs4 import BeautifulSoup
import requests
import re

url = 'http://www.midiworld.com/classic.htm'
headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
r = requests.get(url, headers=headers)
data = r.text
soup = BeautifulSoup(data, "html.parser")

links = []
for link in soup.find_all("a", href=re.compile("mid$")):
    links.append(link['href'])

def get_filename(links):
    filenames = []
    """
    Will return a list of filenames for the files to be downloaded
    """
    for link in links:
        url = link
        if url.find('/'):
            f_name = url.rsplit('/', 1)[1]
            print(url.rsplit('/', 1)[1])
            filenames.append(f_name)
    return filenames

def download_files(links, filenames):
    for link, filename in zip(links, filenames):
        r = requests.get(url, allow_redirects=True)
        with open(filename, 'wb') as saveMidi:
            saveMidi.write(r.content)

filenames = get_filename(links)
download_files(links, filenames)

I can't figure out why I'm getting html files returned.  Any ideas on how to get the midi files downloaded properly?

A: I solved the issue, but I had to make some major changes to your code. Revised code:
import requests
from bs4 import BeautifulSoup
import re

main_page = requests.get('http://www.midiworld.com/classic.htm')
parsed_page = BeautifulSoup(main_page.content, 'html.parser')

links = parsed_page.find_all('a', href=re.compile('mid$'))
def getFileName(link):
    link = link['href']
    filename = link.split('/')[::-1][0]
    return filename

def downloadFile(link, filename):
    mid_file = requests.get(link['href'], stream=True)
    with open(filename, 'wb') as saveMidFile:
        saveMidFile.write(mid_file.content)
        print('Downloaded {} successfully.'.format(filename))

for link in links:
    filename = getFileName(link)
    downloadFile(link, filename)

This seemed to download the files quickly and easily. None of them are corrupted and i can play them just fine.
Thanks for cluttering my home folder with classical music tho.

A: I don't know why, but this worked for me.
from urllib.request import urlopen
x = urlopen(links[0]).read()
with open(filenames[0], "wb") as f:
    f.write(x)

A: If someone wants to use the shell spell:
wget https://www.midiworld.com/mozart.htm
cat mozart.htm | grep -oh -E 'https(.*)\.mid"' | sed 's/"//' | xargs wget -c -t1
rm mozart.htm


text:
Q: how to unwrap a std::reference_wrapper like boost::unwrap_reference I am tring to port some code, that uses boost::unwrap_reference a lot to C++11. The code calls a lot member functions, like
template< typename T, typename Y>
void initialize( T _t, Y y)
{

    typename boost::unwrap_reference< T >::type & t = _t;

    t.doSomethingNastyWithY( y );
}

// The function is called like this
struct DoSomething
{
     template<typename Y>
     void doSomethingNastyWithY(Y y)
     {
         // do stuff
     }
};

struct Object {};

DoSomething s;
Object obj;

int main()
{
    initialize( s, obj ); // Take a copy of DoSomething
    initialize( boost::ref(s), obj ); // Uses DoSomething as reference
}

I couldn't find an equivalent to boost::unwrap_reference in the STL, is there an other straight forward way to do this?
EDIT: I clarified the example a bit

A: Something along the lines of:
template< typename T >
struct UnwrapReference;

template< typename T >
struct UnwrapReference { typedef T type; }

template< >
struct UnwrapReference< std::reference_wrapper< T > > { typedef T type; }

Untested though, but that's the gist of how you'd probably be able to do it.


text:
Q: Can Make PUT and GET calls to Quart Schema, but not POST? I am working on developing an API for a web application using Quart and Quart-Schema. GET and PUT calls to the API work fine.  The API is running in Kubernetes hosted on DigitalOcean.  All the calls work fine on the docs page.  POST calls are not working and The only error message I am getting is 400 BAD REQUEST Bad request or unsupported method.  Any input would be invaluable.
Following PUT curl works:
curl -X PUT "https://app.restake.net/api/helper/email" -H  "accept: application/json" -H    "Content-Type: application/json" -d "{\"check\":\"jmsdevln@gmail.com\"}"

The Below POST curl does not work:
curl -X POST "https://app.restake.net/api/user" -H  "accept: application/json" -H  "Content-                        Type: application/json" -d "{  \"discord_id\": 02,  \"email\": \"string2\",  \"password\": \"string\",  \"telegram_id\": 02}"

This is the code responsible for the POST:
@app.route("/api/user", methods=['POST'])
@validate_request(User_)
@validate_response(User, 201)
async def createNewUser(data: User_) -> User:
"""Create a New User

This creates a new user in the PostgreSQL database.
"""
result = await psql.createUser(app.pool, asdict(data))
if result is not None:
    return User(**result), 201
else:
    abort(404)

My dockerfile is below:
FROM python:3.9.1-slim-buster
WORKDIR /usr/src/app
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# install system dependencies
RUN apt-get update && apt-get install -y build-essential
RUN pip install --upgrade pip
COPY ./requirements.txt /usr/src/app/requirements.txt
RUN pip install -r requirements.txt
COPY ./project/ /usr/src/app/project/
COPY ./manage.py /usr/src/app/
COPY entrypoint.sh .
RUN chmod +x entrypoint.sh
EXPOSE 5000
ENTRYPOINT ["/usr/src/app/entrypoint.sh"]

My Kubernetes YAML:
---
apiVersion: v1
kind: Service
metadata:
  name: dashb-quart
  namespace: restakenet
spec:
  ports:
  - port: 5000
    targetPort: 5000
  selector:
    app: restake
    tier: dashboard
  type: NodePort
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: restake-quart-dashboard-dev
  namespace: restakenet
spec:
  replicas: 3
  selector:
    matchLabels:
      app: restake
      tier: dashboard
  template:
    metadata:
      labels:
        app: restake
        tier: dashboard
    spec:
      containers:
      - name: restake-quart-dashboard-dev
        image: boyroywax/restake-quart-dashboard-dev:latest
        imagePullPolicy: Always
        args: ["hypercorn", "--bind", "0.0.0.0:5000", "manage:app"]
        ports:
        - containerPort: 5000
          name: dashb-qaurt

A: The body of your request is malformed.
Update it so the numbers do not have leading zeros (or are strings):
{
    "discord_id": 2,
    "email": "string2",
    "password": "string",
    "telegram_id": 2
}

Reference
RFC 4627
2.4.  Numbers

   The representation of numbers is similar to that used in most
   programming languages.  A number contains an integer component that
   may be prefixed with an optional minus sign, which may be followed by
   a fraction part and/or an exponent part.

   Octal and hex forms are not allowed.  Leading zeros are not allowed.
   ...


text:
Q: Can RouteData in Angular 2 pass variables to routed components from parent component? I would like to use the RouteConfig to pass a variable from my AppComponent to Coursescomponent, but the "data" property in route config can only pass constant parameter, and it cannot recognize "this". Is there a way to do this?
If not, what is a best practice to pass variables to routed components?
@Component({
    selector: 'app',
    template: `
    <router-outlet></router-outlet>
    `,

directives: [ROUTER_DIRECTIVES],
})

@RouteConfig([
    { path: '/courses'
      , name: 'Courses'
      ,component: CoursesComponent
       ,data:{token:this.token}}  // this doesn't work -- cannot read property "token" of undefined

])

export class AppComponent  {
    token:string;
//I would change the token(string) in this component, and I want to pass this to the routed components

}

A: I have achieved this by defining a dynamic route in the constructor. Here is an example
import {Router,ROUTER_DIRECTIVES} from 'angular2/router';
import {Component} from 'angular2/core';

@Component({
  selector: "app",
  template: '<router-outlet></router-outlet>',
  directives: [ROUTER_DIRECTIVES]
})
export class AppCmp{
  public token:string;
  constructor(private _router:Router){
    var config = [];
    if(!this._router.registry.hasRoute("Courses",AppCmp))
      config.push({ path: '/courses', name: 'Courses',component: CoursesComponent,data:{token:this.token});

    this._router.config(config)
  }
}

A: You can use a shared service to share values between components.
See Global Events in Angular 2 for more details how to implement a shared service.
Alternatively you can inject the Router and call one of it's router.navigateXxx() functions where you pass additional data.


text:
Q: Converting a list of strings into integers First, I have searched and found some other solutions that seem very plausible and should work, but for whatever reason after trying them with my data - those solutions don't work. I am using python 2.7.6
I am attempting to convert a list of strings into integers so I can add them.
#!/usr/bin/env python
import re
numlist = list()
total = 0
#open the file
f = open('c:/Users/Home/Documents/homework/python_webdata/regex_sum_21441.txt', 'r')

for line in f:
    line = line.rstrip()
    z= re.findall('[0-9]+', line)
    if z != []:
    numlist.append(z)

print numlist

#attempting to add up the int's from the list (which doesnt work)
results = [int(i) for i in numlist]

total = sum(results)

My data prints out correctly, and looks something like this before I attempt to convert it to ints
[['2261'], ['2504', '4529'], ['3698', '2693', '3291'], ['3556', '9753', '4059'], ['113', '8261', '157'], ['8059', '1055'], ['1060'], ['2412', '1860'], ['3589'], ['3319'], ['475'], ['6802',

but I get the following error:

Traceback (most recent call last):   File
  "C:\Users\Home\Documents\homework\python_webdata\lesson 2 code.py",
  line 20, in
      results = [int(i) for i in numlist] TypeError: int() argument must be a string or a number, not 'list'

A: As one of the comments put appropriately, you have list of lists containing integers because of the "append" you use.
Put
numlist.extend(z)

instead of
numlist.append(z)

A: Obviously, the issue here is with the z= re.findall('[0-9]+', line) as this will return a list of strings, now, after numlist.append(z), you are appending the whole z list into numlist and that's why you get a list of list of strings.
Now,
results = [int(i) for i in numlist] will not work as you have in your numlist lists of strings and int(i) cannot convert a list into integers, you still have to flatten it, so, I think your best option is numlist.extend(z) to keep numlist flat with strings only (not a list of lists).
Another solution is to flatten your numlist this way:
results = [int(item) for lst in numlist for item in lst]
Note: As improvement to your code and sticking with best practices, it is better to use with open(file, mode) as f: as this will make sure that your file is closed without mentioning f.close() explicitly, this way:
with open('c:/Users/Home/Documents/homework/python_webdata/regex_sum_21441.txt', 'r') as f:
    for line in f:
        line = line.rstrip()
        z= re.findall('[0-9]+', line)
        if z != []:
            numlist.extend(z)


text:
Q: Xcode configuration and CocoaPods Is there any way to not overwrite custom project configurations by auto installing Cocoapods (Pods.debug.xcconfig and Pods.release.xcconfig).
I would like to use my own custom configs and just #include mentioned above Pods configs.
At this moment I'm using pod install --no-integrate command, I wonder is there any better solution?
Don't like this approach because firstly have to build pod install to create in Pods project custom configurations then switch my configurations on own in My Project then I can use --no-integrate option.
I wonder how to optimise this process.


text:
Q: Redirect with JSF and prettyFaces I have a problem with redirecting with JSF and pretty faces. I am quite new to this stuff and need some help as I cannot get redirect to work, like I want it to.
Basically I have this in my pretty config:
<url-mapping id="newProject">
    <pattern value="/newProject/" />
    <view-id value="/faces/project/newProject.xhtml" />
    <action>#{projectController.initNewProject}</action>
</url-mapping>

<url-mapping id="project">
    <pattern value="/project/" />
    <view-id value="/faces/project/projectIdx.xhtml" />
</url-mapping>

The function initNewProject looks like this:
public String initNewProject() throws IOException {

    project = this.createProject(123415, "1234578943148", "KB25");

    System.out.println(project);

    return "pretty:project";
}

where project is a field in the ProjectController:
  @Named
  @ConversationScoped
  public class ProjectController implements Serializable {
     private transient Project project;
     ...

The redirect works as I wish, as the URL changes from ../newProject/ to ../project/ and the contents of /faces/project/newProject.xhtml are displayed. But somewhen during the redirect the constructor of ProjektController is called and nulls the field project.
If I change
    return "pretty:project";

to
    return "/project/projectIdx.xhtml";

everything works fine. The contents of project are displayed on the webpage. However the URL does not change. It stays ../newProject/ and if the user presses F5 he creates a new project which is bad.
For some other reasons I cannot store the project in the session, so that is no option for me.
I dont want the redirect to recreate the controller as I want newProject.xhtml to display contents of the project, which was created during initNewProject
How can this be achieved?
Many thanks!
Michael

A: I think the problem is caused by the tight coupling between the two mappings. Basically you are using a page action in your first mapping to initialize a bean property and then want to access this property in the page rendered by the second mapping. That's not the way RESTful URLs created with PrettyFaces work.
Instead your second mapping should be completely independent from the other. This ensures that the RESTful URL works even if it is bookmarked, copied into another browser window or whatever.
The common way to build such a RESTful URL with PrettyFaces is to use a path parameter like this:
<url-mapping id="project">
    <pattern value="/project/#{projectController.projectId}/" />
    <view-id value="/faces/project/projectIdx.xhtml" />
    <action>#{projectController.loadProject}</action>
</url-mapping>

This way the ID of the project is injected into your controller and you can load the corresponding entity from the database in the page action method:
public void loadProject() {
  this.project = projectDao.getById( projectId );
}

How to handle the "new project" use case for your example depends on your requirements regarding persistence and the overall process.
In theory the code you provided should also work. My guess is that the cid query parameter which is required to keep the conversion scope alive gets lost for some reason. There are a few threads on the PrettyFaces forums about this issue. But AFAIK this is typically caused by bugs in older CDI implementations.

A: Fixed the redirection by using the following syntax:
public String create(final Post post) {
        postService.save(post);
        return "pretty:posts";
}


text:
Q: Could someone improve kernel upgrade scripts with VirtualBox install? Ubuntu kernel updates are very frequent. Each time kernel is updated I need install kernel-headers and do /etc/init.d/vboxdrv setup
¿Could kernel update script check if is needed and do it properly?
I suppose that I could do it but I don't known where should be the correct place to post it and also if there is some major cause due it hasn't done yet.

A: Install the dkms package and it will handle it for you on every kernel upgrade.
After installing DKMS, re-run the original installer for the VirtualBox Guest tools, then it will install a DKMS hook to recompile the kernel modules on every install.
To check the current status of the kernel modules, run
dkms status

Which will output e.g.:
vboxguest, 4.2.6, 3.2.0-43-generic, x86_64: installed
vboxguest, 4.2.6, 3.2.0-44-generic, x86_64: installed

Full steps towards a "proper" VirtualBox Guest tools installation:

*

*Do a full software update of your machine and reboot afterwards.
sudo apt-get update && sudo apt-get dist-upgrade

*Install the dependencies (compiler, Linux headers, DKMS)
sudo apt-get install build-essential linux-headers dkms

*Run the VirtualBox Guest additions installer (from the virtual media inserted):
sudo ./VBoxLinuxAdditions.run

*Reboot.


text:
Q: Count distinct while aggregating others? This is how my dataset looks like:
+---------+------------+-----------------+
|  name   |request_type| request_group_id|
+---------+------------+-----------------+
|Michael  |     X      |  1020           |
|Michael  |     X      |  1018           |
|Joe      |     Y      |  1018           |
|Sam      |     X      |  1018           |
|Michael  |     Y      |  1021           |
|Sam      |     X      |  1030           |
|Elizabeth|     Y      |  1035           |
+---------+------------+-----------------+

I want to calculate the amount of request_type's per person and count unique request_group_id's
Result should be following:
+---------+--------------------+---------------------+--------------------------------+
|  name   |cnt(request_type(X))| cnt(request_type(Y))| cnt(distinct(request_group_id))|
+---------+--------------------+---------------------+--------------------------------+
|Michael  |          2         |         1           |      3                         |
|Joe      |          0         |         1           |      1                         |
|Sam      |          2         |         0           |      2                         |
|John     |          1         |         0           |      1                         |
|Elizabeth|          0         |         1           |      1                         |
+---------+--------------------+---------------------+--------------------------------+

What I've done so far: (helps to derive first two columns)
msgDataFrame.select(NAME, REQUEST_TYPE)
            .groupBy(NAME)
            .pivot(REQUEST_TYPE, Lists.newArrayList(X, Y))
            .agg(functions.count(REQUEST_TYPE))
            .show();

How to count distinct request_group_id's in this select? Is it possible to do within it?
I think it's possible only via two datasets join (my current result + separate aggregation by distinct request_group_id)

A: Example with "countDistinct" ("countDistinct" is not worked over window, replaced with "size","collect_set"):
val groupIdWindow = Window.partitionBy("name")
df.select($"name", $"request_type",
      size(collect_set("request_group_id").over(groupIdWindow)).alias("countDistinct"))
  .groupBy("name", "countDistinct")
  .pivot($"request_type", Seq("X", "Y"))
  .agg(count("request_type"))
  .show(false)


text:
Q: Stored procedure sqlserver 2008 only works with Visual Studio 2008 graphical user interface I'm invoking a stored procedure on sql server r2 2008 through a java application. But I can't any result. Also, when executing the stored procedure from sql server (through a sql sheet or the graphical user interface) I can't get any results.
The stored procedure only works fine when executed from Visual Studio 2008, using the graphical user interface.
This is the main query of the stored procedure:
 SELECT TOP (1)
    @IdLibroHistorico = SD.dbo.VM0001_CuadranteAgenteReal.Id
,@IdServicio = SD.dbo.TM0001_ServiciosMaestro.IdServicio
    ,@IdEntidad = SD.dbo.VM0001_CuadranteAgenteReal.IdAgenteReal
    ,@Negociado = SD.dbo.VM0001_CuadranteAgenteReal.TipoPersonal
    ,@Turno = SD.dbo.VM0001_CuadranteAgenteReal.IdTurno
    ,@UsuarioSysPol = SB.dbo.TSysUser.IdUsuario
FROM SB.dbo.TSysActivos
RIGHT JOIN SB.dbo.TSysUser ON SB.dbo.TSysActivos.Usuario = SB.dbo.TSysUser.IdUsuario
RIGHT JOIN SD.dbo.TM0001_ServiciosMaestro
INNER JOIN SD.dbo.VM0001_CuadranteAgenteReal ON SD.dbo.TM0001_ServiciosMaestro.IdServicio = SD.dbo.VM0001_CuadranteAgenteReal.IdServicio
    AND SD.dbo.TM0001_ServiciosMaestro.TipoPersonal = SD.dbo.VM0001_CuadranteAgenteReal.TipoPersonal ON SB.dbo.TSysUser.IdEntidad = SD.dbo.VM0001_CuadranteAgenteReal.IdAgenteReal WHERE (SD.dbo.TM0001_ServiciosMaestro.ServicioCorto = @Unidad)
    AND (
        @fechaDatetime >= SD.dbo.VM0001_CuadranteAgenteReal.HI
        AND @fechaDatetime <= SD.dbo.VM0001_CuadranteAgenteReal.HF
        )
ORDER BY ISNULL(SB.dbo.TSysActivos.Usuario, '') DESC

Anybody can tell me why?
Thanks in advance

A: The view VM0001_CuadranteAgenteReal was returning zero rows.


text:
Q: How to hide Particular directories in QFileSytemModel I have a QFileSystemModel which is use as a model in QTreeView . This work fine now I have names of some directories. Which I want to hide in QTreeview.
QString strCompleteDirectoryPath = "/Volumes/";
QTreeView *SourceTreeView = new QTreeView;
QSize ItemSize(20,20);
QFileSystemModel *model = new QFileSystemModel();
model->setNameFilterDisables(false);
model->setRootPath(strCompleteDirectoryPath);
model->setFilter(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Hidden);
model->setNameFilters(QStringList("samplefolder"));
SourceTreeView->setModel(model);
SourceTreeView->setRootIndex(model->index(strCompleteDirectoryPath));
SourceTreeView->header()->resizeSection(0,350);
SourceTreeView->setIconSize(ItemSize);

I want to hide "samplefolder" in "/Volumes" directory. I use both strings "samplefolder"  and "/Volumes/samplefolder" in setNameFilters() one by one to check my filter. But it does not work for me.
So kindly tell me how could I hide this because I dont want to show it in my QTreeView.

A: You should use QSortFilterProxyModel for this. Example:
QString strCompleteDirectoryPath = "/Volumes/";

QTreeView *SourceTreeView = new QTreeView;

QFileSystemModel *model = new QFileSystemModel(SourceTreeView);
model->setRootPath(strCompleteDirectoryPath);
model->setFilter(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::Hidden);

QSortFilterProxyModel* filter = new QSortFilterProxyModel(model);
filter->setFilterRegExp(QRegExp("^((?!samplefolder).)*$", Qt::CaseInsensitive));

SourceTreeView->setModel(filter);


text:
Q: Using LibCurl in C++ and self signed certificate I've got a problem using libcurl and ssl.
If I try to connect to my site using the following curl command :
curl -q  --cert client-2048.crt --key client-2048.key https://****** -d "username=&password=" -H "X-Application: curlCommandLineTest"
everything works well(the certificate is self signed by the way)
How can I do the same usign libcurl?
I tried to follow the libcurl ssl sample but the certificates and private key
have different extensions so I don't know where to start.
So far I tried the following(and many other combinations) :
static const char *pCertFile = "client-2048.crt";
static const char *pCACertFile = "client-2048.pem";
static const char *pKeyName = "client-2048.key";

curl_global_init(CURL_GLOBAL_DEFAULT);

curl = curl_easy_init();
if (curl) {
    /* what call to write: */
    curl_easy_setopt(curl, CURLOPT_URL, "https://*****");
    curl_easy_setopt(curl, CURLOPT_HEADERDATA, headerfile);

        /* cert is stored PEM coded in file... */
        /* since PEM is default, we needn't set it for PEM */
        curl_easy_setopt(curl, CURLOPT_SSLCERTTYPE, "PEM");

        /* set the cert for client authentication */
        curl_easy_setopt(curl, CURLOPT_SSLCERT, pCertFile);

        /* set the private key (file or ID in engine) */
        curl_easy_setopt(curl, CURLOPT_SSLKEY, pKeyName);

        /* disconnect if we can't validate server's cert */
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);

        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);
        /* Check for errors */
        if (res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));

        /* we are done... */
    } while (0);
    /* always cleanup */
    curl_easy_cleanup(curl);
    return 0;

But I get the message :
curl_easy_perform() failed: Peer certificate cannot be authenticated with
given CA certificates

So what would it be the Libcurl code to mirror the call that succeed?
Thanks

A: Self Signed Certificate :
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);


text:
Q: Hessian of a black box function that uses Pytorch First of all I am very new to Python and machine learning, so please excuse my ignorance on what might be a very basic issue; I do appreciate any input on this question!
I have a very complicated scalar-valued multivariable function implemented in Python that uses Pytorch functionalities (it is actually a composition of a neural network and operations that depend on outputs from the network), and I wish to find the gradient vector and Hessian matrix of this function at certain points. Besides numdifftools which does finite difference and is not very fast and accurate when the dimension of input is high, are there alternatives? Something that seems promising is the the torch.autograd which I believe is used to compute the gradient of neural networks, however, can it compute the gradient and Hessian of any black-box function that runs Pytorch code? Any input is appreciated!


text:
Q: Sending grouped json data with ajax I'm using extJS version 4.0 to generate a entry form. On that form there is a save button that sends all the fielddata to php via ajax. As transfer protocol for the data itself I'm using json.
As I need to make a dynamical (general) routine for processing this data (as that one form won't be the only form in that project) I would need that json data grouped somehow. One of the requirements I have is that I need the "fieldnames" to be as they are (as I use the fieldnames I get transmitted to me to access the approopriate coloumns in the database in the automatic save routine).
My question here is is there any way to somehow group the data that is transmitted via json (thus that extJS groups it).
As a simplified example:
On the entryform I'm saving data for 2 tables (1. Person 2. bankaccount) which have the following fields shown on the form:
-firstname
-lastname
for person
and
-account number
-bank number
for bankaccount
(the stores are accordingly)
Is there a way with extJS to group this data acordingly, thus generate something like this?
{"person":[{"firstname": "Mark", "lastname":"Smith"}],"bankaccount":[{"account number":123112,"bank number":1A22A1}]}

Currently I'm getting something like this:
{"firstname": "Mark", "lastname":"Smith","account number":123112,"bank number":1A22A1}

Both person and bankaccount  are in their separate stores.
Tnx.

A: Well, you've two stores: one for 'person' and one for 'bankaccount'.
Ext.define ('Person', {
    extend: 'Ext.data.Model' ,
    fields: ['firstname', 'lastname']
});

Ext.define ('BankAccount', {
    extend: 'Ext.data.Model' ,
    fields: ['accountnumber', 'banknumber']
});

var personStore = Ext.create ('Ext.data.Store', {
    model: 'Person' ,
    data: [
        {firstname: 'foo', lastname: 'bar'} ,
        {firstname: 'zoo', lastname: 'zar'} ,
        {firstname: 'too', lastname: 'tar'} ,
        {firstname: 'goo', lastname: 'gar'} ,
        {firstname: 'moo', lastname: 'mar'}
    ]
});

var bankAccountStore = Ext.create ('Ext.data.Store', {
    model: 'BankAccount' ,
    data: [
        {accountnumber: 10000, banknumber: 10000} ,
        {accountnumber: 20000, banknumber: 20000} ,
        {accountnumber: 30000, banknumber: 30000} ,
        {accountnumber: 40000, banknumber: 40000} ,
        {accountnumber: 50000, banknumber: 50000}
    ]
});

Then, you want to dump these stores as JSON. No problem!
Make a container (jsonData) and then fill it up with your stores:
var jsonData = {
    person: [] ,
    bankaccount: []
};

personStore.each (function (person) {
    jsonData.person.push (person.data);
});

bankAccountStore.each (function (bank) {
    jsonData.bankaccount.push (bank.data);
});

console.log (Ext.JSON.encode (jsonData));

And this is the output on the console:
{"person":[{"firstname":"foo","lastname":"bar"},{"firstname":"zoo","lastname":"zar"},{"firstname":"too","lastname":"tar"},{"firstname":"goo","lastname":"gar"},{"firstname":"moo","lastname":"mar"}],"bankaccount":[{"accountnumber":10000,"banknumber":10000},{"accountnumber":20000,"banknumber":20000},{"accountnumber":30000,"banknumber":30000},{"accountnumber":40000,"banknumber":40000},{"accountnumber":50000,"banknumber":50000}]}

Is that what you've requested?
Here's the fiddle


text:
Q: Integrating an .app inside UIViewcontroller of another app currently I'm using an external program (Stencyl) to build my app, however I can't integrate AdMob to it. I thought I might be able to integrate my app (or xcode project) into the AdMob xcode project. Is there a way to do this? Is it even possible?
To clarify:
I got the AdMob working in XCode, I want to add an app/xcodeproject inside my AdMob's xcodeproj main window.

A: If what you want to do is reference one project inside another, you can do this by dragging the project file (the .xcodeproj) from a Finder window into your AdMob XCode workspace. Make sure both projects are not open at once though.


text:
Q: Does the C-m key combination in emacs generate "\r\n" or just "\n" The emacs docs for C-m key (ie. C-h k C-m) displays the following
newline is an interactive compiled Lisp function in `simple.el'.

(newline &optional ARG)

Insert a newline, and move to left margin of the new line if it's blank.
If `use-hard-newlines' is non-nil, the newline is marked with the
text-property `hard'.
With ARG, insert that many newlines.
Call `auto-fill-function' if the current column number is greater
than the value of `fill-column' and ARG is nil.

But it does not say newline is in the context of dos ("\r\n") or unix ("\n").

A: Internally, Emacs stores a Unix newline, i.e. "\n", in its buffers, similar to what most C programs do when reading text files.  If there is a "\r" in an Emacs buffer, it will be displayed as ^M.
On the other hand, Emacs remembers the newline convention used for each opened file.  If you open a file with "\r\n" line breaks, modify it, and save it, then Emacs will convert all newlines back to "\r\n".


text:
Q: Tweepy multiple auth handler when rate limit exceeded I need to get lots of tweets in very short time and want to switch between multiple auth handlers(I have 20 different twitter developer account). I did not find anything related to this problem in Tweepy documentation and saw this method but it doesn't work, I'm not sure, I guess because of different API versin.
auths = []
for consumer_key, consumer_secret, access_key, access_secret in twitter_accs:
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    auths.append(auth)

# api
api = tweepy.API(auths)
currentCursor = tweepy.Cursor(api.search, q = 'bitcoin')
c = currentCursor.items()

switch = 0
api.auth_idx = switch
tweets = []
maxId = 0

while True:
    try:
        for tweet in c:
            tweets.append(tweet)
            maxId = tweet.id

    except tweepy.TweepError as e:
        print(e)
        print("---------------------------Rate limit exceeded.---------------------------")
        print("switching keys...")
        switch += 1
        api.auth_idx = switch           # naechster Key
        currentCursor = tweepy.Cursor(api.search, q='bitcoin', max_id=maxId)

And got this error
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_13904/1614165536.py in <module>
     17 while True:
     18     try:
---> 19         for tweet in c:
     20             tweets.append(tweet)
     21             maxId = tweet.id

~\AppData\Local\Programs\Python\Python38\lib\site-packages\tweepy\cursor.py in __next__(self)
     49
     50     def __next__(self):
---> 51         return self.next()
     52
     53     def next(self):

~\AppData\Local\Programs\Python\Python38\lib\site-packages\tweepy\cursor.py in next(self)
    241         if self.current_page is None or self.page_index == len(self.current_page) - 1:
    242             # Reached end of current page, get the next page...
--> 243             self.current_page = self.page_iterator.next()
    244             while len(self.current_page) == 0:
    245                 self.current_page = self.page_iterator.next()

~\AppData\Local\Programs\Python\Python38\lib\site-packages\tweepy\cursor.py in next(self)
    130
    131         if self.index >= len(self.results) - 1:
--> 132             data = self.method(max_id=self.max_id, parser=RawParser(), *self.args, **self.kwargs)
    133
    134             if hasattr(self.method, '__self__'):

~\AppData\Local\Programs\Python\Python38\lib\site-packages\tweepy\binder.py in _call(*args, **kwargs)
    251                 return method
    252             else:
--> 253                 return method.execute()
    254         finally:
    255             method.session.close()

~\AppData\Local\Programs\Python\Python38\lib\site-packages\tweepy\binder.py in execute(self)
    174                 auth = None
    175                 if self.api.auth:
--> 176                     auth = self.api.auth.apply_auth()
    177
    178                 # Request compression if configured

AttributeError: 'list' object has no attribute 'apply_auth'

A: According to the Tweepy documentation, the argument for the tweepy.API method can not be a list. Why don't you just create a list of authenticated api like you created a list of auths ?
Finally, be carefull because your attempt could be a violation of the Twitter developper terms.


text:
Q: Need assistance getting Bootstrap 3 Scrollspy to work with auto-collapsing mobile menu The issue I am having is getting both Scrollspy and a mobile menu to collapse when a link is clicked together.  I can get the functionality of either one working by itself, but not together.
This snippet has scrollspy working, however, the mobile menu does not collapse when a linked is clicked.

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbarCollapse">
                    Toggle navigation

                </button>
                Site Name

About

Social

Contact

Blog

If I add the following to each anchor tag the mobile menu will collapse on click, but scrollspy breaks:
data-toggle="collapse" data-target=".navbar-collapse.in"

I'm assuming that using data-target is causing the issue, but I'm not sure how else to get around it.
Does anybody know of a way to get these two things to work together?
In searching other answers I was able to get both features to work by themselves, but I've yet been able to find something to assist in getting them working together.  If I missed an answer, please point me in the right direction.
Thanks,

A: After further searching, it seems like using the data-toggle and data-target in the anchor tags breaks scrollspy.  I've decided to use the following JS I found on another StackOverflow question for collapsing the mobile nav menu.  This doesn't work with sub-menus it seems, but I'm not worried about that.


text:
Q: How to get my applicationContext.xml file pull a value from a properties file? I'm pretty new to Java and there's a project I'm working on that I'm struggling with.
For the longest time we've had a really clunky build process for this app, where you have to manually go in and change values in the pom.xml file to switch from test to prod values. I'm trying to fix that so you can instead build using a profile flag, but I'm running into some trouble with one piece. There's an applicationContext.xml file that has the database URL hardcoded into it, and I want to be able to change that based on the profile, but I'm having trouble figuring out how to do that.
The line in question looks like this:
<property name="url" value="jdbc:mysql://databaseserver:3306/testDatabase" />

How can I have that load the property I'm setting up in my application.properties file?
app.database.url="jdbc:mysql://databaseserver:3306/testDatabase"

A: You could do it in few ways. For instance, you could either place your properties directly inside the pom.xml file within a profile, or place them inside a .properties file and decide which file you should use on a profile level.
Here is the first way of doing this:
Firstly, you would write something like that in your main pom.xml :
     <project>

     ...

      <profiles>
        <profile>
          <id>development</id>
          <activation>
            <property>
              <name>env</name>
              <value>dev</value>
            </property>
          </activation>
          <properties>
          <app.database.url>jdbc:mysql://databaseserver:3306/testDatabase</app.database.url>
          </properties>
        </profile>
<profile>
          <id>production</id>
          <activation>
            <property>
              <name>env</name>
              <value>prd</value>
            </property>
          </activation>
          <properties>
          <app.database.url>jdbc:mysql://anotherserver:1234/veryImportantProductionDatabase</app.database.url>
          </properties>
        </profile>
        ...   </profiles>
</project>

Then you would replace your property tag with a given placeholder, that is
 <property name="url" value="${app.database.url}" />

and voilà. Hope that helps

A: Simple just reference the properties file in your applicationContext.xml
<property name="url" value="${app.database.url} />