问:
How to insert an element at the last position in an array dynamically in C?
I'm a newbie in C and trying to insert a number at the last position in C such that, the size of the array is changed over time.

The first array is like this:

```<code>temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
</code>```

Now how can we insert those values in temp that are != 0 to a new array which has a defined length of 5: tmp

Here's what I'm trying:

```<code>void push(int arr[], int value, int current){
  arr[current] = value;
}

int main(void) {

  int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
  int tmp[5];

  for(int i=0;;i++){
    if(temp[i]) push(tmp, temp[i],sizeof(tmp)/sizeof(tmp[0]));
    // I don't put i < 10 int the loop initialization. Since the tmp's length is just 5

  }
  // I put sizeof(tmp)/sizeof(tmp[0]) there because we want at every time the tmp is inserted a new value,
  // it's length will change (increase by 1).
  // So next loop round, the new value will be added to the last position
  // But I failed to do so

}
</code>```

Current output:

```<code>exited segmentation fault
// I'd be very grateful if someone can also explain for me why this error happens
</code>```

Desired output:

```<code>tmp[5] = {1, 2, 5, 6, 8}
</code>```

答:
What is

trying to insert a number at the last position in C

Although you got an explanatory answer by David Ranieri, I want to show the simplest approach keeping in mind that you are a newbie. Look at this code:-

Code:

```<code>#include <stdio.h>
#include <stdlib.h>
#define SIZE 10

void push(int arr[], int value, int current){
  arr[current] = value;
}

int main(void) {

  int temp[SIZE] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
  int *tmp = NULL, count = 0, i, j;

  // Loop for counting non-zero values in temp array.
  for (i = 0; i < SIZE; ++i)
    if (temp[i])
        count++;

  // Dynamically allocating space for tmp along with checking errors if any.
  if((tmp = (int *)malloc(count * sizeof(int))) == NULL)
     {
         printf("Memory Not Available.\n");
         exit(-1);
     }

  for(i = 0, j = 0; i < SIZE; i++){
    if(temp[i])
        push(tmp, temp[i], j++);
  }

  // Printing your desired output.
  for(i = 0; i < count; ++i)
    printf("%d\t", tmp[i]);

    free(tmp);
}
</code>```

Here the size of tmp will change according to the non-zero elements of temp.
Now if you want to make the temp array a dynamic array, use the same approach as used for the tmp, just ask the user at run-time to input the size of temp and then its elements/values as well.

Body:
I'm a newbie in C and trying to insert a number at the last position in C such that, the size of the array is changed over time.

The first array is like this:

temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};

Now how can we insert those values in temp that are != 0 to a new array which has a defined length of 5: tmp

Here's what I'm trying:

void push(int arr[], int value, int current){
  arr[current] = value;
}

int main(void) {

  int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
  int tmp[5];

  for(int i=0;;i++){
    if(temp[i]) push(tmp, temp[i],sizeof(tmp)/sizeof(tmp[0]));
    // I don't put i < 10 int the loop initialization. Since the tmp's length is just 5

  }
  // I put sizeof(tmp)/sizeof(tmp[0]) there because we want at every time the tmp is inserted a new value,
  // it's length will change (increase by 1).
  // So next loop round, the new value will be added to the last position
  // But I failed to do so

}

Current output:

exited segmentation fault
// I'd be very grateful if someone can also explain for me why this error happens

Desired output:

tmp[5] = {1, 2, 5, 6, 8}

Body:
What is

trying to insert a number at the last position in C

Although you got an explanatory answer by David Ranieri, I want to show the simplest approach keeping in mind that you are a newbie. Look at this code:-

Code:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 10

void push(int arr[], int value, int current){
  arr[current] = value;
}

int main(void) {

  int temp[SIZE] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
  int *tmp = NULL, count = 0, i, j;

  // Loop for counting non-zero values in temp array.
  for (i = 0; i < SIZE; ++i)
    if (temp[i])
        count++;

  // Dynamically allocating space for tmp along with checking errors if any.
  if((tmp = (int *)malloc(count * sizeof(int))) == NULL)
     {
         printf("Memory Not Available.\n");
         exit(-1);
     }

  for(i = 0, j = 0; i < SIZE; i++){
    if(temp[i])
        push(tmp, temp[i], j++);
  }

  // Printing your desired output.
  for(i = 0; i < count; ++i)
    printf("%d\t", tmp[i]);

    free(tmp);
}

Here the size of tmp will change according to the non-zero elements of temp.
Now if you want to make the temp array a dynamic array, use the same approach as used for the tmp, just ask the user at run-time to input the size of temp and then its elements/values as well.


来源: stackexchange

问:
What does it mean for a type to distribute over unions?
I'm reading an article :"Unionize and Objectify: A Trick for Applying Conditional Types to Objects"

In TypeScript our most powerful tool is conditional types. This is
  because they have two unique abilities:

They distribute over unions.

They enable you to use the infer keyword.

What does 'distribute over unions' mean in general and in this context?

答:
The term distributive refers to how union types should be treated when subjected to type-level operations (such as keyof or mapped types).

Non-distributive (default) operations are applied to properties that exist on every member of the union.

Distributive operations are applied to all members of the union separately.

Let's use an example.

```<code>type Fruit =
  | { species: 'banana', curvature: number }
  | { species: 'apple', color: string }
</code>```

Let's assume that, for some reason, you want to know all possible keys that can exist on a Fruit.

Non-distributive

Your intuition may tell you to do:

```<code>type KeyOfFruit = keyof Fruit; // "species"
</code>```

However, this will give you only the properties that exist on every member of the union. In our example, species is the only common property shared by all Fruit.

It's the same as applying keyof to the union of the two types.

```<code>keyof ({ species: 'banana', curvature: number } | { species: 'apple', color: string })
</code>```

Distributive

With distribution, the operation is not performed on just the common properties. Instead, it is done on every member of the union separately. The results are then added together.

```<code>type DistributedKeyOf<T> =
  T extends any
    ? keyof T
    : never

type KeyOfFruit = DistributedKeyOf<Fruit>; // "species" | "curvature" | "color"
</code>```

In this case, TypeScript applied keyof to each member of the union, and summed the results.

```<code>keyof { species: 'banana', curvature: number } | keyof { species: 'apple', color: string }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The term distributive refers to how union types should be treated when subjected to type-level operations (such as keyof or mapped types).

Non-distributive (default) operations are applied to properties that exist on every member of the union.

Distributive operations are applied to all members of the union separately.

Let's use an example.

type Fruit =
  | { species: 'banana', curvature: number }
  | { species: 'apple', color: string }

Let's assume that, for some reason, you want to know all possible keys that can exist on a Fruit.

Non-distributive

Your intuition may tell you to do:

type KeyOfFruit = keyof Fruit; // "species"

However, this will give you only the properties that exist on every member of the union. In our example, species is the only common property shared by all Fruit.

It's the same as applying keyof to the union of the two types.

keyof ({ species: 'banana', curvature: number } | { species: 'apple', color: string })

Distributive

With distribution, the operation is not performed on just the common properties. Instead, it is done on every member of the union separately. The results are then added together.

type DistributedKeyOf<T> =
  T extends any
    ? keyof T
    : never

type KeyOfFruit = DistributedKeyOf<Fruit>; // "species" | "curvature" | "color"

In this case, TypeScript applied keyof to each member of the union, and summed the results.

keyof { species: 'banana', curvature: number } | keyof { species: 'apple', color: string }


问:
Do I had to loop? Is there a faster way to build dummy variables?
I have some plant data that looks like (but I have up to 7 attributes):

```<code>     Unnamed: 0     plant          att_1           att_2 ...
0            0     plant_a         sunlover        tall
1            1     plant_b         waterlover      sunlover
2            2     plant_c         fast growing    sunlover
</code>```

I tried to use pandas get_dummies like:

```<code>df = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c'],'C': [1, 2, 3]})

