问:
Change timezone info for multiple datetime columns in pandas
Is there a easy way of converting all timestamp columns in a dataframe to local/any  timezone?

Not by doing it column by column?

答:
You can selectively apply the conversion to all datetime columns. First, select them with select_dtypes, then call tz_convert inside apply:

```<code>df2 = df.select_dtypes('datetimetz')
df[df2.columns] = df2.apply(lambda x: x.dt.tz_convert(None))
</code>```

"datetimetz" selects all datetime columns with timezone information.

Replace tz_convert(None) with tz_convert(your_timezone) to convert to a different timezone.

For plain datetime objects without any timezone info, call tz_localize first with your current timezone before calling tz_convert.

Body:
You can selectively apply the conversion to all datetime columns. First, select them with select_dtypes, then call tz_convert inside apply:

df2 = df.select_dtypes('datetimetz')
df[df2.columns] = df2.apply(lambda x: x.dt.tz_convert(None))

"datetimetz" selects all datetime columns with timezone information.

Replace tz_convert(None) with tz_convert(your_timezone) to convert to a different timezone.

For plain datetime objects without any timezone info, call tz_localize first with your current timezone before calling tz_convert.


来源: stackexchange

问:
PIL - saving file in memory?
I just want to open the image files in a folder, and convert them to jpeg if they are not already jpeg. Only thing is I need to save the file in memory, not to file. The reason is, in fact I'm reading the images from tfrecod file (tensorflow data file format), extract the image from it, check the file format, if not jpeg, convert to jpeg and then write back to tfrecord file after decoding properly. Because tensorflow object detection api doesn't accept any image format than jpeg unfortunately. Anyways, that's just the explanation why I need it.

To be able to do that, I need to keep the file in memory. So here is my code:

for counter, filename_with_path in enumerate(filenames):
    e = next(iter(tf.data.TFRecordDataset([filename_with_path])))
    example = tf.train.Example()
    example.ParseFromString(e.numpy())
    parsed = example.features.feature
    image_raw = parsed['image/encoded'].bytes_list.value[0]

    # After this point is important
    stream = BytesIO(image_raw)
    image = Image.open(stream) # Image is pillow image
    stream.close()

    if image.format != 'JPEG':
        tempFile = BytesIO()
        image.convert('RGB')
        image.save(tempFile, format="JPEG")

        newStream = BytesIO(tempFile)
        img = Image.open(newStream)
        newStream.close()

        print(filename, image.format)
        print(filename, img.format)
```

<p>When I run this, I get <code>ValueError: I/O operation on closed file.</code> on the line </p>

<pre class="lang-py prettyprint-override"><code>image.save(tempFile, format="JPEG")
</code>```

Any idea why this gives error? I saw this as suggested way to write in memory file: How to write PNG image to string with the PIL?

答:
The error is not about tempFile but about stream. You should not do stream.close() until you are done with image. This is a lazy API, so it can handle large images more efficiently.

```<code>for counter, filename_with_path in enumerate(filenames):
    ...

    stream = BytesIO(image_raw)
    image = Image.open(stream) # Image is pillow image
    # remove this line:
    # stream.close()

    if image.format != 'JPEG':
        tempFile = BytesIO()
        image.convert('RGB')
        image.save(tempFile, format="JPEG")

        # this wants bytes, not another BytesIO object, so read it
        newStream = BytesIO(tempFile.read())
        img = Image.open(newStream)
        # same thing, don't close until you are done with img
        # newStream.close()

        print(filename, image.format)
        print(filename, img.format)
</code>```

From the Pillow's Image.open docs:

This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method).

ContentLicense: CC BY-SA 4.0

Title: PIL - saving file in memory?

Body:
I just want to open the image files in a folder, and convert them to jpeg if they are not already jpeg. Only thing is I need to save the file in memory, not to file. The reason is, in fact I'm reading the images from tfrecod file (tensorflow data file format), extract the image from it, check the file format, if not jpeg, convert to jpeg and then write back to tfrecord file after decoding properly. Because tensorflow object detection api doesn't accept any image format than jpeg unfortunately. Anyways, that's just the explanation why I need it.

To be able to do that, I need to keep the file in memory. So here is my code:

for counter, filename_with_path in enumerate(filenames):
    e = next(iter(tf.data.TFRecordDataset([filename_with_path])))
    example = tf.train.Example()
    example.ParseFromString(e.numpy())
    parsed = example.features.feature
    image_raw = parsed['image/encoded'].bytes_list.value[0]

    # After this point is important
    stream = BytesIO(image_raw)
    image = Image.open(stream) # Image is pillow image
    stream.close()

    if image.format != 'JPEG':
        tempFile = BytesIO()
        image.convert('RGB')
        image.save(tempFile, format="JPEG")

        newStream = BytesIO(tempFile)
        img = Image.open(newStream)
        newStream.close()

        print(filename, image.format)
        print(filename, img.format)

When I run this, I get ValueError: I/O operation on closed file. on the line

image.save(tempFile, format="JPEG")

Any idea why this gives error? I saw this as suggested way to write in memory file: How to write PNG image to string with the PIL?

Body:
The error is not about tempFile but about stream. You should not do stream.close() until you are done with image. This is a lazy API, so it can handle large images more efficiently.

for counter, filename_with_path in enumerate(filenames):
    ...

    stream = BytesIO(image_raw)
    image = Image.open(stream) # Image is pillow image
    # remove this line:
    # stream.close()

    if image.format != 'JPEG':
        tempFile = BytesIO()
        image.convert('RGB')
        image.save(tempFile, format="JPEG")

        # this wants bytes, not another BytesIO object, so read it
        newStream = BytesIO(tempFile.read())
        img = Image.open(newStream)
        # same thing, don't close until you are done with img
        # newStream.close()

        print(filename, image.format)
        print(filename, img.format)

From the Pillow's Image.open docs:

This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method).


问:
mocha and ts-node UnhandledPromiseRejectionWarning:TypeError: Cannot convert undefined or null to object
I am trying to setup ts-node with mocha however the test script always fails.

I have tried

```<code>mocha --require ts-node/register --extensions ts,tsx --watch --watch-files src 'src/**/*.spec.{ts,tsx}'
</code>```

and

```<code>mocha --require ts-node/register src/**/*.spec.ts
</code>```

Also I tried installing ts-node locally and globally but always this is the output

```<code>> project@1.0.0 test /home/moamen/foo/baz
> mocha --require ts-node/register src/**/*.spec.ts

(node:48106) UnhandledPromiseRejectionWarning: TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at Object.help (/home/moamen/foo/baz/node_modules/yargs/lib/usage.js:240:22)
    at Object.self.showHelp (/home/moamen/foo/baz/node_modules/yargs/lib/usage.js:432:15)
    at Array.<anonymous> (/home/moamen/foo/baz/node_modules/mocha/lib/cli/cli.js:53:13)
    at Object.fail (/home/moamen/foo/baz/node_modules/yargs/lib/usage.js:41:17)
    at /home/moamen/foo/baz/node_modules/yargs/lib/command.js:246:36
(Use `node --trace-warnings ...` to show where the warning was created)
(node:48106) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:48106) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

and this is my tsconfig.json

```<code>{
    "compilerOptions": {
        "target": "es6" ,
        "module": "commonjs",
        "sourceMap": true ,
        "outDir": "dist" ,
        "strict": true ,
        "moduleResolution": "node" ,
        "esModuleInterop": true
        },
    "lib": ["es2015"]
}
</code>```

答: I had a quite similar issue. The error with me was inside a typescript test helper that did not compile and caused ts-node to fail very early</p>

Body:
I am trying to setup ts-node with mocha however the test script always fails.

I have tried

mocha --require ts-node/register --extensions ts,tsx --watch --watch-files src 'src/**/*.spec.{ts,tsx}'

and

mocha --require ts-node/register src/**/*.spec.ts

Also I tried installing ts-node locally and globally but always this is the output

> project@1.0.0 test /home/moamen/foo/baz
> mocha --require ts-node/register src/**/*.spec.ts

(node:48106) UnhandledPromiseRejectionWarning: TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at Object.help (/home/moamen/foo/baz/node_modules/yargs/lib/usage.js:240:22)
    at Object.self.showHelp (/home/moamen/foo/baz/node_modules/yargs/lib/usage.js:432:15)
    at Array.<anonymous> (/home/moamen/foo/baz/node_modules/mocha/lib/cli/cli.js:53:13)
    at Object.fail (/home/moamen/foo/baz/node_modules/yargs/lib/usage.js:41:17)
    at /home/moamen/foo/baz/node_modules/yargs/lib/command.js:246:36
(Use `node --trace-warnings ...` to show where the warning was created)
(node:48106) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:48106) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

and this is my tsconfig.json

{
    "compilerOptions": {
        "target": "es6" ,
        "module": "commonjs",
        "sourceMap": true ,
        "outDir": "dist" ,
        "strict": true ,
        "moduleResolution": "node" ,
        "esModuleInterop": true
        },
    "lib": ["es2015"]
}


问:
Solving function containing gamma in Python
I'm quite new to programming with python.

I was wondering, if there is a smart way to solve a function, which includes a gamma function with a certain shape and scale.

I already created a function G(x), which is the cdf of a gamma function up to a variable x. Now I want to solve another function including G(x). It should look like: 0=x+2*G(x)-b. Where b is a constant.

My code looks like that:

```<code>b= 10

def G(x):
  return gamma.cdf(x,a=4,scale=25)

f = solve(x+2*G(x)-b,x,dict=True)
</code>```

How is it possible to get a real value for G(x) in my solve function?

Thanks in advance!

答:
```<code>rom sympy import *
# from scipy.stats import gamma
# from sympy.stats import Arcsin, density, cdf
x, y, z, t, gamma, cdf = symbols('x y z t gamma cdf')

#sol = solve([x - 3, y - 1], dict=True)

from sympy.stats import Cauchy, density
from sympy import Symbol
x0 = Symbol("x0")
gamma = Symbol("gamma", positive=True)
z = Symbol("z")
X = Cauchy("x", x0, gamma)
density(X)(z)
print(density(X)(z))

sol = solve([x+2*density(X)(z)-10, y ], dict=True)
print(sol)
</code>```

Or:

```<code>from scipy.stats import gamma
from sympy import solve, Poly, Eq, Function, exp
from sympy.abc import x, y, z, a, b

def G(x):
  return gamma.cdf(x,a=4,scale=25)

b= 10

f = solve(x+2*G(x)-b,x,dict=True)
</code>```

stats cdf gamma solve sympy

Body:
I'm quite new to programming with python.

I was wondering, if there is a smart way to solve a function, which includes a gamma function with a certain shape and scale.

I already created a function G(x), which is the cdf of a gamma function up to a variable x. Now I want to solve another function including G(x). It should look like: 0=x+2*G(x)-b. Where b is a constant.

My code looks like that:

b= 10

def G(x):
  return gamma.cdf(x,a=4,scale=25)

f = solve(x+2*G(x)-b,x,dict=True)

How is it possible to get a real value for G(x) in my solve function?

Thanks in advance!

Body:
rom sympy import *
# from scipy.stats import gamma
# from sympy.stats import Arcsin, density, cdf
x, y, z, t, gamma, cdf = symbols('x y z t gamma cdf')

#sol = solve([x - 3, y - 1], dict=True)

from sympy.stats import Cauchy, density
from sympy import Symbol
x0 = Symbol("x0")
gamma = Symbol("gamma", positive=True)
z = Symbol("z")
X = Cauchy("x", x0, gamma)
density(X)(z)
print(density(X)(z))

sol = solve([x+2*density(X)(z)-10, y ], dict=True)
print(sol)

Or:

from scipy.stats import gamma
from sympy import solve, Poly, Eq, Function, exp
from sympy.abc import x, y, z, a, b

def G(x):
  return gamma.cdf(x,a=4,scale=25)

b= 10

f = solve(x+2*G(x)-b,x,dict=True)

stats cdf gamma solve sympy


问:
I need to split .txt file's content to a new line when it sees a backslash
I have a .txt file named "new.txt" and its content is;

```<code>nxy15\nxy995\nxy823\nxy721\nxy1\nxy1872\nxy3482\nxy878\nxy123\nxy8753\nxy1284\nxy4495\nxy4323\nxy812\nxy7123\nxy1273
</code>```

I need to format that .txt file, to be more specific i need to go to the next line when backslash is detected like one number for each line and i need to remove the letters aswell.

Formatted .txt file needs to look like this;

```<code>15
995
823
721
1
1872
...
</code>```

So far, because of my little Java knowledge, i managed to just read the file and output it. Here it is;

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadingFile{
    public static void main(String[] args) {
        try {
            File file = new File("C:\\new.txt");
            Scanner read = new Scanner(file);
            while (read.hasNextLine()) {
                String obj2 = read.nextLine();
                System.out.println(obj2);
            }
            read.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
</code>```

I need to solve this so i can move on to the next question but i'm stuck with this question and can't solve it and i'm trying for three hours.

Any help or clues are highly appreciated, thanks.

答:
A functional way of doing it (since Java 8) would be something like:

Files.lines(Paths.get("C:\\new.txt"))
                .flatMap(s -> Arrays.stream(s.split("\\\\")))
                .map(s -> s.substring(3))
                .forEach(System.out::println);
```

<p>If you want to sink the results into another file you can drop the <code>forEach</code> and feed the stream into a <code>Files.write</code>:</p>

<pre class="lang-java prettyprint-override"><code>Files.write(Paths.get("C:\\formatted.txt"),
            Files.lines(Paths.get("C:\\new.txt"))
                .flatMap(s -> Arrays.stream(s.split("\\\\")))
                .map(s -> s.substring(3)).collect(Collectors.toList()));
</code>```

Please note that this is not contemplating possible input errors (e.g. different format in the string nxy123), but that should not be difficult to add.

Body:
I have a .txt file named "new.txt" and its content is;

nxy15\nxy995\nxy823\nxy721\nxy1\nxy1872\nxy3482\nxy878\nxy123\nxy8753\nxy1284\nxy4495\nxy4323\nxy812\nxy7123\nxy1273

I need to format that .txt file, to be more specific i need to go to the next line when backslash is detected like one number for each line and i need to remove the letters aswell.

Formatted .txt file needs to look like this;

15
995
823
721
1
1872
...