pd.get_dummies(df, prefix=['col1', 'col2']):
</code>```

.

```<code> C  col1_a  col1_b  col2_a  col2_b  col2_c
 0  1       1       0       0       1       0
 1  2       0       1       1       0       0
 2  3       1       0       0       0       1
</code>```

But sunlover should be encoded as 1 nevertheless it is in att_1 or att_2. Then I will end up with approx 30 dummy variables instead of 7 * 30 = 210 variables.
I have tried to loop through the whole set and add the value for each dummy:

```<code>for count, plants in enumerate(data_plants.iterrows()):
  print("First", count, plants)
  for attribute in plants:
        print("Second", count, attribute)
</code>```

The code is just printing because i saw the issue of time wasting code.
That work but it is not fast enough to use for 100k and more rows. I thought of using .value_counts() to get the attributes and then accessing the dataframe dummy variable to update that to 1, but then I will overwrite the attribute.  At the moment I am a litte bit lost and out of ideas. Perhaps I had to use an other package?

The goal would be something like:

```<code>     Unnamed: 0     plant          att_1           att_2       sunlover      waterlover     tall  ...
0            0     plant_a         sunlover        tall        1             0              1
1            1     plant_b         waterlover      sunlover    1             1              0
2            2     plant_c         fast growing    sunlover    1             0              0
</code>```

答:
What you need is only in some respect similar to get_dummies,
but you should proceed other way.

Define a viev of df, limited to your "attribute" columns:

```<code>attCols = df[['att_1', 'att_2']]
</code>```

In your target version add other "attribute" columns here.

Then define an index containing unique attribute names:

```<code>colVals = pd.Index(np.sort(attCols.stack().unique()))
</code>```

The third step is to define a function, computing the result for
the current row:

```<code>def myDummies(row):
    return pd.Series(colVals.isin(row).astype(int), index=colVals)
</code>```

And the last step is to join the result of application of this function
to each row from attCols:

```<code>df = df.join(attCols.apply(myDummies, axis=1))
</code>```

The result, for your sample data, is:

```<code>     plant         att_1     att_2  fast growing  sunlover  tall  waterlover
0  plant_a      sunlover      tall             0         1     1           0
1  plant_b    waterlover  sunlover             0         1     0           1
2  plant_c  fast growing  sunlover             1         1     0           0
</code>```

Body:
I have some plant data that looks like (but I have up to 7 attributes):

     Unnamed: 0     plant          att_1           att_2 ...
0            0     plant_a         sunlover        tall
1            1     plant_b         waterlover      sunlover
2            2     plant_c         fast growing    sunlover

I tried to use pandas get_dummies like:

df = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c'],'C': [1, 2, 3]})

pd.get_dummies(df, prefix=['col1', 'col2']):

.

 C  col1_a  col1_b  col2_a  col2_b  col2_c
 0  1       1       0       0       1       0
 1  2       0       1       1       0       0
 2  3       1       0       0       0       1

But sunlover should be encoded as 1 nevertheless it is in att_1 or att_2. Then I will end up with approx 30 dummy variables instead of 7 * 30 = 210 variables.
I have tried to loop through the whole set and add the value for each dummy:

for count, plants in enumerate(data_plants.iterrows()):
  print("First", count, plants)
  for attribute in plants:
        print("Second", count, attribute)

The code is just printing because i saw the issue of time wasting code.
That work but it is not fast enough to use for 100k and more rows. I thought of using .value_counts() to get the attributes and then accessing the dataframe dummy variable to update that to 1, but then I will overwrite the attribute.  At the moment I am a litte bit lost and out of ideas. Perhaps I had to use an other package?

The goal would be something like:

     Unnamed: 0     plant          att_1           att_2       sunlover      waterlover     tall  ...
0            0     plant_a         sunlover        tall        1             0              1
1            1     plant_b         waterlover      sunlover    1             1              0
2            2     plant_c         fast growing    sunlover    1             0              0

Body:
What you need is only in some respect similar to get_dummies,
but you should proceed other way.

Define a viev of df, limited to your "attribute" columns:

attCols = df[['att_1', 'att_2']]

In your target version add other "attribute" columns here.

Then define an index containing unique attribute names:

colVals = pd.Index(np.sort(attCols.stack().unique()))

The third step is to define a function, computing the result for
the current row:

def myDummies(row):
    return pd.Series(colVals.isin(row).astype(int), index=colVals)

And the last step is to join the result of application of this function
to each row from attCols:

df = df.join(attCols.apply(myDummies, axis=1))

The result, for your sample data, is:

     plant         att_1     att_2  fast growing  sunlover  tall  waterlover
0  plant_a      sunlover      tall             0         1     1           0
1  plant_b    waterlover  sunlover             0         1     0           1
2  plant_c  fast growing  sunlover             1         1     0           0


问:
Run a python module from an installed package
I have the following sample python application:

```<code>- testapp
-- __init__.py
-- main.py
-- hello
---- __init.py
---- hello.py
-- world
---- __init__.py
---- world.py

</code>```

main.py

```<code>from testapp.hello import hello
from testapp.world import world

if __name__ == "__main__":
    hello.say()
    world.say()
</code>```

world.py

```<code>def say():
    print('world')
</code>```

hello.py

```<code>def say():
    print('hello')
</code>```

then, I can go into testapp folder and run python -m main
I get the print of 'Hello world'

Fine, but what I would like to do is to build a package with this and install the package elsewhere to execute it.
I'm using poetry to build the whl package.
My question is, how to install the package somewhere else (on a server i.e.) and run it?
I would like to setup a distribution flow, where packages are build and stored on a private pypi repo, and servers can update and run the whole app.

I tried to make a poetry add on a folder on the server, it is working as the package is now installed but I  don't know how to launch the main module inside the package.

答:
super easy in fact..
after the package installation,

python -m testapp.main

that's it

Body:
I have the following sample python application:

- testapp
-- __init__.py
-- main.py
-- hello
---- __init.py
---- hello.py
-- world
---- __init__.py
---- world.py

main.py

from testapp.hello import hello
from testapp.world import world

if __name__ == "__main__":
    hello.say()
    world.say()

world.py

def say():
    print('world')

hello.py

def say():
    print('hello')

then, I can go into testapp folder and run python -m main
I get the print of 'Hello world'

Fine, but what I would like to do is to build a package with this and install the package elsewhere to execute it.
I'm using poetry to build the whl package.
My question is, how to install the package somewhere else (on a server i.e.) and run it?
I would like to setup a distribution flow, where packages are build and stored on a private pypi repo, and servers can update and run the whole app.

I tried to make a poetry add on a folder on the server, it is working as the package is now installed but I  don't know how to launch the main module inside the package.


问:
Running scripts within Pyramid framework (ie without a server)
I have a fair bit of experience with PHP frameworks and Python for scripting so am now taking the step to Pyramid.

I'd like to know what is the 'correct' way to run a script in Pyramid. That is, how should I set it up so that it is part of the application and has access to config and thus database but does not run through paster (or whatever WSGI).

As an example, say I have a web application which while a user is offline grabs Facebook updates through a web service. I want to write a script to poll that service and store in the database ready for next login.

How should I do this in terms of:

Adding variables in the ini file

Starting the script correctly

I understand the basics of Python modules and packages; however I don't fully understand Configurator/Paster/package setup, wherein I suspect the answer lies.

Thanks

Update:

Thanks, this seems along the lines of what I am looking for. I note that you have to follow a certain structure (eg have summary and parser attributes set) and that the function called command() will always be run. My test code now looks something like this:

```<code>class AwesomeCommand(Command):

max_args = 2
min_args = 2

usage = "NAME"
# These are required
summary = "Say hello!"
group_name = "My Package Name"
# Required:
parser = Command.standard_parser(verbose=True)

def command(self):

    # Load the config file/section
    config_file, section_name = self.args
    # What next?