So far, because of my little Java knowledge, i managed to just read the file and output it. Here it is;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadingFile{
    public static void main(String[] args) {
        try {
            File file = new File("C:\\new.txt");
            Scanner read = new Scanner(file);
            while (read.hasNextLine()) {
                String obj2 = read.nextLine();
                System.out.println(obj2);
            }
            read.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

I need to solve this so i can move on to the next question but i'm stuck with this question and can't solve it and i'm trying for three hours.

Any help or clues are highly appreciated, thanks.

Body:
A functional way of doing it (since Java 8) would be something like:

Files.lines(Paths.get("C:\\new.txt"))
                .flatMap(s -> Arrays.stream(s.split("\\\\")))
                .map(s -> s.substring(3))
                .forEach(System.out::println);

If you want to sink the results into another file you can drop the forEach and feed the stream into a Files.write:

Files.write(Paths.get("C:\\formatted.txt"),
            Files.lines(Paths.get("C:\\new.txt"))
                .flatMap(s -> Arrays.stream(s.split("\\\\")))
                .map(s -> s.substring(3)).collect(Collectors.toList()));

Please note that this is not contemplating possible input errors (e.g. different format in the string nxy123), but that should not be difficult to add.


问:
How can I alternate "visible" rows in an html table using jQuery
I have this code that does alternating rows for a html in jQuery:

```<code>function AlternateRowColors() {

    $("table.altRow1 tr").filter(function() {
    return true;
    }).filter(':even').addClass('alt');

    $("tr.alt td[rowspan]").each(function() {
    $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('alt');
    });

    $('ins').css("background-color", "#cfc")
}
</code>```

This works great (feel free to add suggestions if anything is inefficient above).

The issue that I have now is that I have code that hides a bunch of rows (details on why are not really relevant for this question), the main point is that I want to have a function that can do alternative row colors to current visible rows.

I am hiding rows by simply adding a class to certain rows and them calling .hide() on that class.

Is there any suggestion to get alternative row colors (like the above code) but have it work on the visible rows so no matter what is hidden, the table always looks correct in terms of alt row coloring.

答:
You might want to call this function again when you are hiding rows, so that it can re-calculate odd and even rows. You can use the not-selector on your tablerows to get only the visible rows, like this:</p>

```<code>$('table.altRow1 tr:not(.hidden)')
</code>```

Body:
I have this code that does alternating rows for a html in jQuery:

function AlternateRowColors() {

    $("table.altRow1 tr").filter(function() {
    return true;
    }).filter(':even').addClass('alt');

    $("tr.alt td[rowspan]").each(function() {
    $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('alt');
    });

    $('ins').css("background-color", "#cfc")
}

This works great (feel free to add suggestions if anything is inefficient above).

The issue that I have now is that I have code that hides a bunch of rows (details on why are not really relevant for this question), the main point is that I want to have a function that can do alternative row colors to current visible rows.

I am hiding rows by simply adding a class to certain rows and them calling .hide() on that class.

Is there any suggestion to get alternative row colors (like the above code) but have it work on the visible rows so no matter what is hidden, the table always looks correct in terms of alt row coloring.

Body:
You might want to call this function again when you are hiding rows, so that it can re-calculate odd and even rows. You can use the not-selector on your tablerows to get only the visible rows, like this:

$('table.altRow1 tr:not(.hidden)')

ContentLicense: CC BY-SA 3.0


问:
What does it mean when there are two functions with the 'arrow function indicator' between them?
I have seen arrow function examples like this:

```<code>people.forEach((person) => {
  console.log(person.id + person.name);
});
</code>```

and this all makes sense to me. But what does this mean?

```<code>dispatch = (action) => {
      this.setState((state) => reducer(state, action));
    }
</code>```

It looks like action is the parameter passed to dispatch() and then what happens in the body of the function? Does it take the result of reducer and set the state? If so, why? What is the syntax?
Thank you.

答:
The first block of code is equivalent to the code below.

people.forEach take one params which is a callback function
Similar with the second block of code with dispatch

const callback = (person) => {
  console.log(person.id + person.name);
}

people.forEach(callback);```
</div>
</div>
</p>

<p>The implementation of <code>dispatch</code> might be like this</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//Implementation
const dispatch = (callback) =>{
  const action = "something" // this might sth from somewhere, just get the idea of it
  callback(action)
}

// Similar to people.forEach we have
const callback = (action) => {
      this.setState((state) => reducer(state, action));
}
dispatch(callback)</code>```

They are called high-order function

Body:
I have seen arrow function examples like this:

people.forEach((person) => {
  console.log(person.id + person.name);
});

and this all makes sense to me. But what does this mean?

dispatch = (action) => {
      this.setState((state) => reducer(state, action));
    }

It looks like action is the parameter passed to dispatch() and then what happens in the body of the function? Does it take the result of reducer and set the state? If so, why? What is the syntax?
Thank you.

Body:
The first block of code is equivalent to the code below.

people.forEach take one params which is a callback function
Similar with the second block of code with dispatch

const callback = (person) => {
  console.log(person.id + person.name);
}

people.forEach(callback);

The implementation of dispatch might be like this

//Implementation
const dispatch = (callback) =>{
  const action = "something" // this might sth from somewhere, just get the idea of it
  callback(action)
}

// Similar to people.forEach we have
const callback = (action) => {
      this.setState((state) => reducer(state, action));
}
dispatch(callback)

They are called high-order function


问:
timer in thread problem
I have my application in which in three datagridview independently in three thread load data from wcf service. I execute in each thread timer which every second load this data.

My problem is that every time my thread go threw each thread but only like I show in method timerNowyYork_Elapsed

Any idea why this happens ? I bad lock thread?

this code :

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;

namespace Sprawdzanie_warunków_pogodowych
{
public partial class Form1 : Form
{
    PogodaEntities entity = new PogodaEntities();
    System.Timers.Timer timerKrakow = new System.Timers.Timer();
    System.Timers.Timer timerSzczecin = new System.Timers.Timer();
    System.Timers.Timer timerNowyYork = new System.Timers.Timer();
    KeyValuePair<string, string> krakowInfo;
    KeyValuePair<string, string> szczecinInfo;
    KeyValuePair<string, string> nowyYorkInfo;

    public Form1()
    {
        System.Net.ServicePointManager.Expect100Continue = false;
        InitializeComponent();
        List<MiastoContainer> miasta = (from miasto in entity.Miasta
                                        select new MiastoContainer()
                                   {
                                       MiastoName = miasto.Nazwa,
                                       Panstwo = miasto.Państwo
                                   }).ToList();
        krakowInfo = new KeyValuePair<string, string>(miasta[0].MiastoName, miasta[0].Panstwo);
        szczecinInfo = new KeyValuePair<string, string>(miasta[1].MiastoName, miasta[1].Panstwo);
        nowyYorkInfo = new KeyValuePair<string, string>(miasta[2].MiastoName, miasta[2].Panstwo);

        ParameterizedThreadStart ptsKrakow = new ParameterizedThreadStart(PobierzKrakow);
        Thread tKrakow = new Thread(ptsKrakow);
        tKrakow.Start(this.dataGridViewKrakow);

        ParameterizedThreadStart ptsSzczecin = new ParameterizedThreadStart(PobierzSzczecin);
        Thread tSzczecin = new Thread(ptsSzczecin);
        tSzczecin.Start(this.dataGridViewSzczecin);
    }

    private void oAutorzeToolStripMenuItem_Click(object sender, EventArgs e)
    {
        new AboutBox1().Show();
    }

    private void zapiszRaportToolStripMenuItem_Click(object sender, EventArgs e)
    {

    }

    public void PobierzKrakow(object parameters)
    {
        this.timerKrakow.Elapsed += new System.Timers.ElapsedEventHandler(timerKrakow_Elapsed);
        this.timerKrakow.Enabled = true;
        this.timerKrakow.Interval = 1000;
        this.timerKrakow.Start();
    }

    public void PobierzSzczecin(object parameters)
    {
        this.timerSzczecin.Elapsed += new System.Timers.ElapsedEventHandler(timerSzczecin_Elapsed);
        this.timerSzczecin.Enabled = true;
        this.timerSzczecin.Interval = 1000;
        this.timerSzczecin.Start();
    }

    public void PobierzNowyYork(object parameters)
    {
        this.timerNowyYork.Elapsed += new System.Timers.ElapsedEventHandler(timerNowyYork_Elapsed);
        this.timerNowyYork.Enabled = true;
        this.timerNowyYork.Interval = 1000;
        this.timerNowyYork.Start();
    }

    void timerNowyYork_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {  GlobalWeather.Weather weather = new GlobalWeather.Weather();
        lock (weather)
        {
            //thread always start from here
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(nowyYorkInfo.Key, nowyYorkInfo.Value));
           //and end here , never come any line further
            weatherList.Add(weather.GetPressure(nowyYorkInfo.Key, nowyYorkInfo.Value));
            weatherList.Add(weather.GetHumidity(nowyYorkInfo.Key, nowyYorkInfo.Value));
            weatherList.Add(weather.GetVisibility(nowyYorkInfo.Key, nowyYorkInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == nowyYorkInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewNowyYork.Rows.Add(warunki);
        }
    }

    void timerSzczecin_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        GlobalWeather.Weather weather = new GlobalWeather.Weather();

        lock (weather)
        {
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetPressure(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetHumidity(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetVisibility(szczecinInfo.Key, szczecinInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == szczecinInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewSzczecin.Rows.Add(warunki);
        }
    }
    void timerKrakow_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        GlobalWeather.Weather weather = new GlobalWeather.Weather();

        lock (weather)
        {
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetPressure(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetHumidity(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetVisibility(krakowInfo.Key, krakowInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == krakowInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewKrakow.Rows.Add(warunki);
        }
    }
}

class MiastoContainer
{
    string miastoName;

    public string MiastoName
    {
        get { return miastoName; }
        set { miastoName = value; }
    }
    string panstwo;

    public string Panstwo
    {
        get { return panstwo; }
        set { panstwo = value; }
    }

    public MiastoContainer()
    { }

    public MiastoContainer(string miasto, string panstwo)
    {
        this.MiastoName = miasto;
        this.Panstwo = panstwo;
    }

    public void Add(MiastoContainer item)
    {
        ((ICollection<MiastoContainer>)this).Add(item);
    }

}
</code>```

}

答:
Your locks are completely useless. As you are locking on an object that you just created, each lock will have it's own identifier and does not affect each other at all.

You need all locks that should exclude each other to use the same object as identifier.

Title: timer in thread problem

Body:
I have my application in which in three datagridview independently in three thread load data from wcf service. I execute in each thread timer which every second load this data.

My problem is that every time my thread go threw each thread but only like I show in method timerNowyYork_Elapsed

Any idea why this happens ? I bad lock thread?

this code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;

namespace Sprawdzanie_warunków_pogodowych
{
public partial class Form1 : Form
{
    PogodaEntities entity = new PogodaEntities();
    System.Timers.Timer timerKrakow = new System.Timers.Timer();
    System.Timers.Timer timerSzczecin = new System.Timers.Timer();
    System.Timers.Timer timerNowyYork = new System.Timers.Timer();
    KeyValuePair<string, string> krakowInfo;
    KeyValuePair<string, string> szczecinInfo;
    KeyValuePair<string, string> nowyYorkInfo;

    public Form1()
    {
        System.Net.ServicePointManager.Expect100Continue = false;
        InitializeComponent();
        List<MiastoContainer> miasta = (from miasto in entity.Miasta
                                        select new MiastoContainer()
                                   {
                                       MiastoName = miasto.Nazwa,
                                       Panstwo = miasto.Państwo
                                   }).ToList();
        krakowInfo = new KeyValuePair<string, string>(miasta[0].MiastoName, miasta[0].Panstwo);
        szczecinInfo = new KeyValuePair<string, string>(miasta[1].MiastoName, miasta[1].Panstwo);
        nowyYorkInfo = new KeyValuePair<string, string>(miasta[2].MiastoName, miasta[2].Panstwo);

        ParameterizedThreadStart ptsKrakow = new ParameterizedThreadStart(PobierzKrakow);
        Thread tKrakow = new Thread(ptsKrakow);
        tKrakow.Start(this.dataGridViewKrakow);

        ParameterizedThreadStart ptsSzczecin = new ParameterizedThreadStart(PobierzSzczecin);
        Thread tSzczecin = new Thread(ptsSzczecin);
        tSzczecin.Start(this.dataGridViewSzczecin);
    }

    private void oAutorzeToolStripMenuItem_Click(object sender, EventArgs e)
    {
        new AboutBox1().Show();
    }

    private void zapiszRaportToolStripMenuItem_Click(object sender, EventArgs e)
    {

    }

    public void PobierzKrakow(object parameters)
    {
        this.timerKrakow.Elapsed += new System.Timers.ElapsedEventHandler(timerKrakow_Elapsed);
        this.timerKrakow.Enabled = true;
        this.timerKrakow.Interval = 1000;
        this.timerKrakow.Start();
    }

    public void PobierzSzczecin(object parameters)
    {
        this.timerSzczecin.Elapsed += new System.Timers.ElapsedEventHandler(timerSzczecin_Elapsed);
        this.timerSzczecin.Enabled = true;
        this.timerSzczecin.Interval = 1000;
        this.timerSzczecin.Start();
    }

    public void PobierzNowyYork(object parameters)
    {
        this.timerNowyYork.Elapsed += new System.Timers.ElapsedEventHandler(timerNowyYork_Elapsed);
        this.timerNowyYork.Enabled = true;
        this.timerNowyYork.Interval = 1000;
        this.timerNowyYork.Start();
    }

    void timerNowyYork_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {  GlobalWeather.Weather weather = new GlobalWeather.Weather();
        lock (weather)
        {
            //thread always start from here
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(nowyYorkInfo.Key, nowyYorkInfo.Value));
           //and end here , never come any line further
            weatherList.Add(weather.GetPressure(nowyYorkInfo.Key, nowyYorkInfo.Value));
            weatherList.Add(weather.GetHumidity(nowyYorkInfo.Key, nowyYorkInfo.Value));
            weatherList.Add(weather.GetVisibility(nowyYorkInfo.Key, nowyYorkInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == nowyYorkInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewNowyYork.Rows.Add(warunki);
        }
    }

    void timerSzczecin_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        GlobalWeather.Weather weather = new GlobalWeather.Weather();

        lock (weather)
        {
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetPressure(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetHumidity(szczecinInfo.Key, szczecinInfo.Value));
            weatherList.Add(weather.GetVisibility(szczecinInfo.Key, szczecinInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == szczecinInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewSzczecin.Rows.Add(warunki);
        }
    }
    void timerKrakow_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        GlobalWeather.Weather weather = new GlobalWeather.Weather();

        lock (weather)
        {
            List<object> weatherList = new List<object>();
            weatherList.Add(weather.GetTempreature(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetPressure(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetHumidity(krakowInfo.Key, krakowInfo.Value));
            weatherList.Add(weather.GetVisibility(krakowInfo.Key, krakowInfo.Value));
            entity.SaveChanges();

            WarunkiPogodowe warunki = new WarunkiPogodowe()
            {
                Temperatura = weatherList[0].ToString(),
                Ciśnienie = weatherList[1].ToString(),
                Wilgotność = weatherList[2].ToString(),
                Widoczność = weatherList[3].ToString(),
                DataSprawdzenia = DateTime.Now
            };
            entity.AddToWarunkiPogodowe(warunki);
            entity.SaveChanges();
            int miastoId = entity.Miasta.First(m => m.Nazwa == krakowInfo.Key).id;
            Miasto_has_WarunkiPogodowe m_has_wp = new Miasto_has_WarunkiPogodowe()
            {
                idMiasto_FK = miastoId,
                idWarunkiPogodowe_FK = warunki.id
            };
            entity.AddToMiasto_has_WarunkiPogodowe(m_has_wp);
            entity.SaveChanges();

            this.dataGridViewKrakow.Rows.Add(warunki);
        }
    }
}

class MiastoContainer
{
    string miastoName;

    public string MiastoName
    {
        get { return miastoName; }
        set { miastoName = value; }
    }
    string panstwo;

    public string Panstwo
    {
        get { return panstwo; }
        set { panstwo = value; }
    }

    public MiastoContainer()
    { }

    public MiastoContainer(string miasto, string panstwo)
    {
        this.MiastoName = miasto;
        this.Panstwo = panstwo;
    }

    public void Add(MiastoContainer item)
    {
        ((ICollection<MiastoContainer>)this).Add(item);
    }

}

}


问:
Confused between whether or not to change the class_mode from binary to categorical in Imagedatagenerator
When i shifted from 2 classes to 4 classes in a CNN model. I got errors. A lot of people helped me solve them, like I needed to change loss to sparse_categorical_crossentropy and last layer activation function.

```<code>model.compile(loss='sparse_categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

history = model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples//batch_size,
    epochs=epochs,
    validation_data = validation_generator,
    validation_steps = validation_generator.samples // batch_size,
)
</code>```

I am confused as I had to change the loss function from binary_crossentropy to categorical_crossenpropy. I want to know whether I should change the class_mode from binary to categorical for 4 classes or should I leave it as binary.

```<code>train_datagen=ImageDataGenerator(
    rescale=1./255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip = True,
    #vertical_flip = True,
    validation_split=0.2,
    brightness_range=[0.5, 1.5]

)

#test_datagen = ImageDataGenerator(
 #   rescale=1./255,
 #
#)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width,img_height),
    batch_size=batch_size,
    shuffle=True,
    class_mode='binary',
    subset='training'
)

validation_generator = train_datagen.flow_from_directory(
    train_data_dir, # same directory as training data
    target_size=(img_height, img_width),
    batch_size=batch_size,
    class_mode='binary',
    subset='validation'
    #validation_data_dir,
    #target_size=(img_width,img_height),
    #batch_size=batch_size,
    #class_mode='binary'
)
</code>```

答:
I think reading the documentation would be a good starting point. It would answer all your questions, and then some.

class_mode: One of "categorical", "binary", "sparse", "input", or None. Default: "categorical". Determines the type of label arrays that are returned: - "categorical" will be 2D one-hot encoded labels, - "binary" will be 1D binary labels, "sparse" will be 1D integer labels, - "input" will be images identical to input images (mainly used to work with autoencoders). - If None, no labels are returned (the generator will only yield batches of image data, which is useful to use with model.predict_generator()). Please note that in case of class_mode None, the data still needs to reside in a subdirectory of directory for it to work correctly.

So you should use categorical_crossentropy as loss function if you choose categorical for class_mode, and sparse_categorical_crossentropy if you choose sparse.

Body:
When i shifted from 2 classes to 4 classes in a CNN model. I got errors. A lot of people helped me solve them, like I needed to change loss to sparse_categorical_crossentropy and last layer activation function.

model.compile(loss='sparse_categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

history = model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples//batch_size,
    epochs=epochs,
    validation_data = validation_generator,
    validation_steps = validation_generator.samples // batch_size,
)

I am confused as I had to change the loss function from binary_crossentropy to categorical_crossenpropy. I want to know whether I should change the class_mode from binary to categorical for 4 classes or should I leave it as binary.

train_datagen=ImageDataGenerator(
    rescale=1./255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip = True,
    #vertical_flip = True,
    validation_split=0.2,
    brightness_range=[0.5, 1.5]

)

#test_datagen = ImageDataGenerator(
 #   rescale=1./255,
 #
#)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width,img_height),
    batch_size=batch_size,
    shuffle=True,
    class_mode='binary',
    subset='training'
)

validation_generator = train_datagen.flow_from_directory(
    train_data_dir, # same directory as training data
    target_size=(img_height, img_width),
    batch_size=batch_size,
    class_mode='binary',
    subset='validation'
    #validation_data_dir,
    #target_size=(img_width,img_height),
    #batch_size=batch_size,
    #class_mode='binary'
)


问:
oracle - fetch first n json objects from json array
I have a table in which one column we have json array data. in some rows this json is very big (with 10000+ json objects) like below. wanted to know is there any way just to select first 250 objects from the array-</p>

```<code>[
   {
      "product":"Vegetable",
      "name":"Potato",
      "price":"$60.00"
   },
   {
      "product":"Fruit",
      "name":"Mango",
      "price":"$3.30"
   },
   {
      "product":"Milk",
      "name":"Milk",
      "price":"$1.08"
   },
.....10,000
]
</code>```

答:
An analytic function such as ROW_NUMBER() might be used within the subquery to determine the restriction, and then JSON_ARRAYAGG() and JSON_OBJECT() combination might be added to get back the reduced array :

```<code>SELECT JSON_ARRAYAGG(
                     JSON_OBJECT('product' VALUE product,
                                 'name'    VALUE name,
                                 'price'   VALUE price) ) AS "Result"
  FROM
  (
   SELECT t.*, ROW_NUMBER() OVER (ORDER BY 1) AS rn
     FROM tab
    CROSS JOIN
     JSON_TABLE(jsdata, '$[*]' COLUMNS (
                 product VARCHAR(100) PATH '$.product',
                 name    VARCHAR(100) PATH '$.name',
                 price   VARCHAR(100) PATH '$.price'
                )
     ) t
   )
 WHERE rn <= 250
</code>```

Demo

Body:
I have a table in which one column we have json array data. in some rows this json is very big (with 10000+ json objects) like below. wanted to know is there any way just to select first 250 objects from the array-

[
   {
      "product":"Vegetable",
      "name":"Potato",
      "price":"$60.00"
   },
   {
      "product":"Fruit",
      "name":"Mango",
      "price":"$3.30"
   },
   {
      "product":"Milk",
      "name":"Milk",
      "price":"$1.08"
   },
.....10,000
]

Body:
An analytic function such as ROW_NUMBER() might be used within the subquery to determine the restriction, and then JSON_ARRAYAGG() and JSON_OBJECT() combination might be added to get back the reduced array :

SELECT JSON_ARRAYAGG(
                     JSON_OBJECT('product' VALUE product,
                                 'name'    VALUE name,
                                 'price'   VALUE price) ) AS "Result"
  FROM
  (
   SELECT t.*, ROW_NUMBER() OVER (ORDER BY 1) AS rn
     FROM tab
    CROSS JOIN
     JSON_TABLE(jsdata, '$[*]' COLUMNS (
                 product VARCHAR(100) PATH '$.product',
                 name    VARCHAR(100) PATH '$.name',
                 price   VARCHAR(100) PATH '$.price'
                )
     ) t
   )
 WHERE rn <= 250

Demo


问:
What is the Pin Icon called in Material Icons?
What is the name of this pin icon?

答:
Now the exact icon is available in Material Icon.

Icon Name:  push_pin

Icon Url: https://material.io/resources/icons/?search=push%20pin&icon=push_pin&style=baseline

Image:

Body: What is the name of this pin icon?


问:
Node js code not working properly with net server
Here i am receiving tcp socket data, parsing it and putting into mongo db.

On application start some times i am getting huge data (socket 'data' event) as soon as connection gets established and then process getting stopped at line no 15 and after few minutes applicating again  getting started from run() method.

But  if data is not immediately recived on application start and connection establishment but recived after few seconds of connection establishment then its working smoothly.

code snippet as below, Also looking for design improvement

const streamer = require("/server.js");

async function run() {
    logger.debug('Initialize mongo, net-server');
    try {
        // Initialize the database environment or exit with exception error
        await mongo.init();
    } catch (err) {
        logger.error(err);
        process.exit(1);
    }
    server.start(); // net server listen to TCP dump

    setInterval(() => {

        if (server.isServerRunning() && server.isDataAvailable()) { //**line 15 getting stuck here
            // get collected data, parse and put into mongo
        }
    }, 3000);
}

run();
```

答:
may-2020 updated

how to user settimeout in nodejs

```<code>
    if (len == 0) {
            console.log(" No Recored Found): ");

            setTimeout(() => {
                clearInterval(intervalId);
                funcationcall();
            }, 2000);
        }
</code>```

Body:
may-2020 updated

how to user settimeout in nodejs

    if (len == 0) {
            console.log(" No Recored Found): ");

            setTimeout(() => {
                clearInterval(intervalId);
                funcationcall();
            }, 2000);
        }


问:
Postgresql - Sum JSON rows on matching keys
I have two columns in my database, one of uid (myuid) and another of key value pairs representing total pets per user (totalpetsjson). I would like to query on uid and then sum the resulting JSON rows where keys match.

This query

```<code>SELECT totalpetsjson FROM mytable WHERE "myuid" IN ('john','andy')
</code>```

Results in two rows

```<code>{'dogs':3,'cats':5,'fish':144}
{'dogs':2,'lizards':4,'cats':3'}
</code>```

What I want the result to be. How could I query and combine the above two rows to look like below?

```<code>{'dogs':5,'cats':8,'fish':144,'lizards':4}
</code>```

答:
Building on top of the previous anwser by klin, that approach can be expanded if you're not interested in flattening a full table but keeping a grouping:

SELECT x, json_object_agg(key, sum)
FROM (
    SELECT x, key, sum(value::INT) AS sum
    FROM (
        VALUES (1, '{
          "a": 10,
          "b": 11
        }'::JSONB),
        (1, '{
          "b": 12,
          "c": 13
        }'::JSONB),
        (2, '{
          "b": 14,
          "c": 15
        }'::JSONB)
    ) AS mytable(x, y)
             CROSS JOIN jsonb_each_text(Y)
    GROUP BY 1, 2
) x
GROUP BY 1
ORDER BY 1;
```

<p>Result:</p>

```1,"{ ""c"" : 13, ""b"" : 23, ""a"" : 10 }"
2,"{ ""c"" : 15, ""b"" : 14 }"
```

Body:
I have two columns in my database, one of uid (myuid) and another of key value pairs representing total pets per user (totalpetsjson). I would like to query on uid and then sum the resulting JSON rows where keys match.

This query

SELECT totalpetsjson FROM mytable WHERE "myuid" IN ('john','andy')

Results in two rows

{'dogs':3,'cats':5,'fish':144}
{'dogs':2,'lizards':4,'cats':3'}

What I want the result to be. How could I query and combine the above two rows to look like below?

{'dogs':5,'cats':8,'fish':144,'lizards':4}

Body:
Building on top of the previous anwser by klin, that approach can be expanded if you're not interested in flattening a full table but keeping a grouping:

SELECT x, json_object_agg(key, sum)
FROM (
    SELECT x, key, sum(value::INT) AS sum
    FROM (
        VALUES (1, '{
          "a": 10,
          "b": 11
        }'::JSONB),
        (1, '{
          "b": 12,
          "c": 13
        }'::JSONB),
        (2, '{
          "b": 14,
          "c": 15
        }'::JSONB)
    ) AS mytable(x, y)
             CROSS JOIN jsonb_each_text(Y)
    GROUP BY 1, 2
) x
GROUP BY 1
ORDER BY 1;

Result:

1,"{ ""c"" : 13, ""b"" : 23, ""a"" : 10 }"
2,"{ ""c"" : 15, ""b"" : 14 }"


问:
Java parent's private attribute inside child constructor
The title says it all, I got a class in which the variables of the constructor must be private.

```<code>public class AdMedia {
private String name;
private int price;

public AdMedia(){}

public AdMedia(String name, int price) {
    this.name = name;
    this.price = price;
}
</code>```

that comes with public getter setter of the variables of course.

Now the problem comes right after I try to make a child class named Magazine. The class should inherit the name and price but the price is constant for every object initiation. so they won't be on the constructor as the name.

```<code>public class Magazine extends AdMedia {
private int area;
private String position;
private String topics;

public Magazine() {}
public Magazine(String name, int size, String position, String topic){

    super();
    this.size = size;
    this.position = position;
    this.topic = topic;

}
</code>```

that also comes with its own getter setter too.

I try to put the price inside the constructor but the constructor demand a passed parameter. Using super(name) also notifies that none of parent constructor have such shape.

This complicates me when I'm trying to get the name using parent class method getName() which might require some downcasting I guess?

I had try to search for the solution but most require me to change the variable's accessibility into protected . Would there be no other way to do it in private ?

EDIT :
I forgot to mention that the result by doing what I wrote above is the unability to access Magazine name, so when I try to downcast-get the name, what returned is a null.

答:
You could write your child constructor either as

```<code>public Magazine(String name, int size, String position, String topic){
    super();
    setName(name);
    setPrice(100); // 100 is your constant price
    this.size = size;
    this.position = position;
    this.topic = topic;
}
</code>```

or as

```<code>public Magazine(String name, int size, String position, String topic){
    super(name, 100); // 100 is your constant price
    this.size = size;
    this.position = position;
    this.topic = topic;
}
</code>```

Both ways would however open the possibility to change the price later:

```<code>Magazine m = new Magazine("name", 50, "position", "topic");
m.setPrice(10);
</code>```

If you need to prevent this, you should also override the setPrice() setter:

```<code>public class Magazine extends AdMedia {

    ...
    @Override
    public void setPrice(int price) {
        // what to do here?
        // * you could either silently ignore
        //   (which might surprise some users expecting to be able to change the price)
        // * throw an UnsupportedOperationException
        //   (which might surprise other users which are not prepared to handle such an exception)
    }
}
</code>```

Body:
The title says it all, I got a class in which the variables of the constructor must be private.

public class AdMedia {
private String name;
private int price;

public AdMedia(){}

public AdMedia(String name, int price) {
    this.name = name;
    this.price = price;
}

that comes with public getter setter of the variables of course.

Now the problem comes right after I try to make a child class named Magazine. The class should inherit the name and price but the price is constant for every object initiation. so they won't be on the constructor as the name.

public class Magazine extends AdMedia {
private int area;
private String position;
private String topics;

public Magazine() {}
public Magazine(String name, int size, String position, String topic){

    super();
    this.size = size;
    this.position = position;
    this.topic = topic;

}

that also comes with its own getter setter too.

I try to put the price inside the constructor but the constructor demand a passed parameter. Using super(name) also notifies that none of parent constructor have such shape.

This complicates me when I'm trying to get the name using parent class method getName() which might require some downcasting I guess?

I had try to search for the solution but most require me to change the variable's accessibility into protected . Would there be no other way to do it in private ?

EDIT :
I forgot to mention that the result by doing what I wrote above is the unability to access Magazine name, so when I try to downcast-get the name, what returned is a null.

Body:
You could write your child constructor either as

public Magazine(String name, int size, String position, String topic){
    super();
    setName(name);
    setPrice(100); // 100 is your constant price
    this.size = size;
    this.position = position;
    this.topic = topic;
}

or as

public Magazine(String name, int size, String position, String topic){
    super(name, 100); // 100 is your constant price
    this.size = size;
    this.position = position;
    this.topic = topic;
}

Both ways would however open the possibility to change the price later:

Magazine m = new Magazine("name", 50, "position", "topic");
m.setPrice(10);

If you need to prevent this, you should also override the setPrice() setter:

public class Magazine extends AdMedia {

    ...
    @Override
    public void setPrice(int price) {
        // what to do here?
        // * you could either silently ignore
        //   (which might surprise some users expecting to be able to change the price)
        // * throw an UnsupportedOperationException
        //   (which might surprise other users which are not prepared to handle such an exception)
    }
}


问:
Tuple templates in GCC
I first started C++ with Microsoft VC++ in VS2010. I recently found some work, but I've been using RHEL 5 with GCC. My code is mostly native C++, but I've noticed one thing...

GCC doesn't appear to recognize the <tuple> header file, or the tuple template. At first I thought maybe it's just a typo, until I looked at cplusplus.com and found that the  header is indeed not part of the standard library.

The problem is that I like to write my code in Visual Studio because the environment is way superior and aesthetically pleasing than eclipse or netbeans, and debugging is a breeze. The thing is, I've already written a good chunk of code to use tuples and I really like my code. How am I supposed to deal with this issue?

Here's my code:

```<code>using std::cout;
using std::make_tuple;
using std::remove;
using std::string;
using std::stringstream;
using std::tolower;
using std::tuple;
using std::vector;

// Define three conditions to code
enum {DONE, OK, EMPTY_LINE};
// Tuple containing a condition and a string vector
typedef tuple<int,vector<string>> Code;

// Passed an alias to a string
// Parses the line passed to it
Code ReadAndParse(string& line)
{

    /***********************************************/
    /****************REMOVE COMMENTS****************/
    /***********************************************/
    // Sentinel to flag down position of first
    // semicolon and the index position itself
    bool found = false;
    size_t semicolonIndex = -1;

    // Convert the line to lowercase
    for(int i = 0; i < line.length(); i++)
    {
        line[i] = tolower(line[i]);

        // Find first semicolon
        if(line[i] == ';' && !found)
        {
            semicolonIndex = i;
            // Throw the flag
            found = true;
        }
    }

    // Erase anything to and from semicolon to ignore comments
    if(found != false)
        line.erase(semicolonIndex);

    /***********************************************/
    /*****TEST AND SEE IF THERE'S ANYTHING LEFT*****/
    /***********************************************/

    // To snatch and store words
    Code code;
    string token;
    stringstream ss(line);
    vector<string> words;

    // A flag do indicate if we have anything
    bool emptyLine = true;

    // While the string stream is passing anything
    while(ss >> token)
    {
        // If we hit this point, we did find a word
        emptyLine = false;

        // Push it onto the words vector
        words.push_back(token);
    }

    // If all we got was nothing, it's an empty line
    if(emptyLine)
    {
        code = make_tuple(EMPTY_LINE, words);
        return code;
    }

    // At this point it should be fine
    code = make_tuple(OK, words);
    return code;
}
</code>```

Is there anyway to save my code from compiler incompatibility?

答:
As long as it's just a pair you can use

```<code>typedef pair<int,vector<string>> Code;
</code>```

But I don't think tuple is standard C++ (turns out it is included in TR1 and consequently also standard C++0x). As usual Boost has you covered though. So including:

```<code>#include "boost/tuple/tuple.hpp"
</code>```

will solve your problem across compilers.

Title: Tuple templates in GCC

Body:
I first started C++ with Microsoft VC++ in VS2010. I recently found some work, but I've been using RHEL 5 with GCC. My code is mostly native C++, but I've noticed one thing...

GCC doesn't appear to recognize the <tuple> header file, or the tuple template. At first I thought maybe it's just a typo, until I looked at cplusplus.com and found that the  header is indeed not part of the standard library.

The problem is that I like to write my code in Visual Studio because the environment is way superior and aesthetically pleasing than eclipse or netbeans, and debugging is a breeze. The thing is, I've already written a good chunk of code to use tuples and I really like my code. How am I supposed to deal with this issue?

Here's my code:

using std::cout;
using std::make_tuple;
using std::remove;
using std::string;
using std::stringstream;
using std::tolower;
using std::tuple;
using std::vector;

// Define three conditions to code
enum {DONE, OK, EMPTY_LINE};
// Tuple containing a condition and a string vector
typedef tuple<int,vector<string>> Code;

// Passed an alias to a string
// Parses the line passed to it
Code ReadAndParse(string& line)
{

    /***********************************************/
    /****************REMOVE COMMENTS****************/
    /***********************************************/
    // Sentinel to flag down position of first
    // semicolon and the index position itself
    bool found = false;
    size_t semicolonIndex = -1;

    // Convert the line to lowercase
    for(int i = 0; i < line.length(); i++)
    {
        line[i] = tolower(line[i]);

        // Find first semicolon
        if(line[i] == ';' && !found)
        {
            semicolonIndex = i;
            // Throw the flag
            found = true;
        }
    }

    // Erase anything to and from semicolon to ignore comments
    if(found != false)
        line.erase(semicolonIndex);

    /***********************************************/
    /*****TEST AND SEE IF THERE'S ANYTHING LEFT*****/
    /***********************************************/

    // To snatch and store words
    Code code;
    string token;
    stringstream ss(line);
    vector<string> words;

    // A flag do indicate if we have anything
    bool emptyLine = true;

    // While the string stream is passing anything
    while(ss >> token)
    {
        // If we hit this point, we did find a word
        emptyLine = false;

        // Push it onto the words vector
        words.push_back(token);
    }

    // If all we got was nothing, it's an empty line
    if(emptyLine)
    {
        code = make_tuple(EMPTY_LINE, words);
        return code;
    }

    // At this point it should be fine
    code = make_tuple(OK, words);
    return code;
}

Is there anyway to save my code from compiler incompatibility?

Body:
As long as it's just a pair you can use

typedef pair<int,vector<string>> Code;

But I don't think tuple is standard C++ (turns out it is included in TR1 and consequently also standard C++0x). As usual Boost has you covered though. So including:

#include "boost/tuple/tuple.hpp"

will solve your problem across compilers.


问:
R sub-setting netcdf file
I am working with a lulc cover data from this source for the year 2018

https://cds.climate.copernicus.eu/cdsapp#!/dataset/satellite-land-cover?tab=form

The data format is in netcdf and shows for each lat long the land cover classification. In order to read and create a raster from this netcdf, I did this:

```<code>library(ncdf4)
temp <- nc_open(file.name)
lon <- ncvar_get(temp, "lon")
lat <- ncvar_get(temp, "lat")
lccs <- ncvar_get(temp, "lccs_class", signedbyte = FALSE)
</code>```

However, the netcdf file is so big that it takes ages to read the file. I only need a subset of the lat lon whose bounding box is defined as follows:

```<code>min lat: 8.125
max lat: 37.125
min lon: 68.125
max lon: 97.375
</code>```

How can I subset the above netcdf using these bounding boxes?

答:
In most cases you can do that like this</p>

```<code>library(raster)
b <- brick("filename.nc")
e <- extent(8.125, 37.125, 68.125, 97.375)
x <- crop(b, e)
</code>```

Title: R sub-setting netcdf file

Body:
I am working with a lulc cover data from this source for the year 2018

https://cds.climate.copernicus.eu/cdsapp#!/dataset/satellite-land-cover?tab=form

The data format is in netcdf and shows for each lat long the land cover classification. In order to read and create a raster from this netcdf, I did this:

library(ncdf4)
temp <- nc_open(file.name)
lon <- ncvar_get(temp, "lon")
lat <- ncvar_get(temp, "lat")
lccs <- ncvar_get(temp, "lccs_class", signedbyte = FALSE)

However, the netcdf file is so big that it takes ages to read the file. I only need a subset of the lat lon whose bounding box is defined as follows:

min lat: 8.125
max lat: 37.125
min lon: 68.125
max lon: 97.375

How can I subset the above netcdf using these bounding boxes?

Body:
In most cases you can do that like this

library(raster)
b <- brick("filename.nc")
e <- extent(8.125, 37.125, 68.125, 97.375)
x <- crop(b, e)


问:
Powershell script and outputting to file share
I have a powershell script that is converting CSV to XLSX.  It works as intended when outputting to local disk.  It runs for a few seconds and then an XLSX file is generated in $files path.

```<code>$files = Get-ChildItem c:\test\*.csv
Write "Loading Files..."

$Excel = New-Object -ComObject Excel.Application

ForEach ($file in $files)
{

     $WorkBook = $Excel.Workbooks.Open($file.Fullname)
     $NewFilepath = $file.Fullname -replace ".{4}$"
     $NewFilepath =  $NewFilepath + ".xlsx"
     $Workbook.SaveAs($NewFilepath,51)
}

$Excel.Quit()
Stop-Process -processname EXCEL
</code>```

But when I change it to output to a file share, it immediately completes with no error, but no output file is generated.

```<code>$files = Get-ChildItem \\fileserver\path\*.csv
Write "Loading Files..."

$Excel = New-Object -ComObject Excel.Application

ForEach ($file in $files)
{

     $WorkBook = $Excel.Workbooks.Open($file.Fullname)
     $NewFilepath = $file.Fullname -replace ".{4}$"
     $NewFilepath =  $NewFilepath + ".xlsx"
     $Workbook.SaveAs($NewFilepath,51)
}

$Excel.Quit()
Stop-Process -processname EXCEL
</code>```

I would suspect this is a permissions issue, but the logged in account has write access the share.  Does a powershell script change the user/account context?  What can I add to this script to capture errors and identify the problem?

答:
try this:

```<code>$files = Get-ChildItem "\\fileserver\path" -filter *.csv"
</code>```

and then separately echo out after your $NewFilepath assignments.

If that doesn't give you more info, then try writing something simple to the share like:

```<code>"Hello World" > "\\fileserver\path\test.txt"
</code>```

That could give you clues on user context and permissions.

Body:
I have a powershell script that is converting CSV to XLSX.  It works as intended when outputting to local disk.  It runs for a few seconds and then an XLSX file is generated in $files path.

$files = Get-ChildItem c:\test\*.csv
Write "Loading Files..."

$Excel = New-Object -ComObject Excel.Application

ForEach ($file in $files)
{

     $WorkBook = $Excel.Workbooks.Open($file.Fullname)
     $NewFilepath = $file.Fullname -replace ".{4}$"
     $NewFilepath =  $NewFilepath + ".xlsx"
     $Workbook.SaveAs($NewFilepath,51)
}

$Excel.Quit()
Stop-Process -processname EXCEL

But when I change it to output to a file share, it immediately completes with no error, but no output file is generated.

$files = Get-ChildItem \\fileserver\path\*.csv
Write "Loading Files..."

$Excel = New-Object -ComObject Excel.Application

ForEach ($file in $files)
{

     $WorkBook = $Excel.Workbooks.Open($file.Fullname)
     $NewFilepath = $file.Fullname -replace ".{4}$"
     $NewFilepath =  $NewFilepath + ".xlsx"
     $Workbook.SaveAs($NewFilepath,51)
}

$Excel.Quit()
Stop-Process -processname EXCEL

I would suspect this is a permissions issue, but the logged in account has write access the share.  Does a powershell script change the user/account context?  What can I add to this script to capture errors and identify the problem?

Body:
try this:

$files = Get-ChildItem "\\fileserver\path" -filter *.csv"

and then separately echo out after your $NewFilepath assignments.

If that doesn't give you more info, then try writing something simple to the share like:

"Hello World" > "\\fileserver\path\test.txt"

That could give you clues on user context and permissions.


问:
Strange definition and call of a function with curly bracket in Scala (function as parameter of a function)
I'm totally new with Scala, I have to maintain an old code, so I have to understand what it does.

Now I am stuck on this piece of code, it is about defining and calling a method.

This is the definition of the method:

```<code>private def myMethod[I, O](price: Long, id: Int)(i: I)(f: (I, String) => O): O = {
      ..some code..
}
</code>```

this is the method call

```<code>myMethod(price, id)(b) {
      ..some code.. //single line of code, just calling an other function
}
</code>```

I understood the part of having type parameter also of having multiple parameter (currying).

But what I didn't understand, is :

first of all this part: (f: (I, String) => O) , this is completely strange for me

second, why in the method call, it contains code after the { symbol, is it overriding the original method? even it's the case, it make no sense to override it when making the call

also, myMethod is supposed to return a value of type O , but in my code it's never affected to any variable. (EDIT: this point is clear now, I just misunderstood the code, nvm mind about it)

Please can any one clarify this points (especially the first and second one which are making me so confused)

EDIT

```<code>private var x : classX

myMethod(price, id)(b) {
      x.listX //calling method without parameters
}
</code>```

```<code>def listX (param1: ListFaFBI, param2: String): ListX ={
  //returning an Object of type ListX, not a function
}
</code>```

as you can see that myMethod is calling listX. if I understood well, myMethod is returning the method listX itself which has two parameters ListFaFBI (or I) and String and returning ListX (or O) as defined in (f: (I, String) => O)

答:
f is a function that takes in an I and a String and returns an O. f: (I, String) => O is syntactic sugar for f: Function2[I, String, O].

The braces act essentially the same as parentheses would, although there are some differences, as they can be treated as blocks (See this question). The code inside the braces is actually a function literal, and it will be passed as f. Also see this question. Here,

```<code>myMethod(price, id)(b) { (i, s) =>
      ..some code..
}
</code>```

would be syntactic sugar for

```<code>myMethod(price, id)(b)({ (i, s) =>
      ..some code..
})
</code>```

I'm not sure what you mean by "in my code it's never affected to any variable", but I assume that what is returned is either irrelevant or that there is an implied return (in case the call to myMethod is at the end of a block.

Body:
I'm totally new with Scala, I have to maintain an old code, so I have to understand what it does.

Now I am stuck on this piece of code, it is about defining and calling a method.

This is the definition of the method:

private def myMethod[I, O](price: Long, id: Int)(i: I)(f: (I, String) => O): O = {
      ..some code..
}

this is the method call

myMethod(price, id)(b) {
      ..some code.. //single line of code, just calling an other function
}

I understood the part of having type parameter also of having multiple parameter (currying).

But what I didn't understand, is :

first of all this part: (f: (I, String) => O) , this is completely strange for me

second, why in the method call, it contains code after the { symbol, is it overriding the original method? even it's the case, it make no sense to override it when making the call

also, myMethod is supposed to return a value of type O , but in my code it's never affected to any variable. (EDIT: this point is clear now, I just misunderstood the code, nvm mind about it)

Please can any one clarify this points (especially the first and second one which are making me so confused)

EDIT

private var x : classX

myMethod(price, id)(b) {
      x.listX //calling method without parameters
}

def listX (param1: ListFaFBI, param2: String): ListX ={
  //returning an Object of type ListX, not a function
}

as you can see that myMethod is calling listX. if I understood well, myMethod is returning the method listX itself which has two parameters ListFaFBI (or I) and String and returning ListX (or O) as defined in (f: (I, String) => O)

Body:
f is a function that takes in an I and a String and returns an O. f: (I, String) => O is syntactic sugar for f: Function2[I, String, O].

The braces act essentially the same as parentheses would, although there are some differences, as they can be treated as blocks (See this question). The code inside the braces is actually a function literal, and it will be passed as f. Also see this question. Here,

myMethod(price, id)(b) { (i, s) =>
      ..some code..
}

would be syntactic sugar for

myMethod(price, id)(b)({ (i, s) =>
      ..some code..
})

I'm not sure what you mean by "in my code it's never affected to any variable", but I assume that what is returned is either irrelevant or that there is an implied return (in case the call to myMethod is at the end of a block.


问:
How to use react-native-google-places-autocomplete
I have included react-native-google-places-autocomplete in my project as documented in Github but it is not rendering suggestions as expected. Is the provided example on its Github enough or should I add something else?

Here is my code(I have my API key included in my original code), which is almost is the same as Github example

```<code>import React from "react";
import {
  Button,
  Text,
  Image,
  TextInput,
  TouchableOpacity,
  View,
  StyleSheet
} from "react-native";
import MapView, { PROVIDER_GOOGLE, Marker } from "react-native-maps";
import Colors from "./../../Shared/Colors";
import CommonStyles from "./../../Shared/CommonStyles";
import { Ionicons } from "@expo/vector-icons";
import { GooglePlacesAutocomplete } from "react-native-google-places-autocomplete";

const homePlace = {
  description: "Home",
  geometry: {
    location: {
      lat: 48.8152937,
      lng: 2.4597668
    }
  }
};
const workPlace = {
  description: "Work",
  geometry: {
    location: {
      lat: 48.8496818,
      lng: 2.2940881
    }
  }
};

const Booking = props => {
  return (
    <View style={StyleSheet.absoluteFillObject}>
      <MapView
        provider={PROVIDER_GOOGLE} // remove if not using Google Maps
        style={StyleSheet.absoluteFillObject}
        region={{
          latitude: 37.78825,
          longitude: -122.4324,
          latitudeDelta: 0.015,
          longitudeDelta: 0.0121
        }}
      />
      <View style={styles.locationsInputs}>
        <View style={styles.pickupInput}>
        <GooglePlacesAutocomplete
      placeholder='Search'
      minLength={2} // minimum length of text to search
      autoFocus={false}
      returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
      keyboardAppearance={'light'} // Can be left out for default keyboardAppearance https://facebook.github.io/react-native/docs/textinput.html#keyboardappearance
      listViewDisplayed='auto'    // true/false/undefined
      fetchDetails={true}
      renderDescription={row => row.description} // custom description render
      onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
        console.log(data, details);
      }}

      getDefaultValue={() => ''}

      query={{
        // available options: https://developers.google.com/places/web-service/autocomplete
        key: 'myApiKey', // I have included my api key
        language: 'en', // language of the results
        types: '(cities)' // default: 'geocode'
      }}

      styles={{
        textInputContainer: {
          width: '100%'
        },
        description: {
          fontWeight: 'bold'
        },
        predefinedPlacesDescription: {
          color: '#1faadb'
        }
      }}

      currentLocation={true} // Will add a 'Current location' button at the top of the predefined places list
      currentLocationLabel="Current location"
      nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
      GoogleReverseGeocodingQuery={{
        // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
      }}
      GooglePlacesSearchQuery={{
        // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
        rankby: 'distance',
        type: 'cafe'
      }}

      GooglePlacesDetailsQuery={{
        // available options for GooglePlacesDetails API : https://developers.google.com/places/web-service/details
        fields: 'formatted_address',
      }}

      filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities
      predefinedPlaces={[homePlace, workPlace]}

      debounce={200} // debounce the requests in ms. Set to 0 to remove debounce. By default 0ms.
    />
          {/* <Image source={require("./../../assets/images/downloadarrow.png")} /> */}
        </View>
      </View>

    </View>
  );
};

export default Booking;
</code>```

答:
The problem is likely in the billing configuration on Google APIs. Visit your console to set up your billing details.

https://github.com/FaridSafi/react-native-google-places-autocomplete/issues/503#issuecomment-612102925

Body:
I have included react-native-google-places-autocomplete in my project as documented in Github but it is not rendering suggestions as expected. Is the provided example on its Github enough or should I add something else?

Here is my code(I have my API key included in my original code), which is almost is the same as Github example

import React from "react";
import {
  Button,
  Text,
  Image,
  TextInput,
  TouchableOpacity,
  View,
  StyleSheet
} from "react-native";
import MapView, { PROVIDER_GOOGLE, Marker } from "react-native-maps";
import Colors from "./../../Shared/Colors";
import CommonStyles from "./../../Shared/CommonStyles";
import { Ionicons } from "@expo/vector-icons";
import { GooglePlacesAutocomplete } from "react-native-google-places-autocomplete";

const homePlace = {
  description: "Home",
  geometry: {
    location: {
      lat: 48.8152937,
      lng: 2.4597668
    }
  }
};
const workPlace = {
  description: "Work",
  geometry: {
    location: {
      lat: 48.8496818,
      lng: 2.2940881
    }
  }
};

const Booking = props => {
  return (
    <View style={StyleSheet.absoluteFillObject}>
      <MapView
        provider={PROVIDER_GOOGLE} // remove if not using Google Maps
        style={StyleSheet.absoluteFillObject}
        region={{
          latitude: 37.78825,
          longitude: -122.4324,
          latitudeDelta: 0.015,
          longitudeDelta: 0.0121
        }}
      />
      <View style={styles.locationsInputs}>
        <View style={styles.pickupInput}>
        <GooglePlacesAutocomplete
      placeholder='Search'
      minLength={2} // minimum length of text to search
      autoFocus={false}
      returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
      keyboardAppearance={'light'} // Can be left out for default keyboardAppearance https://facebook.github.io/react-native/docs/textinput.html#keyboardappearance
      listViewDisplayed='auto'    // true/false/undefined
      fetchDetails={true}
      renderDescription={row => row.description} // custom description render
      onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
        console.log(data, details);
      }}

      getDefaultValue={() => ''}

      query={{
        // available options: https://developers.google.com/places/web-service/autocomplete
        key: 'myApiKey', // I have included my api key
        language: 'en', // language of the results
        types: '(cities)' // default: 'geocode'
      }}

      styles={{
        textInputContainer: {
          width: '100%'
        },
        description: {
          fontWeight: 'bold'
        },
        predefinedPlacesDescription: {
          color: '#1faadb'
        }
      }}

      currentLocation={true} // Will add a 'Current location' button at the top of the predefined places list
      currentLocationLabel="Current location"
      nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
      GoogleReverseGeocodingQuery={{
        // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
      }}
      GooglePlacesSearchQuery={{
        // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
        rankby: 'distance',
        type: 'cafe'
      }}

      GooglePlacesDetailsQuery={{
        // available options for GooglePlacesDetails API : https://developers.google.com/places/web-service/details
        fields: 'formatted_address',
      }}

      filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities
      predefinedPlaces={[homePlace, workPlace]}

      debounce={200} // debounce the requests in ms. Set to 0 to remove debounce. By default 0ms.
    />
          {/* <Image source={require("./../../assets/images/downloadarrow.png")} /> */}
        </View>
      </View>

    </View>
  );
};

export default Booking;


问:
A little confused with Big O
So I have a quick question on how to verify the big O of a function.

for example: a quicksort algorithm sorting an array of 5000000 element yields a time interval of 0.008524 seconds, running the same algorithm with 1000000 element yields 0.017909.  How would I check the big O if my quicksort is/is not big O of n*log(n)??

What I think I understand: n increased by 2  thus the runtime should increase by 2*log(2)?

f(n) = 0.008524 -> n log (n)

f(2n) = 0.017909 ->2n*log(2n)

答:
Big-O notation is not normally concerned with run-time in seconds.  It's concerned with the number of operations that were carried out by the algorithm.  The only way to establish that is to look at the code for the function.

Not only will run-time be affected by lower-order terms (remember that big-O notation only concerns itself with the highest-order term), but also things such as program startup overhead, cache efficiency and branch prediction.

Having said all that, it's possible that none of these other effects will be significant in your case.  In which case, if n is doubled, then you would expect the run-time to increase from k.n.log(n) to k.2n.log(2n) = k(2n.log(2) + 2n.log(n)).

Title: A little confused with Big O


答:
This is how I would do it:</p>

```<code>public class ReadingFile{
    public static void main(String[] args) {
        File in = new File("C:\\old.txt");
        File out = new File("C:\\new.txt");
        ArrayList<String> al = new ArrayList<>();

        try (Scanner read = new Scanner(in);
                FileWriter write = new FileWriter(out)) { //ALWAYS use try-with-resources if you can
            while (read.hasNextLine()) {
                al.add(read.nextLine()); //reads to an ArrayList (so there could be multiple lines in the input file)
            }

            for (String str : al) {
                write.write(str.replace("\\", "\n")); //replace all backslashes with newlines
                write.write('\n');
            }

            write.flush(); //flush the Writer at the end, so everything gets written to the file
        } catch (FileNotFoundException e) {
            throw new RuntimeException("File not found."); //Don't swallow exceptions, at least throw a RuntimeException
        } catch (IOException ex) {
            throw new RuntimeException("IO exception occured"); //Don't swallow exceptions, at least throw a RuntimeException
        }
    }
}
</code>```

Title: I need to split .txt file's content to a new line when it sees a backslash

Body:
I have a .txt file named "new.txt" and its content is;

nxy15\nxy995\nxy823\nxy721\nxy1\nxy1872\nxy3482\nxy878\nxy123\nxy8753\nxy1284\nxy4495\nxy4323\nxy812\nxy7123\nxy1273

I need to format that .txt file, to be more specific i need to go to the next line when backslash is detected like one number for each line and i need to remove the letters aswell.

Formatted .txt file needs to look like this;

15
995
823
721
1
1872
...

So far, because of my little Java knowledge, i managed to just read the file and output it. Here it is;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadingFile{
    public static void main(String[] args) {
        try {
            File file = new File("C:\\new.txt");
            Scanner read = new Scanner(file);
            while (read.hasNextLine()) {
                String obj2 = read.nextLine();
                System.out.println(obj2);
            }
            read.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

I need to solve this so i can move on to the next question but i'm stuck with this question and can't solve it and i'm trying for three hours.

Any help or clues are highly appreciated, thanks.

Body:
This is how I would do it:

public class ReadingFile{
    public static void main(String[] args) {
        File in = new File("C:\\old.txt");
        File out = new File("C:\\new.txt");
        ArrayList<String> al = new ArrayList<>();

        try (Scanner read = new Scanner(in);
                FileWriter write = new FileWriter(out)) { //ALWAYS use try-with-resources if you can
            while (read.hasNextLine()) {
                al.add(read.nextLine()); //reads to an ArrayList (so there could be multiple lines in the input file)
            }

            for (String str : al) {
                write.write(str.replace("\\", "\n")); //replace all backslashes with newlines
                write.write('\n');
            }

            write.flush(); //flush the Writer at the end, so everything gets written to the file
        } catch (FileNotFoundException e) {
            throw new RuntimeException("File not found."); //Don't swallow exceptions, at least throw a RuntimeException
        } catch (IOException ex) {
            throw new RuntimeException("IO exception occured"); //Don't swallow exceptions, at least throw a RuntimeException
        }
    }
}


问:
navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't
So I have a pretty simple bit of JS using the navigator.geolocation.getCurrentPosition jammy.

```<code>$(document).ready(function(){
  $("#business-locate, #people-locate").click(function() {
    navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
  });

  navigator.geolocation.getCurrentPosition(foundLocation, noLocation);

  function foundLocation(position) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    var userLocation = lat + ', ' + lon;
    $("#business-current-location, #people-current-location").remove();
    $("#Near-Me")
      .watermark("Current Location")
      .after("<input type='hidden' name='business-current-location' id='business-current-location' value='"+userLocation+"' />");
    $("#people-Near-Me")
      .watermark("Current Location")
      .after("<input type='hidden' name='people-current-location' id='people-current-location' value='"+userLocation+"' />");
  }
  function noLocation() {
    $("#Near-Me").watermark("Could not find location");
    $("#people-Near-Me").watermark("Could not find location");
  }
})//end DocReady
</code>```

Basically what's happening here is we get the current position, if it's obtained, two "watermarks" are placed in two fields that say "Current Position" and two hidden fields are created with the lat-long data as their value (they're removed in the beginning so they don't get duplicated every time). There are also two buttons that have a click function tied to them that do the same thing.
Unfortunately, every third time or so, it works.
What's the problem here???

答: This happened to me when using Firefox's responsive design mode. There has been a bug report filed. For now, just don't use responsive design mode while using the Geolocation API.</p>

ContentLicense: CC BY-SA 2.5

Body:
So I have a pretty simple bit of JS using the navigator.geolocation.getCurrentPosition jammy.

$(document).ready(function(){
  $("#business-locate, #people-locate").click(function() {
    navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
  });

  navigator.geolocation.getCurrentPosition(foundLocation, noLocation);

  function foundLocation(position) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    var userLocation = lat + ', ' + lon;
    $("#business-current-location, #people-current-location").remove();
    $("#Near-Me")
      .watermark("Current Location")
      .after("<input type='hidden' name='business-current-location' id='business-current-location' value='"+userLocation+"' />");
    $("#people-Near-Me")
      .watermark("Current Location")
      .after("<input type='hidden' name='people-current-location' id='people-current-location' value='"+userLocation+"' />");
  }
  function noLocation() {
    $("#Near-Me").watermark("Could not find location");
    $("#people-Near-Me").watermark("Could not find location");
  }
})//end DocReady

Basically what's happening here is we get the current position, if it's obtained, two "watermarks" are placed in two fields that say "Current Position" and two hidden fields are created with the lat-long data as their value (they're removed in the beginning so they don't get duplicated every time). There are also two buttons that have a click function tied to them that do the same thing.
Unfortunately, every third time or so, it works.
What's the problem here???


问:
Use map(v, reduce) to create Fibonacci sequence in R?
I was wondering if we could use purrr's map and reduce to create to Fibonacci function akin to this one in JavaScript:

```<code>function fib(n){
  return new Array(n).fill(1).reduce((arr, _ ,i) => {
    arr.push((i <= 1) ? i : arr[i-2] + arr[i-1])
    return arr
  },[]) ;
}
console.log(fib(10))
</code>```

I see answers here Fibonacci Sequence in R that use recursion but I was wondering if we could specifically use purrr's reduce and if so how?

答:
How about this approach with map?

```<code>n<-10
map(n,function(x) round(((5+sqrt(5))/10) * ((1+sqrt(5))/2) ** (1:x-1)))
[[1]]
 [1]  1  1  2  3  5  8 13 21 34 55
</code>```

Inspired by this answer. Obviously @Artem's answer is more in the spirit of the question. So hats off to them.

Body:
I was wondering if we could use purrr's map and reduce to create to Fibonacci function akin to this one in JavaScript:

function fib(n){
  return new Array(n).fill(1).reduce((arr, _ ,i) => {
    arr.push((i <= 1) ? i : arr[i-2] + arr[i-1])
    return arr
  },[]) ;
}
console.log(fib(10))

I see answers here Fibonacci Sequence in R that use recursion but I was wondering if we could specifically use purrr's reduce and if so how?

Body:
How about this approach with map?

n<-10
map(n,function(x) round(((5+sqrt(5))/10) * ((1+sqrt(5))/2) ** (1:x-1)))
[[1]]
 [1]  1  1  2  3  5  8 13 21 34 55

Inspired by this answer. Obviously @Artem's answer is more in the spirit of the question. So hats off to them.


问:
digital ocean docker selenoid
I created a docker selenoid on digital oceon, i went to the link hub and create a chrome session but when i try to run my python script, the vnc of the session doesn't work !</p>

```<code>from selenium import webdriver

capabilities = {
    "browserName": "chrome",
    "version": "81.0",
    "enableVNC": True,
    "enableVideo": True
}

driver = webdriver.Remote(
    command_executor="http://myserverip:4444/wd/hub",
    desired_capabilities=capabilities)

driver.get('www.stackoverflow.com')
print('done')
</code>```

答: In recent Selenium client versions you could solve this by using Selenium protocol extensions as shown here: https://aerokube.com/selenoid/latest/#_specifying_capabilities_via_protocol_extensions</p>

Title: digital ocean docker selenoid

Body:
I created a docker selenoid on digital oceon, i went to the link hub and create a chrome session but when i try to run my python script, the vnc of the session doesn't work !

from selenium import webdriver

capabilities = {
    "browserName": "chrome",
    "version": "81.0",
    "enableVNC": True,
    "enableVideo": True
}

driver = webdriver.Remote(
    command_executor="http://myserverip:4444/wd/hub",
    desired_capabilities=capabilities)

driver.get('www.stackoverflow.com')
print('done')


问:
Is there a shortcut for switching between panels in eclipse?
Eclipse has an MDI structure (Multi Document Interface), so the search panel, the package explorer and the code editor can all be open in one window, but I haven't found a keyboard shortcut for switching between these panels. For example, after I search the code-base, I would love to have a quick shortcut for going back to the code editor.</p>

答: If I understand your question correct, you are probably looking for Ctrl + F7 and Ctrl + Shift + F7. Other navigational shortcuts can be found in the menu: Window > Navigation.


问:
Find the two numbers that appear only once - divide and conquer
Given an array in which each element appears twice, I have to find which two numbers of the array appear only once. Maximum additional memory is O(1).

I have found this amazing solution: https://medium.com/@gurupad93/two-numbers-that-appear-once-b89e92a9334b

The problem is that my solution should be divide and conquer, and my understanding is that the solution I found is not.

I know how to solve this problem with divide and conquer when the element appearing once is just one. Here, I wouldn't know how to divide the array recursively to be honest.

Any suggestions?

Thank you so much!

答:
Choose the first bit.

Separate numbers with this bit set and numbers with this bit zero.

You can use routine like partition in quick sort - find the leftmost number with one bit, find the rightmost number with zero bit, exchange them, continue until left and right indexes meet.

Treat the left part and the right part, considering the next bit.

Do this recursively with next bits until part size becomes 1 or 2.

In the first case you have found one of needed numbers.

In the second case check whether numbers are distinct.

I hope these clues might help to realize possible divide and conquer approach.