</code>```

I'm now stuck as to how to get the settings themselves. For example, in init.py you can do this:

```<code> engine = engine_from_config(settings, 'sqlalchemy.')
</code>```

What do I need to do to transform the config file into the settings?

EDIT: The (simpler) way to do this in Pylons is here:
 Run Pylons controller as separate app?

答:
you need to make view for that action and then run it using:</p>

```<code>paster request development.ini /url_to_your_view
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a fair bit of experience with PHP frameworks and Python for scripting so am now taking the step to Pyramid.

I'd like to know what is the 'correct' way to run a script in Pyramid. That is, how should I set it up so that it is part of the application and has access to config and thus database but does not run through paster (or whatever WSGI).

As an example, say I have a web application which while a user is offline grabs Facebook updates through a web service. I want to write a script to poll that service and store in the database ready for next login.

How should I do this in terms of:

Adding variables in the ini file

Starting the script correctly

I understand the basics of Python modules and packages; however I don't fully understand Configurator/Paster/package setup, wherein I suspect the answer lies.

Thanks

Update:

Thanks, this seems along the lines of what I am looking for. I note that you have to follow a certain structure (eg have summary and parser attributes set) and that the function called command() will always be run. My test code now looks something like this:

class AwesomeCommand(Command):

max_args = 2
min_args = 2

usage = "NAME"
# These are required
summary = "Say hello!"
group_name = "My Package Name"
# Required:
parser = Command.standard_parser(verbose=True)

def command(self):

    # Load the config file/section
    config_file, section_name = self.args
    # What next?

I'm now stuck as to how to get the settings themselves. For example, in init.py you can do this:

 engine = engine_from_config(settings, 'sqlalchemy.')

What do I need to do to transform the config file into the settings?

EDIT: The (simpler) way to do this in Pylons is here:
 Run Pylons controller as separate app?

Body:
you need to make view for that action and then run it using:

paster request development.ini /url_to_your_view


问:
How to run raw SQL query without any expected result in Laravel 6?
In Laravel 6.x is any way to run raw SQL query without any expected result?

Like this one:

$query = 'INSERT INTO product_copys (SELECT '. implode(',', $myColumArray) .' FROM products)';
```

<p>I tried this:</p>

<pre class="lang-php prettyprint-override"><code>DB::run($query);
</code>```

...but it said FatalThrowableError: Call to protected method Illuminate\Database\Connection::run() from context 'Illuminate\Database\DatabaseManager'.

Any idea?

答:
did you try DB::statement() ?</p>

```<code>$query = 'INSERT INTO product_copys (SELECT '. implode(',', $myColumArray) .' FROM products)';

DB::statement($query);

</code>```

Body:
In Laravel 6.x is any way to run raw SQL query without any expected result?

Like this one:

$query = 'INSERT INTO product_copys (SELECT '. implode(',', $myColumArray) .' FROM products)';

I tried this:

DB::run($query);

...but it said FatalThrowableError: Call to protected method Illuminate\Database\Connection::run() from context 'Illuminate\Database\DatabaseManager'.

Any idea?

Body:
did you try DB::statement() ?

$query = 'INSERT INTO product_copys (SELECT '. implode(',', $myColumArray) .' FROM products)';

DB::statement($query);


问:
ORACLE APEX: Try to insert LOGIN PAGE custom email to a table
I try to create a different action when user presses the LOGIN button.
I can't insert values from the LOGIN form.

I Try with this code:

```<code>INSERT INTO DEBTOR_EMAIL VALUES (V':P9999_USERNAME', V':P9999_EMAIL');
</code>```

And I get an error:

ORA-06550: line 1, column 30: ORA-00936: missing expression

Could some please help how to reference form input fields?

答:
While the answer above is completely correct and does answer the actual question, I don't think this is the best way to handle this problem. With this solution, you have locked that functionality in the login page. In most cases, the application login is handled outside of apex (single sign on, social authentication, etc).  Adding code in the login screen is not possible in those cases.
A more robust solution is to create an application process with a processing point "After Authentication" and perform the insert statement there.

Body:
I try to create a different action when user presses the LOGIN button.
I can't insert values from the LOGIN form.

I Try with this code:

INSERT INTO DEBTOR_EMAIL VALUES (V':P9999_USERNAME', V':P9999_EMAIL');

And I get an error:

ORA-06550: line 1, column 30: ORA-00936: missing expression

Could some please help how to reference form input fields?


问:
Arduino: Difficulty with String concatenation
I'm (mis-)using the Arduino String class. My entire program:

```<code>void setup() {
  Serial.begin(9600);
}

void loop() {

  const String args[3] = {
    "foo", "bar", "baz"    };
  String result = "";
  Serial.println(result);
  result += args[0];
  Serial.println(result);
  result += args[1];
  Serial.println(result);
  result += args[2];
  Serial.println(result);
  Serial.println();
}
</code>```

This prints:

```<code>foo
foobar
foobarbaz

foo
foobar
foobarbaz

foo
foobar
foobarüÿ

foo
foobar
foobarüÿ

foo
foobar
foobar

foo
foobar
foobarüÿ

foo
foobar
foobarüÿ

foo
foobar
foobarüÿ
</code>```

I'm not sure why it doesn't just always print:

```<code>foo
foobar
foobarbaz
</code>```

What could I be doing wrong?

Update: I tried adding a fourth string to the array. Now the program stops running after 15 times through loop() or so.

Update 2: Here is the code for the String append operator:

```<code>const String & String::operator+=( const String &other )
{
  _length += other._length;
  if ( _length > _capacity )
  {
    char *temp = (char *)realloc(_buffer, _length + 1);
    if ( temp != NULL ) {
      _buffer = temp;
      _capacity = _length;
    } else {
      _length -= other._length;
      return *this;
    }
  }
  strcat( _buffer, other._buffer );
  return *this;
}
</code>```

Update 3: If I replace:

```<code>  String result = "";
</code>```

with:

```<code>  String result = args[0];
</code>```

The problem goes away. Interesting.

答:
The odd characters are a result of heap memory corruption.

There is nothing wrong with your code. This is a manifestation of a defect in the version of the memory allocation routines used by the current Arduino software. It currently ships with AVR Libc 1.6.4 which contains a number of memory allocation issues fixed in the latest 1.7.1 release.

I have run this code successfully (i.e. without the odd characters being displayed) on a Teensy 2.0 board using the teensyduino enhancement to the Arduino software. This contains fixes for these memory issues but unfortunately these fixes don't apply when programming Arduinos.

There are plans to upgrade the official Arduino software to the latest AVR Libc in August 2011.

Body:
I'm (mis-)using the Arduino String class. My entire program:

void setup() {
  Serial.begin(9600);
}

void loop() {

  const String args[3] = {
    "foo", "bar", "baz"    };
  String result = "";
  Serial.println(result);
  result += args[0];
  Serial.println(result);
  result += args[1];
  Serial.println(result);
  result += args[2];
  Serial.println(result);
  Serial.println();
}

This prints:

foo
foobar
foobarbaz

foo
foobar
foobarbaz

foo
foobar
foobarüÿ

foo
foobar
foobarüÿ

foo
foobar
foobar

foo
foobar
foobarüÿ

foo
foobar
foobarüÿ

foo
foobar
foobarüÿ

I'm not sure why it doesn't just always print:

foo
foobar
foobarbaz

What could I be doing wrong?

Update: I tried adding a fourth string to the array. Now the program stops running after 15 times through loop() or so.

Update 2: Here is the code for the String append operator:

const String & String::operator+=( const String &other )
{
  _length += other._length;
  if ( _length > _capacity )
  {
    char *temp = (char *)realloc(_buffer, _length + 1);
    if ( temp != NULL ) {
      _buffer = temp;
      _capacity = _length;
    } else {
      _length -= other._length;
      return *this;
    }
  }
  strcat( _buffer, other._buffer );
  return *this;
}

Update 3: If I replace:

  String result = "";

with:

  String result = args[0];

The problem goes away. Interesting.


问:
Javascript overwrite certain object keys
So, i have an object, for example

```<code>let header = {
        "navbar": {
            "buttons": {
                0: {
                    "content": "home",
                    "color": "blue",
                    "href": "home"
                },
                1: {
                    "content": "shop",
                    "color": "red",
                    "href": "shop"
                },
                2: {
                    "content": "contact",
                    "color": "gold",
                    "href": "contact"
                }
            }
        }
    };
</code>```

And i have a second object:

```<code>let header = {
        "navbar": {
            "buttons": {
                0: {
                    "content": "work",
                },
                2: {
                    "color": "blue",
                    "href": "test"
                }
            }
        }
    };
</code>```

Now i want to update the first object keys that exist in the second object. So the object looks like this:

```<code>let header = {
        "navbar": {
            "buttons": {
                0: {
                    "content": "work",
                    "color": "blue",
                    "href": "home"
                },
                1: {
                    "content": "shop",
                    "color": "red",
                    "href": "shop"
                },
                2: {
                    "content": "contact",
                    "color": "blue",
                    "href": "test"
                }
            }
        }
    };
</code>```

What is the easiest way of aproaching this problem?
Thanks in advance,
Jari

答:
const header1 = {
  navbar: {
    buttons: {
      0: {
        content: "home",
        color: "blue",
        href: "home",
      },
      1: {
        content: "shop",
        color: "red",
        href: "shop",
      },
      2: {
        content: "contact",
        color: "gold",
        href: "contact",
      },
    },
  },
};

const header2 = {
  navbar: {
    buttons: {
      0: {
        content: "work",
      },
      2: {
        color: "blue",
        href: "test",
      },
    },
  },
};

const header = {
  navbar: {
    buttons: {},
  },
};

// only given the keys are sequel
const header1Keys = Object.keys(header1.navbar.buttons)
const header2Keys = Object.keys(header2.navbar.buttons)
const keys = header1Keys.length > header2Keys.length ? header1Keys : header2Keys;

for (const key of keys) {
    header.navbar.buttons[key] = {...header1.navbar.buttons[key], ...header2.navbar.buttons[key]}
}

console.log(header)```

Body:
So, i have an object, for example

let header = {
        "navbar": {
            "buttons": {
                0: {
                    "content": "home",
                    "color": "blue",
                    "href": "home"
                },
                1: {
                    "content": "shop",
                    "color": "red",
                    "href": "shop"
                },
                2: {
                    "content": "contact",
                    "color": "gold",
                    "href": "contact"
                }
            }
        }
    };

And i have a second object:

let header = {
        "navbar": {
            "buttons": {
                0: {
                    "content": "work",
                },
                2: {
                    "color": "blue",
                    "href": "test"
                }
            }
        }
    };

Now i want to update the first object keys that exist in the second object. So the object looks like this:

let header = {
        "navbar": {
            "buttons": {
                0: {
                    "content": "work",
                    "color": "blue",
                    "href": "home"
                },
                1: {
                    "content": "shop",
                    "color": "red",
                    "href": "shop"
                },
                2: {
                    "content": "contact",
                    "color": "blue",
                    "href": "test"
                }
            }
        }
    };

What is the easiest way of aproaching this problem?
Thanks in advance,
Jari


问:
my archive build fails with error "no such module combine"
I recently added some Combine Code to my project (storyboard project), which run successfully on device and simulator.
Unfortunately if i try to build my archive file i got "no such module combine" error.

I searched long time via google and stackoverflow, but nothing helped. Anybody an idea?

find out, that it works for deployment target 11.0 and 12.0 and 13.0, just 10.0 says: no such module Combine

答:
I faced same trouble yesterday - a huge set of errors under RELEASE environment:

"use of undeclared type 'View'";

"no such module 'Combine'";

some other declarations from SwiftUI are also not recognisable;

In same time everything is fine under DEBUG environment.

The problem was in supporting iOS9+ and using SwiftUI for iOS13+ in same time.
It is probably a bug in Xcode (11.3.1, 11.5 are checked), but YES, we have 2 options here:

we have to increase deployment target up to iOS11+;

we can stay deployment target iOS9+, but we have to wrap any SwiftUI files in preprocessor directives like this:

```<code>import SwiftUI

#if canImport(Combine)
 ... any SwiftUI code here ...
#endif
</code>```

I choose the second option because we still need to support such an old version as iOS9.

Body:
I faced same trouble yesterday - a huge set of errors under RELEASE environment:

"use of undeclared type 'View'";

"no such module 'Combine'";

some other declarations from SwiftUI are also not recognisable;

In same time everything is fine under DEBUG environment.

The problem was in supporting iOS9+ and using SwiftUI for iOS13+ in same time.
It is probably a bug in Xcode (11.3.1, 11.5 are checked), but YES, we have 2 options here:

we have to increase deployment target up to iOS11+;

we can stay deployment target iOS9+, but we have to wrap any SwiftUI files in preprocessor directives like this:

import SwiftUI

#if canImport(Combine)
 ... any SwiftUI code here ...
#endif

I choose the second option because we still need to support such an old version as iOS9.


问:
How can I get the attribute value through Select-Xml?
How can I get an attribute value using Select-Xml?

Here is a fragment of an SSIS .dtsx file.

```<code><?xml version="1.0"?>
<DTS:Executable xmlns:DTS="www.microsoft.com/SqlServer/Dts"
  DTS:refId="Package"
  ...
  <DTS:ConnectionManagers>
    <DTS:ConnectionManager
      DTS:refId="Package.ConnectionManagers[DW02.EDW_Source]"
      DTS:CreationName="OLEDB"
      DTS:DTSID="{12F8E4D7-B122-40AF-A3BD-2B283F9EB3A0}"
      DTS:ObjectName="DW02.EDW_Source">
</code>```

The following code does not produce the desired result. How can I get the attribute value?

$x = Get-Content -Path .\ECW_SPECIALITY.dtsx
$namespace = @{DTS='www.microsoft.com/SqlServer/Dts'}
$x | Select-Xml -XPath '//@ConnectionManagers/@ConnectionManager[@DTS:ObjectName]' -Namespace $namespace
```

<p>I'm getting the following error:</p>

```
Select-Xml : Cannot convert value "<DTS:Executable xmlns:DTS="www.microsoft.com/
SqlServer/Dts"" to type "System.Xml.XmlDocument". Error: "Unexpected end of file
has occurred. The following elements are not closed:  Line 1, position 60."
At line:1 char:6
+ $x | Select-Xml -XPath '//@ConnectionManagers/@ConnectionManager[@DTS ...
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Select-Xml], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : InvalidCastToXmlDocument,Microsoft.PowerShell.Commands.SelectXmlCommand
```

答:
This solution could be useful:</p>

```<code>$rootpath  = 'C:\Users\EricBellet\Desktop\Test\'
$filename = 'connections.txt'

$ns = @{DTS='www.microsoft.com/SqlServer/Dts'}
$objectname = '//DTS:ConnectionManagers/DTS:ConnectionManager/@DTS:ObjectName'
$connectionstring = '//DTS:ConnectionManagers/DTS:ConnectionManager/DTS:ObjectData/DTS:ConnectionManager/@DTS:ConnectionString'

Get-ChildItem $rootpath -Include *.dtsx -Recurse | % { $_.FullName >> $filename; Select-Xml -Path $_.FullName -XPath $objectname -Namespace $ns | Select-Object -Expand Node | Select-Object -Expand '#text' >> $filename; Select-Xml -Path $_.FullName-XPath $connectionstring -Namespace $ns | Select-Object -Expand Node | Select-Object -Expand '#text' >> $filename; '' >> $filename; }
</code>```

Body:
How can I get an attribute value using Select-Xml?

Here is a fragment of an SSIS .dtsx file.

<?xml version="1.0"?>
<DTS:Executable xmlns:DTS="www.microsoft.com/SqlServer/Dts"
  DTS:refId="Package"
  ...
  <DTS:ConnectionManagers>
    <DTS:ConnectionManager
      DTS:refId="Package.ConnectionManagers[DW02.EDW_Source]"
      DTS:CreationName="OLEDB"
      DTS:DTSID="{12F8E4D7-B122-40AF-A3BD-2B283F9EB3A0}"
      DTS:ObjectName="DW02.EDW_Source">

The following code does not produce the desired result. How can I get the attribute value?

$x = Get-Content -Path .\ECW_SPECIALITY.dtsx
$namespace = @{DTS='www.microsoft.com/SqlServer/Dts'}
$x | Select-Xml -XPath '//@ConnectionManagers/@ConnectionManager[@DTS:ObjectName]' -Namespace $namespace

I'm getting the following error:

Select-Xml : Cannot convert value "<DTS:Executable xmlns:DTS="www.microsoft.com/
SqlServer/Dts"" to type "System.Xml.XmlDocument". Error: "Unexpected end of file
has occurred. The following elements are not closed:  Line 1, position 60."
At line:1 char:6
+ $x | Select-Xml -XPath '//@ConnectionManagers/@ConnectionManager[@DTS ...
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Select-Xml], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : InvalidCastToXmlDocument,Microsoft.PowerShell.Commands.SelectXmlCommand

Body:
This solution could be useful:

$rootpath  = 'C:\Users\EricBellet\Desktop\Test\'
$filename = 'connections.txt'

$ns = @{DTS='www.microsoft.com/SqlServer/Dts'}
$objectname = '//DTS:ConnectionManagers/DTS:ConnectionManager/@DTS:ObjectName'
$connectionstring = '//DTS:ConnectionManagers/DTS:ConnectionManager/DTS:ObjectData/DTS:ConnectionManager/@DTS:ConnectionString'

Get-ChildItem $rootpath -Include *.dtsx -Recurse | % { $_.FullName >> $filename; Select-Xml -Path $_.FullName -XPath $objectname -Namespace $ns | Select-Object -Expand Node | Select-Object -Expand '#text' >> $filename; Select-Xml -Path $_.FullName-XPath $connectionstring -Namespace $ns | Select-Object -Expand Node | Select-Object -Expand '#text' >> $filename; '' >> $filename; }


问:
How to update local state after the execution of multiple Apollo queries and mutations?
I am new to Apollo and I am missing something.
I have a query to get the currently logged in user that I run when the page load and it's executed from one of my very top components (the same one that contains also the matching logic for react-router):

```<code>export const GET_USER = gql`
  query {
    me {
      id
      email
    }
  }
`
</code>```

Then very nested in the DOM tree I have the login and logout buttons, both of them trigger mutations that are going to set or unset the session for the current user.
But... how do I update the state at the top of the app at this point?

I have read this blog post that suggests to wrap Apollo Hooks into other custom hooks:

```<code>const useAuth = () => {
  const { data: getUserData } = useQuery(GET_USER)
  const [login, { data: loginData } = useMutation(LOGIN)
  const [logout, { data: logoutData } = useMutation(LOGOUT)

  // Should I find out here if I have a user id or not?
  // It's doable, but not clean

  return { login, logout, userId }
}
</code>```

It's very unintuitive to me to make requests in this way, it was easy for me to understand to have these side effects in Redux or MobX actions... hence I am moving to use the Apollo client directly from there, even if it's not the suggested solution from the Apollo docs.

What am I not getting right?

答:
It will look something like below. The important part is that the mutation calls update function once it receives a response. That is the location where you manually update the cache. The goal would to replace the value of "me" that is in the apollo cache. The satisfying part is that once you get this working, the data retrieved from useQuery will automatically update (hence rerendering components using this hook). Here is the link to the documentation.</p>

```<code>const useAuth = () => {
  const { data: getUserData } = useQuery(GET_USER)
  const [mutateLogin] = useMutation(LOGIN)
  const [mutateLogout] = useMutation(LOGOUT)

  function login(..args) {
    mutateLogin({
      variables: args,
      update(proxy, {data}) {
        proxy.writeQuery({
          query: GET_USER,
          data: {
            me: (GET USER FROM data)
          }
        })
      }
    })
  }

  function logout() {
     mutateLogout({
       update(proxy, {data}) {
         proxy.writeQuery({
           query: GET_USER,
           data: {
             me: null
           }
         });
       }
     })
  }

  return { login, logout, userId }
}
</code>```

Body:
I am new to Apollo and I am missing something.
I have a query to get the currently logged in user that I run when the page load and it's executed from one of my very top components (the same one that contains also the matching logic for react-router):

export const GET_USER = gql`
  query {
    me {
      id
      email
    }
  }
`

Then very nested in the DOM tree I have the login and logout buttons, both of them trigger mutations that are going to set or unset the session for the current user.
But... how do I update the state at the top of the app at this point?

I have read this blog post that suggests to wrap Apollo Hooks into other custom hooks:

const useAuth = () => {
  const { data: getUserData } = useQuery(GET_USER)
  const [login, { data: loginData } = useMutation(LOGIN)
  const [logout, { data: logoutData } = useMutation(LOGOUT)

  // Should I find out here if I have a user id or not?
  // It's doable, but not clean

  return { login, logout, userId }
}

It's very unintuitive to me to make requests in this way, it was easy for me to understand to have these side effects in Redux or MobX actions... hence I am moving to use the Apollo client directly from there, even if it's not the suggested solution from the Apollo docs.

What am I not getting right?

Body:
It will look something like below. The important part is that the mutation calls update function once it receives a response. That is the location where you manually update the cache. The goal would to replace the value of "me" that is in the apollo cache. The satisfying part is that once you get this working, the data retrieved from useQuery will automatically update (hence rerendering components using this hook). Here is the link to the documentation.

const useAuth = () => {
  const { data: getUserData } = useQuery(GET_USER)
  const [mutateLogin] = useMutation(LOGIN)
  const [mutateLogout] = useMutation(LOGOUT)

  function login(..args) {
    mutateLogin({
      variables: args,
      update(proxy, {data}) {
        proxy.writeQuery({
          query: GET_USER,
          data: {
            me: (GET USER FROM data)
          }
        })
      }
    })
  }

  function logout() {
     mutateLogout({
       update(proxy, {data}) {
         proxy.writeQuery({
           query: GET_USER,
           data: {
             me: null
           }
         });
       }
     })
  }

  return { login, logout, userId }
}


问:
Is C# a high level language?
Is C# a high level language? I see it as more like medium level, but I am still unsure about this. Would you consider it as high level as some of the popular scripting languages?

Or does it accommodate more than one level?

答:
In consideration of Bob The Janitor's post:

Define a high level language? When C
  was created it was considered a high
  level language because it could be
  compiled on multiple architectures

I'd say it's moving from the "High" spot just like Java is.

Java's considered the assembly language of the JVM at this point.  New languages like Scala and Ruby seem to offer quite a variety that Java and C# are not going to easily match.

Don't get me wrong, I happen to think that Java/C# are at the perfect level--I'm just saying, as with C, these languages have a fairly set definition/feature set whereas "Features" will continue to be invented and implemented in newer languages.

If you don't believe me, have a look at Scala.. a completely different monster!

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Is C# a high level language?

OwnerDisplayName: Bill K


问:
XML Parsing too slow!
I wrote a java app to communicate with a web application using XML. After deployment, I found out it takes too long to parse the XML generated by the web application.

For example, it takes about 2 minutes to login; the login information is included in the url. The web application does its processing and responds to the Java app whether the login was successful using XML returned.

I used the standard java DOM parsing.

Is there a way I can optimize this process so that activities can be faster?

答:
What @Nathan said, plus I suggest doing some random pausing while it's taking so much time.
I've run into this in the past, and discovered it wasn't the parsing that was taking the time, but the creation and manipulation of data structure as it parsed.
You may see something different, but chances are it's a surprise.</p>

Title: XML Parsing too slow!


问:
Is it a good pattern to use array map instead of FlatList in React Native?
I am currently developing an App with comments section to article. Is it a good idea to write the screen with comments using ScrollView and map() through all elements in comments array? Something like:

```<code><ScrollView>
  {
    comments.map(comment => (
      <View>{/* comment related content */}</View>
    ))
  }
</ScrollView>
</code>```

The main reason why I don't want to use FlatList is scrolling ability to the specific comment, knowing that View with comment is going to have variable height (without FlatList I expect the ScrollView to allow me to scroll to the position returned by onLayout). The second thing is that FlatList doesn't render all items at once, so I will not be able to scroll to comment which is far down the list. The scroll mechanism will stuck at the last rendered element which is not what I want to achieve. Therefore I want to ditch FlatList completely. Will I have considerable performance problem if my list be like 50-60 of items? I don't expect the users to write more comments to the article.

答:
Absolutely not, FlatList is much more optimized and have more power than ScrollView

Anything that is possible with ScrollView can be done with FlatList but there are cases that are not supported by ScrollView like onEndReched, initialNumToRender, viewabilityConfig and much more also all of the props of ScrollView is supported by FlatList too.

Also, you can render any number of the items with FlatList at once.

Performance issues depend on what you are doing inside the items of the list but if 50 or 60 items in a list with some simpple view, there will be no issues even with ScrollView

Read more about FlatList.
https://reactnative.dev/docs/flatlist#docsNav

Body:
I am currently developing an App with comments section to article. Is it a good idea to write the screen with comments using ScrollView and map() through all elements in comments array? Something like:

<ScrollView>
  {
    comments.map(comment => (
      <View>{/* comment related content */}</View>
    ))
  }
</ScrollView>

The main reason why I don't want to use FlatList is scrolling ability to the specific comment, knowing that View with comment is going to have variable height (without FlatList I expect the ScrollView to allow me to scroll to the position returned by onLayout). The second thing is that FlatList doesn't render all items at once, so I will not be able to scroll to comment which is far down the list. The scroll mechanism will stuck at the last rendered element which is not what I want to achieve. Therefore I want to ditch FlatList completely. Will I have considerable performance problem if my list be like 50-60 of items? I don't expect the users to write more comments to the article.


问:
visiting a dynamic link that opened in new tab in cypress
Scenario:

While clicking a link/button in the application, a new tab is opened (with a dynamic url)

Is there a way in cypress to test somethings in the newly opened tab?

I cannot use cy.visit() as the url generated will be different each time

答:
Cypress documentation is very specific about it - Cypress doesn't have and will never have support for multi tabs.

However, they also provide plenty of workarounds for it. Please check here - there is plenty of example code for multiple cases, so you may choose what suits you best.
Hope it helps


问:
WifiManager.WifiInfo getSSID & getBSSID not working if targetSdkVersion >= 26
I'm getting correctly those values if I compile with API 27 but target API 25. If I set targetSdkVersion to 27, then, those values are not correctly retrieved.

Targeting SDK 25 or less, values are correct, but targeting 26 or more, I get those values:

SSID gives <unknown ssid>

BBSSID gives 02:00:00:00:00:00

These are my manifest permissions, all are normal permissions and don't require user grant:

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</code>```

And this is the sample code:

```<code>WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
WifiInfo connectionInfo = wifiManager.getConnectionInfo();
connectionInfo.getSSID();
connectionInfo.getBSSID();
</code>```

What has changed when targeting SDK 26 or more? what more should we do to get those values?

答:
I met with same problem. This problem happens higher android versions than API 23.
Solution:
You need to add below to build.gradle file.

```<code>implementation 'com.google.android.gms:play-services-location:15.0.0'
</code>```

And you permission below rules.

```<code><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
</code>```

Below code provides automatically permission for location in application.

```<code>        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        try {
            LocationRequest request = new LocationRequest()
                    .setFastestInterval(1500)
                    .setInterval(3000)
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

            builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(request);

            try {
                Task<LocationSettingsResponse> result =
                        LocationServices.getSettingsClient(this.getApplicationContext()).checkLocationSettings(builder.build());
                result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
                    @Override
                    public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
                        try {
                            task.getResult(ApiException.class);
                        } catch (ApiException e) {
                            switch (e.getStatusCode()) {
                                case LocationSettingsStatusCodes
                                        .RESOLUTION_REQUIRED:
                                    ResolvableApiException resolveApiException = (ResolvableApiException) e;
                                    try {
                                        resolveApiException.startResolutionForResult(WifiConnectionActivity.this, REQUEST_CHECK_CODE);
                                    } catch (IntentSender.SendIntentException ex) {
                                        ex.printStackTrace();
                                    } catch (ClassCastException ex) {

                                    }
                                    break;

                                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                                    break;
                            }
                        }
                    }
                });
            } catch (Exception x) {
            }
            checkPermissions();
        } catch (Exception a) {
        }
    }

void checkPermissions() {
    if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(WifiConnectionActivity.this, new String[]
                {
                        Manifest.permission.ACCESS_COARSE_LOCATION
                }, REQUEST_LOCATION);
    }
    else{
        //Toast.makeText(getActivity(), "GPS is already permissioned", Toast.LENGTH_SHORT).show();
    }
}
</code>```

Body:
I'm getting correctly those values if I compile with API 27 but target API 25. If I set targetSdkVersion to 27, then, those values are not correctly retrieved.

Targeting SDK 25 or less, values are correct, but targeting 26 or more, I get those values:

SSID gives <unknown ssid>

BBSSID gives 02:00:00:00:00:00

These are my manifest permissions, all are normal permissions and don't require user grant:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

And this is the sample code:

WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
WifiInfo connectionInfo = wifiManager.getConnectionInfo();
connectionInfo.getSSID();
connectionInfo.getBSSID();

What has changed when targeting SDK 26 or more? what more should we do to get those values?

Body:
I met with same problem. This problem happens higher android versions than API 23.
Solution:
You need to add below to build.gradle file.

implementation 'com.google.android.gms:play-services-location:15.0.0'

And you permission below rules.

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">

Below code provides automatically permission for location in application.

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        try {
            LocationRequest request = new LocationRequest()
                    .setFastestInterval(1500)
                    .setInterval(3000)
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

            builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(request);

            try {
                Task<LocationSettingsResponse> result =
                        LocationServices.getSettingsClient(this.getApplicationContext()).checkLocationSettings(builder.build());
                result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
                    @Override
                    public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
                        try {
                            task.getResult(ApiException.class);
                        } catch (ApiException e) {
                            switch (e.getStatusCode()) {
                                case LocationSettingsStatusCodes
                                        .RESOLUTION_REQUIRED:
                                    ResolvableApiException resolveApiException = (ResolvableApiException) e;
                                    try {
                                        resolveApiException.startResolutionForResult(WifiConnectionActivity.this, REQUEST_CHECK_CODE);
                                    } catch (IntentSender.SendIntentException ex) {
                                        ex.printStackTrace();
                                    } catch (ClassCastException ex) {

                                    }
                                    break;

                                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                                    break;
                            }
                        }
                    }
                });
            } catch (Exception x) {
            }
            checkPermissions();
        } catch (Exception a) {
        }
    }

void checkPermissions() {
    if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(WifiConnectionActivity.this, new String[]
                {
                        Manifest.permission.ACCESS_COARSE_LOCATION
                }, REQUEST_LOCATION);
    }
    else{
        //Toast.makeText(getActivity(), "GPS is already permissioned", Toast.LENGTH_SHORT).show();
    }
}


问:
How can I force update all the snapshot Gradle dependencies in intellij
I have a project with SNAPSHOT dependencies using gradle as its build tool in intellij.

The problem is that intellij is using SNAPSHOTS that are now outdated.

When I build the project on the command line

```<code>gradle build or
gradle clean build --refresh-dependencies
</code>```

On command line the latest dependencies are fetched. I also setup my grade file to always download snapshot dependencies according to this answer.

How can I force intellij to download all dependencies?

答:
EDIT

On Gradle 6+, snapshots are changing by default. So, no need to set changing = true anymore. But you still need to set resolutionStrategy.cacheChangingModulesFor to 0 seconds.

Previous answer:

Gradle caches changing modules for 24 hours by default. We can tell Gradle to refresh or redownload dependencies in the build script by marking those as 'changing'.

Follow these steps:

Step #1: Tell Gradle not to cache changing modules by set the value of the cacheChangingModulesFor property to 0 second:

```<code>configurations.all {
    resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}
</code>```

Step #2: Mark dependencies which are needed to be refreshed  or redownloaded, as changing module:

```<code>dependencies {
    implementation("com.howtoprogram.buysell:payment-api:0.0.1-SNAPSHOT") {
        changing = true
    }
}
</code>```

Source: Refresh or Redownload Dependencies in Gradle

Body:
I have a project with SNAPSHOT dependencies using gradle as its build tool in intellij.

The problem is that intellij is using SNAPSHOTS that are now outdated.

When I build the project on the command line

gradle build or
gradle clean build --refresh-dependencies

On command line the latest dependencies are fetched. I also setup my grade file to always download snapshot dependencies according to this answer.

How can I force intellij to download all dependencies?

Body:
EDIT

On Gradle 6+, snapshots are changing by default. So, no need to set changing = true anymore. But you still need to set resolutionStrategy.cacheChangingModulesFor to 0 seconds.

Previous answer:

Gradle caches changing modules for 24 hours by default. We can tell Gradle to refresh or redownload dependencies in the build script by marking those as 'changing'.

Follow these steps:

Step #1: Tell Gradle not to cache changing modules by set the value of the cacheChangingModulesFor property to 0 second:

configurations.all {
    resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}

Step #2: Mark dependencies which are needed to be refreshed  or redownloaded, as changing module:

dependencies {
    implementation("com.howtoprogram.buysell:payment-api:0.0.1-SNAPSHOT") {
        changing = true
    }
}

Source: Refresh or Redownload Dependencies in Gradle


问:
Spring Boot not loading @ConfigurationProperties
I am developing a Spring boot application where I am trying to configure custom properties for a bean which gives the suppourted extensions for my file .
When I run the application it runs sucessfully with 0 errors but the extensions are not loaded from the application.properties file.

Here is my code in application.properties :-----

```<code>suppourted.extensions[0]="jpg"
suppourted.extensions[1]="pdf"
suppourted.extensions[2]="png"

</code>```

Here is the code of the bean:--

```<code>package com.MyBoot.FirstBoot;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@ConfigurationProperties(prefix = "suppourted")
public class SuppourtedFiles {

    private List<String> extensions=new ArrayList<>();

    public List<String>getExtensions() {
        return extensions;
    }

    public void setExtensions(List<String>extensions) {
        this.extensions = extensions;
    }

    @Override
    public String toString() {
        return "SuppourtedFiles [extensions=" + extensions.size() + "]";
    }

}

</code>```

My main SpringBootApplication:----

```<code>package com.MyBoot.FirstBoot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class FirstBoot1Application {

    public static void main(String[] args) {
        SpringApplication.run(FirstBoot1Application.class, args);
    }

}

</code>```

I do not understand where the problem is occuring. Kindly help me.

Update:--

I want to send that object to my jsp page for displaying it using model not just create that bean in CommandLineRunner

答:
Hope below will work,

Applications:

package com.MyBoot.FirstBoot;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@EnableConfigurationProperties(SuppourtedFiles.class)
public class FirstBoot1Application implements CommandLineRunner {
    private final SuppourtedFiles suppourtedFiles;

    public FirstBoot1Application(SuppourtedFiles suppourtedFiles) {
        this.suppourtedFiles = suppourtedFiles;
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println(suppourtedFiles);
    }

    public static void main(String[] args) {
        SpringApplication.run(FirstBoot1Application.class, args);
    }

}
```

<p><strong>Configuration Class:</strong></p>

<pre class="lang-java prettyprint-override"><code>package com.MyBoot.FirstBoot;

import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@ConfigurationProperties(prefix = "suppourted")
public class SuppourtedFiles {

    private List<String> extensions = new ArrayList<>();

    public List<String> getExtensions() {
        return extensions;
    }

    public void setExtensions(List<String> extensions) {
        this.extensions = extensions;
    }

    @Override
    public String toString() {
        return "com.MyBoot.FirstBoot.SuppourtedFiles [extensions=" + Arrays.toString(extensions.toArray()) + "]"; // Changed to check if array is filled from spring or not.
    }

}
</code>```

minimum maven dependencies

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    </dependencies>
```

<p><strong>Optional Dependency for annotation processor:</strong></p>

<pre class="lang-xml prettyprint-override"><code><dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
</dependency>
</code>```

Please make sure your project packaging is jar or war

Controller:

@RestController
public class SampleController {
    private final SuppourtedFiles suppourtedFiles;

    public SampleController(SuppourtedFiles suppourtedFiles) {
        this.suppourtedFiles = suppourtedFiles;
    }

    @GetMapping("/extensions")
    public ResponseEntity<List<String>> extensions(){
        return ResponseEntity.ok(suppourtedFiles.getExtensions());
    }
}
```

<p><strong>Controller Dependency:</strong></p>

<pre class="lang-xml prettyprint-override"><code><dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
</code>```

Body:
I am developing a Spring boot application where I am trying to configure custom properties for a bean which gives the suppourted extensions for my file .
When I run the application it runs sucessfully with 0 errors but the extensions are not loaded from the application.properties file.

Here is my code in application.properties :-----

suppourted.extensions[0]="jpg"
suppourted.extensions[1]="pdf"
suppourted.extensions[2]="png"

Here is the code of the bean:--

package com.MyBoot.FirstBoot;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@ConfigurationProperties(prefix = "suppourted")
public class SuppourtedFiles {

    private List<String> extensions=new ArrayList<>();

    public List<String>getExtensions() {
        return extensions;
    }

    public void setExtensions(List<String>extensions) {
        this.extensions = extensions;
    }

    @Override
    public String toString() {
        return "SuppourtedFiles [extensions=" + extensions.size() + "]";
    }

}

My main SpringBootApplication:----

package com.MyBoot.FirstBoot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class FirstBoot1Application {

    public static void main(String[] args) {
        SpringApplication.run(FirstBoot1Application.class, args);
    }

}

I do not understand where the problem is occuring. Kindly help me.

Update:--

I want to send that object to my jsp page for displaying it using model not just create that bean in CommandLineRunner

Body:
Hope below will work,

Applications:

package com.MyBoot.FirstBoot;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@EnableConfigurationProperties(SuppourtedFiles.class)
public class FirstBoot1Application implements CommandLineRunner {
    private final SuppourtedFiles suppourtedFiles;

    public FirstBoot1Application(SuppourtedFiles suppourtedFiles) {
        this.suppourtedFiles = suppourtedFiles;
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println(suppourtedFiles);
    }

    public static void main(String[] args) {
        SpringApplication.run(FirstBoot1Application.class, args);
    }

}

Configuration Class:

package com.MyBoot.FirstBoot;

import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@ConfigurationProperties(prefix = "suppourted")
public class SuppourtedFiles {

    private List<String> extensions = new ArrayList<>();

    public List<String> getExtensions() {
        return extensions;
    }

    public void setExtensions(List<String> extensions) {
        this.extensions = extensions;
    }

    @Override
    public String toString() {
        return "com.MyBoot.FirstBoot.SuppourtedFiles [extensions=" + Arrays.toString(extensions.toArray()) + "]"; // Changed to check if array is filled from spring or not.
    }

}

minimum maven dependencies

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    </dependencies>

Optional Dependency for annotation processor:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
</dependency>

Please make sure your project packaging is jar or war

Controller:

@RestController
public class SampleController {
    private final SuppourtedFiles suppourtedFiles;

    public SampleController(SuppourtedFiles suppourtedFiles) {
        this.suppourtedFiles = suppourtedFiles;
    }

    @GetMapping("/extensions")
    public ResponseEntity<List<String>> extensions(){
        return ResponseEntity.ok(suppourtedFiles.getExtensions());
    }
}

Controller Dependency:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


答:
This is an example of a gaps-and-islands problem.  The difference of row numbers should do what you want:</p>

```<code>SELECT project, MIN(created_at) as start_dt, max(created_at) as end_dt
       TIMEDIFF(MAX(created_at), created_at) AS Duration
FROM (SELECT r.*,
             ROW_NUMBER() OVER (PARTITION BY project ORDER BY created_at) as seqnum_p,
             ROW_NUMBER() OVER (ORDER BY created_at) as seqnum
      FROM results r
     ) r
GROUP BY project, (seqnum - seqnum_p)
ORDER BY MIN(created_at);
</code>```

Title: Query a series of consecutive events in MySQL

Body:
I have a table of events with a project and a timestamp. I want to query all series of consecutive projects. If a project occurs consecutively more than once, the project should be listed several times. I would also like to get the start and end time and the duration of each series.

Example:

| project   | created_at              |
|-----------|-------------------------|
| project a | 2020-05-29 10:00:00.000 |
| project a | 2020-05-29 10:00:01.167 |
| project a | 2020-05-29 10:00:03.954 |
| project a | 2020-05-29 10:00:10.055 |
| project b | 2020-05-29 10:05:00.000 |
| project b | 2020-05-29 10:06:01.049 |
| project b | 2020-05-29 10:06:30.197 |
| project a | 2020-05-29 10:07:05.167 |
| project a | 2020-05-29 10:07:18.680 |

I would like to receive the following output:

| project   | start                   | end                     | duration     |
|-----------|-------------------------|-------------------------|--------------|
| project a | 2020-05-29 10:00:00.000 | 2020-05-29 10:00:10.055 | 00:00:10.055 |
| project b | 2020-05-29 10:05:00.000 | 2020-05-29 10:06:30.197 | 00:01:30:197 |
| project a | 2020-05-29 10:07:05.167 | 2020-05-29 10:07:18.680 | 00:00:13.513 |

I have the following query so far:

SELECT
project,
created_at AS "Start",
Max(created_at) AS "End",
TIMEDIFF(MAX(created_at), created_at) AS "Duration"
FROM results GROUP BY project;

This gives me the following output:

| project   | start                   | end                     | duration     |
|-----------|-------------------------|-------------------------|--------------|
| project a | 2020-05-29 10:00:00.000 | 2020-05-29 10:07:18.680 | 00:07:18.680 |
| project b | 2020-05-29 10:05:00.000 | 2020-05-29 10:06:30.197 | 00:01:30:197 |

The problem is that I only get two outputs through the group by. This in turn messes up the start and end date and duration to be output.

Is there a way around this so that I get my desired output?

Body:
This is an example of a gaps-and-islands problem.  The difference of row numbers should do what you want:

SELECT project, MIN(created_at) as start_dt, max(created_at) as end_dt
       TIMEDIFF(MAX(created_at), created_at) AS Duration
FROM (SELECT r.*,
             ROW_NUMBER() OVER (PARTITION BY project ORDER BY created_at) as seqnum_p,
             ROW_NUMBER() OVER (ORDER BY created_at) as seqnum
      FROM results r
     ) r
GROUP BY project, (seqnum - seqnum_p)
ORDER BY MIN(created_at);


问:
Python Twisted Scrapy AttributeError: 'DefaultOpenSSLContextFactory' object has no attribute 'privateKey'
In this code, I am trying to use a certificate .key and .pem file for a private page which I am authorized to use.

```<code>from OpenSSL import SSL
from twisted.internet import ssl

class BrowserLikeContextFactory(ScrapyClientContextFactory):

        def creatorForNetloc(self, hostname, port):

            certificate = ssl.DefaultOpenSSLContextFactory('path\\sample.key','path\\sample.pem')

            return optionsForClientTLS(hostname.decode("ascii"),
                trustRoot=platformTrust(),
                clientCertificate=certificate,
                extraCertificateOptions={
                'method': self._ssl_method,
                    })

</code>```

The two files exist in the path specified. I tried a fetch command in Scrapy and this was the first result.

However, after putting in the PEM pass phrase, this error was encountered? How do I resolve this?

答:
certificate = ssl.DefaultOpenSSLContextFactory('path\sample.key','path\sample.pem')

This isn't a certificate.  Later, something tries to use it as if it were and gets an attribute error because it doesn't have the privateKey attribute like a certificate would/should.

Try something like

```<code>with open("path/sample.key") as k:
    with open("path/sample.pem") as p:
        certificate = ssl.PrivateCertificate.loadPEM(k.read() + p.read())
</code>```

instead.

Body:
In this code, I am trying to use a certificate .key and .pem file for a private page which I am authorized to use.

from OpenSSL import SSL
from twisted.internet import ssl

class BrowserLikeContextFactory(ScrapyClientContextFactory):

        def creatorForNetloc(self, hostname, port):

            certificate = ssl.DefaultOpenSSLContextFactory('path\\sample.key','path\\sample.pem')

            return optionsForClientTLS(hostname.decode("ascii"),
                trustRoot=platformTrust(),
                clientCertificate=certificate,
                extraCertificateOptions={
                'method': self._ssl_method,
                    })

The two files exist in the path specified. I tried a fetch command in Scrapy and this was the first result.

However, after putting in the PEM pass phrase, this error was encountered? How do I resolve this?

Body:
certificate = ssl.DefaultOpenSSLContextFactory('path\sample.key','path\sample.pem')

This isn't a certificate.  Later, something tries to use it as if it were and gets an attribute error because it doesn't have the privateKey attribute like a certificate would/should.

Try something like

with open("path/sample.key") as k:
    with open("path/sample.pem") as p:
        certificate = ssl.PrivateCertificate.loadPEM(k.read() + p.read())

instead.


问:
R sapply new evaluation of function for each incidence in array
Thanks to lots of help, I've got an expression that substitutes the value from a rbinom into a vector, when certain conditions are met.  My problem is that it always substitutes the same value, i.e. does not do a new evaluation for each instance of the conditions being met.  I think I just need to wrap it in a sapply statement but haven't got the syntax correct. MWE:

```<code>arr1 <- c(8, 2, 5, 2, 3, 2, 2, 2, 8, 2, 4)
arr2 <- c(0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0)

arr1
arr1[Reduce("&", list(arr1 == 2, arr2 ==1))] <- rbinom(1,1,0.5) * 2
arr1
arr1
[1] 8 2 5 0 3 0 0 0 8 0 4
</code>```

I would have hoped that it changed some of the values but not others, so evaluated the result again for each instance.  Is this a good application of purrr::modify2 ? Thx. J

答:
Probably, you mean to use : </p>

```<code>inds <- arr1 == 2 & arr2 == 1
arr1[inds] <- rbinom(sum(inds), 1, 0.5) * 2
</code>```

Body:
Thanks to lots of help, I've got an expression that substitutes the value from a rbinom into a vector, when certain conditions are met.  My problem is that it always substitutes the same value, i.e. does not do a new evaluation for each instance of the conditions being met.  I think I just need to wrap it in a sapply statement but haven't got the syntax correct. MWE:

arr1 <- c(8, 2, 5, 2, 3, 2, 2, 2, 8, 2, 4)
arr2 <- c(0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0)

arr1
arr1[Reduce("&", list(arr1 == 2, arr2 ==1))] <- rbinom(1,1,0.5) * 2
arr1
arr1
[1] 8 2 5 0 3 0 0 0 8 0 4

I would have hoped that it changed some of the values but not others, so evaluated the result again for each instance.  Is this a good application of purrr::modify2 ? Thx. J

Body:
Probably, you mean to use :

inds <- arr1 == 2 & arr2 == 1
arr1[inds] <- rbinom(sum(inds), 1, 0.5) * 2