问:
Accessing Dictionary Elements from Pandas DataFrame
I have a column of dictionaries like this:

id                            element
 1  {'Colour': 'Grey', 'Brand': 'AB'}
 2   {'Colour': 'Blue', 'Brand': 'B'}
 3   {'Colour': 'Red', 'Brand': 'AH'}
```
<p>And I want to create new columns from those dictionaries, like this:</p>
<pre class="lang-py prettyprint-override"><code>id                            element  colour  brand
 1  {'Colour': 'Grey', 'Brand': 'AB'}    Grey     AB
 2   {'Colour': 'Blue', 'Brand': 'B'}    Blue      B
 3   {'Colour': 'Red', 'Brand': 'AH'}     Red     AH
</code>```

I have done the following but it's not working:

def whatever(row):
    tmp_d = {}
    for d in row.values:
        for k in d.keys():
            if k in tmp_d.keys():
                tmp_d[k] += 1
            else:
                tmp_d[k] = 1
    return tmp_d

new_df.colour = df.groupby('element')'element'].apply(whatever).unstack().fillna(0)
```
<p>Data:</p>
```data = {'id': [1, 2, 3],
 'element': ["{'Colour': 'Grey', 'Brand': 'AB'}",
  "{'Colour': 'Blue', 'Brand': 'B'}",
  "{'Colour': 'Red', 'Brand': 'AH'}"]}
```

答:
First, you can convert the strings to dict objects. Then you can also use str.get method to get values under a specific key:

```<code>import ast
df['element'] = df['element'].apply(ast.literal_eval)
df = df.assign(**{key: df['element'].str.get(key) for key in ('Colour','Brand')})
</code>```

Output:

```<code>   id                            element Colour Brand
0   1  {'Colour': 'Grey', 'Brand': 'AB'}   Grey    AB
1   2   {'Colour': 'Blue', 'Brand': 'B'}   Blue     B
2   3   {'Colour': 'Red', 'Brand': 'AH'}    Red    AH
</code>```

Body:
I have a column of dictionaries like this:

id                            element
 1  {'Colour': 'Grey', 'Brand': 'AB'}
 2   {'Colour': 'Blue', 'Brand': 'B'}
 3   {'Colour': 'Red', 'Brand': 'AH'}

And I want to create new columns from those dictionaries, like this:

id                            element  colour  brand
 1  {'Colour': 'Grey', 'Brand': 'AB'}    Grey     AB
 2   {'Colour': 'Blue', 'Brand': 'B'}    Blue      B
 3   {'Colour': 'Red', 'Brand': 'AH'}     Red     AH

I have done the following but it's not working:

def whatever(row):
    tmp_d = {}
    for d in row.values:
        for k in d.keys():
            if k in tmp_d.keys():
                tmp_d[k] += 1
            else:
                tmp_d[k] = 1
    return tmp_d

new_df.colour = df.groupby('element')'element'].apply(whatever).unstack().fillna(0)

Data:

data = {'id': [1, 2, 3],
 'element': ["{'Colour': 'Grey', 'Brand': 'AB'}",
  "{'Colour': 'Blue', 'Brand': 'B'}",
  "{'Colour': 'Red', 'Brand': 'AH'}"]}

Body:
First, you can convert the strings to dict objects. Then you can also use str.get method to get values under a specific key:

import ast
df['element'] = df['element'].apply(ast.literal_eval)
df = df.assign(**{key: df['element'].str.get(key) for key in ('Colour','Brand')})

Output:

   id                            element Colour Brand
0   1  {'Colour': 'Grey', 'Brand': 'AB'}   Grey    AB
1   2   {'Colour': 'Blue', 'Brand': 'B'}   Blue     B
2   3   {'Colour': 'Red', 'Brand': 'AH'}    Red    AH


来源: stackexchange

问:
Operator overloading with python outside a class
```<code>class A:
    def __init__(self,m1,m2):
        self.m1 = m1
        self.m2 = m2

    def __add__(self, other):
        ''' add takes 2 objects basically objects on RHS and LHS of + say a + b '''
        print("Inside add")
        s3 = A(self.m1+other.m1,self.m2+other.m2)
        return s3

    def disp(self):
        print('{} {}'.format(self.m1,self.m2))

    def __str__(self):
        return '{} {}'.format(self.m1,self.m2)

def __add__(self,other):
    return self*other

a = 2+5
print(a)
</code>```

Output seen is: 7
Whereas expected is 10 since I am trying to overwrite the implicit add function with multiply operation.
What happens here?
Does operator overloading works only with pytclass?

答:
```<code>class A:
   def __init__(self,m):
       self.m=m
   def __str__(self):
      return str(self.m)
   #multiply two objects
   def __mul__(self,other):
      t=self.m*other.m
      return A(t)
   #add two objects
   def __add__(self,other):
       t=self.m+other.m
      return A(t)
obj1=A(2)
obj2=A(5)
#calling operator overloading of '*'
print(obj1*obj2)
#calling operator overloading of '+'
print(obj1+obj2)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
class A:
    def __init__(self,m1,m2):
        self.m1 = m1
        self.m2 = m2

    def __add__(self, other):
        ''' add takes 2 objects basically objects on RHS and LHS of + say a + b '''
        print("Inside add")
        s3 = A(self.m1+other.m1,self.m2+other.m2)
        return s3

    def disp(self):
        print('{} {}'.format(self.m1,self.m2))

    def __str__(self):
        return '{} {}'.format(self.m1,self.m2)

def __add__(self,other):
    return self*other

a = 2+5
print(a)

Output seen is: 7
Whereas expected is 10 since I am trying to overwrite the implicit add function with multiply operation.
What happens here?
Does operator overloading works only with pytclass?


问:
is there a way to crop multiple netcdf files using CDO?
I have multiple global climate model (GCM) data files. I successfully cropped one file but it takes time to crop one by one over thousand data files manually. How can I do multiple crops? Thanks</p>

答:
I know I am a little late to add to the answer, but still wanted to add my knowledge for those who would still pass through this question.

I followed the code given by Adrian Tompkins and it seems to work exceptionally fine. But there are somethings to be considered which I'd like to highlight. And because I am still novice at programming, please forgive my much limited answer. So here are my findings for the code above to work...

The code used calls CDO (Climate Data Operators) which is a non-GUI standalone program that can be utilized in Linux terminal. In my case, I used it in my Windows 10 through WSL (Ubuntu 20.04 LTS). There are good videos in youtube for using WSL in youtube.

The code initially did not work for until I made a slight change. The code

```<code>for file in $(ls *.nc) ; do
      cdo sellonlatbox,lon1,lon2,lat1,lat2 $file ${file%???}_crop.nc
done
</code>```

worked for me when I wrote it as

```<code>for file in $(ls *.nc) ; do
    cdo sellonlatbox,lon1,lon2,lat1,lat2 $file ${file%???}_crop.nc;
done
</code>```

see the presence of  a ; in the code in line 2.

The entire code (in my case to work) was put in a text file (can be put as script in other formats as well) and passed as a script in the Linux terminal. The procedure to execute the script file is as follows:

3.a) create the '.txt' file containing the script above. Do note that the directory should be checked in all steps.

3.b) make the file executable by running the command line

chmod +x <name_of_the_textfile_with_extension> in the terminal.

3.c) run the script (in my case it is the textfile) by running the command line ./<name_of_the_textfile_with_extension>

The above procedures will give you cropped netcdf files for the corresponding netcdf files in the same folder.

cheers!

Body:
I know I am a little late to add to the answer, but still wanted to add my knowledge for those who would still pass through this question.

I followed the code given by Adrian Tompkins and it seems to work exceptionally fine. But there are somethings to be considered which I'd like to highlight. And because I am still novice at programming, please forgive my much limited answer. So here are my findings for the code above to work...

The code used calls CDO (Climate Data Operators) which is a non-GUI standalone program that can be utilized in Linux terminal. In my case, I used it in my Windows 10 through WSL (Ubuntu 20.04 LTS). There are good videos in youtube for using WSL in youtube.

The code initially did not work for until I made a slight change. The code

for file in $(ls *.nc) ; do
      cdo sellonlatbox,lon1,lon2,lat1,lat2 $file ${file%???}_crop.nc
done

worked for me when I wrote it as

for file in $(ls *.nc) ; do
    cdo sellonlatbox,lon1,lon2,lat1,lat2 $file ${file%???}_crop.nc;
done

see the presence of  a ; in the code in line 2.

The entire code (in my case to work) was put in a text file (can be put as script in other formats as well) and passed as a script in the Linux terminal. The procedure to execute the script file is as follows:

3.a) create the '.txt' file containing the script above. Do note that the directory should be checked in all steps.

3.b) make the file executable by running the command line

chmod +x <name_of_the_textfile_with_extension> in the terminal.

3.c) run the script (in my case it is the textfile) by running the command line ./<name_of_the_textfile_with_extension>

The above procedures will give you cropped netcdf files for the corresponding netcdf files in the same folder.

cheers!


问:
How to convert list of lists into a pytho dataframe : getting typeError
I have a list of lists named list_values in this format:

```<code>list_values[0] =

[
 {'lat': 55.8313729, 'lng': -3.9775758},
 {'quality_id': 7, 'quality_tx': 'Intersection'},
 [{'address_components': [{'long_name': '7 Dovecote Road',
   'short_name': '7 Dovecote Rd',
   'types': ['rca_address_line_1']},
   {'long_name': '7', 'short_name': '7', 'types': ['street_number']},
   {'long_name': 'Dovecote Road',
     'short_name': 'Dovecote Rd',
     'types': ['route']}],
   'formatted_address': '7 Dovecote Rd, Motherwell ML1, UK',
   'geometry': {'location': {'lat': 55.8313729, 'lng': -3.9775758},
     'location_type': 'RANGE_INTERPOLATED',
     'viewport': {'northeast': {'lat': 55.8327218802915,
       'lng': -3.976226819708498},
       'southwest': {'lat': 55.8300239197085, 'lng': -3.978924780291502}}},
   'partial_match': True,
   'types': ['street_address'],
   'rca_extended_properties': {'geocode': {'quality_id': 7,
     'quality_tx': 'Intersection'},
     'distanceInMeters': None,
     'displayCity_tx': 'Motherwell',
     'displayCityNameOrigin_id': 8,
     'searchParcels': False}}]
]

</code>```

Which I would like to convert to a dataframe, where each of the 3 columns will have each of the lists.
But when I try
lat = pd.DataFrame(list_values) , I get an error
TypeError: object of type 'NoneType' has no len()

What would be a good approach to overcome this?

答:
I believe this is the structure that would work in this particular example:

```<code>[
    {'lat': 51.4900961, 'lng': -0.1792465},
    {'quality_id': 9, 'quality_tx': 'Premises'},
    {'address_components': [
        {'long_name': '34 Cranley Gardens','short_name': '34 Cranley Gardens','types': ['rca_address_line_1']},
        {'long_name': 'England','displayCityNameOrigin_id': 8,'searchParcels': False},
        {'reverse_geocode': {'adminLevel3_id': 61719,'cbd_fg': False,'neighborhood_display_city_name_fg': False}}
    ]}
]
</code>```

Comparing this to the code you posted, i found two issues:

Right in front of 'address components'  you are opening a list but
directly afterwards assign a value in a dictionary type of way by
using the ':'.

Further, right in front of 'reverse_geocode' there is no opening
'{' in your code in order to create a dictionary that consists of
the key 'reverse_geocode'  and the following dictionary.

Body:
I have a list of lists named list_values in this format:

list_values[0] =

[
 {'lat': 55.8313729, 'lng': -3.9775758},
 {'quality_id': 7, 'quality_tx': 'Intersection'},
 [{'address_components': [{'long_name': '7 Dovecote Road',
   'short_name': '7 Dovecote Rd',
   'types': ['rca_address_line_1']},
   {'long_name': '7', 'short_name': '7', 'types': ['street_number']},
   {'long_name': 'Dovecote Road',
     'short_name': 'Dovecote Rd',
     'types': ['route']}],
   'formatted_address': '7 Dovecote Rd, Motherwell ML1, UK',
   'geometry': {'location': {'lat': 55.8313729, 'lng': -3.9775758},
     'location_type': 'RANGE_INTERPOLATED',
     'viewport': {'northeast': {'lat': 55.8327218802915,
       'lng': -3.976226819708498},
       'southwest': {'lat': 55.8300239197085, 'lng': -3.978924780291502}}},
   'partial_match': True,
   'types': ['street_address'],
   'rca_extended_properties': {'geocode': {'quality_id': 7,
     'quality_tx': 'Intersection'},
     'distanceInMeters': None,
     'displayCity_tx': 'Motherwell',
     'displayCityNameOrigin_id': 8,
     'searchParcels': False}}]
]

Which I would like to convert to a dataframe, where each of the 3 columns will have each of the lists.
But when I try
lat = pd.DataFrame(list_values) , I get an error
TypeError: object of type 'NoneType' has no len()

What would be a good approach to overcome this?

Body:
I believe this is the structure that would work in this particular example:

[
    {'lat': 51.4900961, 'lng': -0.1792465},
    {'quality_id': 9, 'quality_tx': 'Premises'},
    {'address_components': [
        {'long_name': '34 Cranley Gardens','short_name': '34 Cranley Gardens','types': ['rca_address_line_1']},
        {'long_name': 'England','displayCityNameOrigin_id': 8,'searchParcels': False},
        {'reverse_geocode': {'adminLevel3_id': 61719,'cbd_fg': False,'neighborhood_display_city_name_fg': False}}
    ]}
]

Comparing this to the code you posted, i found two issues:

Right in front of 'address components'  you are opening a list but
directly afterwards assign a value in a dictionary type of way by
using the ':'.

Further, right in front of 'reverse_geocode' there is no opening
'{' in your code in order to create a dictionary that consists of
the key 'reverse_geocode'  and the following dictionary.


问:
What DB to use for a windows application?
I am developing a small windows application in .net. What DB should I use?

DB Structure

Table 1 : Not more than 3 fields : 50+ records (Add, Delete)

Table 2 : Not more than 10 fields : 10-20 records (Add, Delete)

I thought of using XMLDatabase but some say its not advisable to use it. What are the reasons for this?
If it is OK to use XML files as the DB then can you suggest some tutorials or best practices? I have worked with XML files before. Is there anything different when it comes to using it as a DB?

I am also planning to distribute the application to my friends some time later and these guys are not programmers and they are less tech savvy.

So If I am using SQL server how can I deploy it in others machine? How can I add it to the setup file?

Update: Thanks for the answers. I am going for SQLite and here is a tutorial about SQLite and .net if someone is interested.

答:
Based on what you have mentioned I would either look at SQLite or look at SQL Server Compact Edition.

The recommendation for Compact Edition is so that there is not a SQL Server process running all the time.  Compact edition only runs while the application is running.

Update

When it comes to size between the two, SQLite is a little under 1 mb in size.  SQL Server Compact edition is 1.8mb  (See MS Document for Confirmation).

OwnerDisplayName: Shoban

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Shoban

OwnerDisplayName: Mitchel Sellers

LastEditorDisplayName: Mitchel Sellers


问:
how to calculate difference between two date and get year month and days in flutter
How can I change the Date format in dart

I get the from and to date difference value is int. How to change this integer to date format... and convert it to 0Days 0Months 7days;
I need this type of format

but I got this type of format
see the Vehicle Age:

```<code> vehicleAge(DateTime doPurchase, DateTime doRenewel) {
    age = doPurchase.difference(doRenewel).abs().inDays.toInt();
    return age;
  }
</code>```

That is my function...

答:
Correct Answer

I got a correct answer use jiffy package.

import 'package:jiffy/jiffy.dart';

then use this code

```<code>vehicleAge(DateTime doPurchase, DateTime doRenewel) {
    var dt1 = Jiffy(doPurchase);
    var dt2 = Jiffy(doRenewel);

    int years = int.parse("${dt2.diff(dt1, Units.YEAR)}");
    dt1.add(years: years);

    int month = int.parse("${dt2.diff(dt1, Units.MONTH)}");
    dt1.add(months: month);

    var days = dt2.diff(dt1, Units.DAY);

    return "$years Years $month Month $days Days";

  }
</code>```

Body:
How can I change the Date format in dart

I get the from and to date difference value is int. How to change this integer to date format... and convert it to 0Days 0Months 7days;
I need this type of format

but I got this type of format
see the Vehicle Age:

 vehicleAge(DateTime doPurchase, DateTime doRenewel) {
    age = doPurchase.difference(doRenewel).abs().inDays.toInt();
    return age;
  }

That is my function...

Body:
Correct Answer

I got a correct answer use jiffy package.

import 'package:jiffy/jiffy.dart';

then use this code

vehicleAge(DateTime doPurchase, DateTime doRenewel) {
    var dt1 = Jiffy(doPurchase);
    var dt2 = Jiffy(doRenewel);

    int years = int.parse("${dt2.diff(dt1, Units.YEAR)}");
    dt1.add(years: years);

    int month = int.parse("${dt2.diff(dt1, Units.MONTH)}");
    dt1.add(months: month);

    var days = dt2.diff(dt1, Units.DAY);

    return "$years Years $month Month $days Days";

  }


问:
Executing a Bash Script from Golang
I am trying to figure out a way to execute a script (.sh) file from Golang. I have found a couple of easy ways to execute commands (e.g. os/exec), but what I am looking to do is to execute an entire sh file (the file sets variables etc.).

Using the standard os/exec method for this does not seem to be straightforward: both trying to input "./script.sh" and loading the content of the script into a string do not work as arguments for the exec function.

for example, this is an sh file that I want to execute from Go:

```<code>OIFS=$IFS;
IFS=",";

# fill in your details here
dbname=testDB
host=localhost:27017
collection=testCollection
exportTo=../csv/

# get comma separated list of keys. do this by peeking into the first document in the collection and get his set of keys
keys=`mongo "$host/$dbname" --eval "rs.slaveOk();var keys = []; for(var key in db.$collection.find().sort({_id: -1}).limit(1)[0]) { keys.push(key); }; keys;" --quiet`;
# now use mongoexport with the set of keys to export the collection to csv
mongoexport --host $host -d $dbname -c $collection --fields "$keys" --csv --out $exportTo$dbname.$collection.csv;

IFS=$OIFS;
</code>```

from the Go program:

```<code>out, err := exec.Command(mongoToCsvSH).Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("output is %s\n", out)
</code>```

where mongoToCsvSH can be either the path to the sh or the actual content - both do not work.

Any ideas how to achieve this?

答:
This allows you to pass the arguments as well as get the output of the script in the Stdout or Stderr.

```<code>import (
    "github.com/sirupsen/logrus"
    "os"
    "os/exec"
)

func Execute(script string, command []string) (bool, error) {

    cmd := &exec.Cmd{
        Path:   script,
        Args:   command,
        Stdout: os.Stdout,
        Stderr: os.Stderr,
    }

    c.logger.Info("Executing command ", cmd)

    err := cmd.Start()
    if err != nil {
        return false, err
    }

    err = cmd.Wait()
    if err != nil {
        return false, err
    }

    return true, nil
}
</code>```

Calling example:

```<code>command := []string{
    "/<path>/yourscript.sh",
    "arg1=val1",
    "arg2=val2",
}

Execute("/<path>/yourscript.sh", command)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Executing a Bash Script from Golang

Body:
I am trying to figure out a way to execute a script (.sh) file from Golang. I have found a couple of easy ways to execute commands (e.g. os/exec), but what I am looking to do is to execute an entire sh file (the file sets variables etc.).

Using the standard os/exec method for this does not seem to be straightforward: both trying to input "./script.sh" and loading the content of the script into a string do not work as arguments for the exec function.

for example, this is an sh file that I want to execute from Go:

OIFS=$IFS;
IFS=",";

# fill in your details here
dbname=testDB
host=localhost:27017
collection=testCollection
exportTo=../csv/

# get comma separated list of keys. do this by peeking into the first document in the collection and get his set of keys
keys=`mongo "$host/$dbname" --eval "rs.slaveOk();var keys = []; for(var key in db.$collection.find().sort({_id: -1}).limit(1)[0]) { keys.push(key); }; keys;" --quiet`;
# now use mongoexport with the set of keys to export the collection to csv
mongoexport --host $host -d $dbname -c $collection --fields "$keys" --csv --out $exportTo$dbname.$collection.csv;

IFS=$OIFS;

from the Go program:

out, err := exec.Command(mongoToCsvSH).Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("output is %s\n", out)

where mongoToCsvSH can be either the path to the sh or the actual content - both do not work.

Any ideas how to achieve this?

Body:
This allows you to pass the arguments as well as get the output of the script in the Stdout or Stderr.

import (
    "github.com/sirupsen/logrus"
    "os"
    "os/exec"
)

func Execute(script string, command []string) (bool, error) {

    cmd := &exec.Cmd{
        Path:   script,
        Args:   command,
        Stdout: os.Stdout,
        Stderr: os.Stderr,
    }

    c.logger.Info("Executing command ", cmd)

    err := cmd.Start()
    if err != nil {
        return false, err
    }

    err = cmd.Wait()
    if err != nil {
        return false, err
    }

    return true, nil
}

Calling example:

command := []string{
    "/<path>/yourscript.sh",
    "arg1=val1",
    "arg2=val2",
}

Execute("/<path>/yourscript.sh", command)


问:
Rails 4 pagination with dynamic data
Hi I have a rails4 app using pagination with the will_paginate gem.

Is there a way to handle pagination with objects created very often? If you call the first page and right after that the page 2, considering new objects are created in the meantime, it is going to mess data (the offset in the sql request is for example going to call almost the same data as the first page).

Is there a way to use pagination with rapidly changing dynamic data?

Thx for your suggestions

答: This is a good tutorial showing how to do cursor based pagination without a gem. https://www.ananunesdasilva.com/posts/pagination-in-rails-from-scratch-no-gems I've also saved it in archive.org/wayback machine in case the author doesn't maintain the website in a few years.</p>

Title: Rails 4 pagination with dynamic data


问:
Why does pickle protocol 2 let me serialise an open file object?
Consider:

```<code>>>> import pickle
>>> thing = open('foobar.txt','w')
>>> pickle.dumps(thing)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/pickle.py", line 1366, in dumps
    Pickler(file, protocol).dump(obj)
  File "/usr/lib/python2.6/pickle.py", line 224, in dump
    self.save(obj)
  File "/usr/lib/python2.6/pickle.py", line 306, in save
    rv = reduce(self.proto)
  File "/usr/lib/python2.6/copy_reg.py", line 70, in _reduce_ex
    raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle file objects
</code>```

Seems entirely reasonable - of course I can't pickle an open file handle. But:

```<code>>>> pickle.dumps(thing, 2)
'\x80\x02c__builtin__\nfile\nq\x00)\x81q\x01.'
>>> pickle.loads(pickle.dumps(thing, 2))
<closed file '<uninitialized file>', mode '<uninitialized file>' at 0x7ff3c078>
</code>```

Apparently I can pickle an open file, just not usefully.

Is this deliberate? It was obscuring a bug in my code, where I was wrongly pickling an object that owned a file. Under some conditions, that object also holds a pyodbc cursor, with the same result.

I don't see anything in PEP 307 about it. Was it just an oversight, or is there something important going on that I'm missing, that could let me get the exception I want even when pickling using protocol 2?

I'm using Python 2.6.5. I know, I know, but it's what comes with my distribution.

答:
On the Python Wiki, it says

You cannot pickle open file objects, network connections, or database connections. When you think about it, it makes sense -- pickle cannot will the connection for file object to exist when you unpickle your object, and the process of creating that connection goes beyond what pickle can automatically do for you. If you really want to pickle something that has an attribute that is causing problems, look at the pickle documentation for __getstate__, __setstate__, and __getinitargs__ -- using these you can exclude problematic attributes.

However, I found this bug report which indicates that you actually can pickle file objects. This does seem to be unintentional. It's been fixed in Python 3.2.

You could see if you could adapt that patch to Python 2.6 if you wanted to prevent it from happening. Otherwise, you just need to be careful what you pickle.

Body:
Consider:

>>> import pickle
>>> thing = open('foobar.txt','w')
>>> pickle.dumps(thing)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/pickle.py", line 1366, in dumps
    Pickler(file, protocol).dump(obj)
  File "/usr/lib/python2.6/pickle.py", line 224, in dump
    self.save(obj)
  File "/usr/lib/python2.6/pickle.py", line 306, in save
    rv = reduce(self.proto)
  File "/usr/lib/python2.6/copy_reg.py", line 70, in _reduce_ex
    raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle file objects

Seems entirely reasonable - of course I can't pickle an open file handle. But:

>>> pickle.dumps(thing, 2)
'\x80\x02c__builtin__\nfile\nq\x00)\x81q\x01.'
>>> pickle.loads(pickle.dumps(thing, 2))
<closed file '<uninitialized file>', mode '<uninitialized file>' at 0x7ff3c078>

Apparently I can pickle an open file, just not usefully.

Is this deliberate? It was obscuring a bug in my code, where I was wrongly pickling an object that owned a file. Under some conditions, that object also holds a pyodbc cursor, with the same result.

I don't see anything in PEP 307 about it. Was it just an oversight, or is there something important going on that I'm missing, that could let me get the exception I want even when pickling using protocol 2?

I'm using Python 2.6.5. I know, I know, but it's what comes with my distribution.


问:
Firebase V9 with React Native - Display Name updating too slow
I am new to react, firebase and stack overflow so please bear with me.
I'm trying to create a user registration form with firebase that includes a 'name' input. It does work to update the display name, but not fast enough to show the name when the user first logs in. I need to save the homescreen.js file and then the display name populates.

code from registerscreen.js

```<code> const [name, setName] = useState('')

const handleRegister = async () => {
if (confirmPass !== password){
  alert('Passwords Do Not Match')
  return false}
  else{
}
try{
const user = await createUserWithEmailAndPassword(auth, email, password)
updateProfile(auth.currentUser, {displayName: name})
console.log('logged in with', user.email)
} catch (error) {
    alert(error.message);
}
</code>```

and here is the text on the homescreen.js to display the users name:

```<code> <Text style={styles.text}>Logged in as {auth.currentUser?.displayName}</Text>
</code>```

答:
I think you have two good options.

Save the user's display name locally when they register, for example in Context or AsyncStorage, and use that on your logged-in screen.  In AsyncStorage, that would look something like this:

  // registerscreen.js
  await AsyncStorage.setItem('name', name);

  // homescreen.js body
  const name = await AsyncStorage.getItem('name');
  // homescreen.js return
  <Text style={styles.text}>Logged in as {auth.currentUser?.displayName || name}</Text>

```
<p>Docs for AsyncStorage are here.</p>
<ol start="2">
<li>Show a loading indicator until your Firebase request comes back with the display name.</li>
</ol>
<pre class="lang-js prettyprint-override"><code>  // homescreen.js body
  // get auth object, however you are doing this already
  const auth = await getAuth();
  // homescreen.js return
  return (
   auth?.currentUser
     ? // your current component here
     : <LoadingScreen />
  );
</code>```

LoadingScreen could be something like

  <View style={[StyleSheet.absoluteFill, { justifyContent: 'center', alignItems: 'center'>
    <LoadingIndicator />
  </View>
```

Body:
I am new to react, firebase and stack overflow so please bear with me.
I'm trying to create a user registration form with firebase that includes a 'name' input. It does work to update the display name, but not fast enough to show the name when the user first logs in. I need to save the homescreen.js file and then the display name populates.

code from registerscreen.js

 const [name, setName] = useState('')

const handleRegister = async () => {
if (confirmPass !== password){
  alert('Passwords Do Not Match')
  return false}
  else{
}
try{
const user = await createUserWithEmailAndPassword(auth, email, password)
updateProfile(auth.currentUser, {displayName: name})
console.log('logged in with', user.email)
} catch (error) {
    alert(error.message);
}

and here is the text on the homescreen.js to display the users name:

 <Text style={styles.text}>Logged in as {auth.currentUser?.displayName}</Text>

Body:
I think you have two good options.

Save the user's display name locally when they register, for example in Context or AsyncStorage, and use that on your logged-in screen.  In AsyncStorage, that would look something like this:

  // registerscreen.js
  await AsyncStorage.setItem('name', name);

  // homescreen.js body
  const name = await AsyncStorage.getItem('name');
  // homescreen.js return
  <Text style={styles.text}>Logged in as {auth.currentUser?.displayName || name}</Text>

Docs for AsyncStorage are here.

Show a loading indicator until your Firebase request comes back with the display name.

  // homescreen.js body
  // get auth object, however you are doing this already
  const auth = await getAuth();
  // homescreen.js return
  return (
   auth?.currentUser
     ? // your current component here
     : <LoadingScreen />
  );

LoadingScreen could be something like

  <View style={[StyleSheet.absoluteFill, { justifyContent: 'center', alignItems: 'center'>
    <LoadingIndicator />
  </View>


问:
How to find the title of an URL using VBA in MS Excel
I am working on a VBA project to get Page title and created date from an URL. I found this code online but it's not working since IE is not available. Is there any way I can get the title without IE?

```<code>Function GetPageTitle(a As String)

Set ie = CreateObject("InternetExplorer.Application")
With ie
    .Visible = False
    .Navigate a
    Do Until .ReadyState = 4
        DoEvents
    Loop
    GetPageTitle = .document.Title
    .Quit
End With

End Function
</code>```

I have tried to use Edge as Internet Explorer but it's not working.
I have tried this code also HTML Page Title in Excel VBA

答:
If you want to automate Edge with VBA, you need to use SeleniumBasic. SeleniumBasic is a Selenium based browser automation framework for VB.Net, VBA and VBScript.

You can follow the steps below:

Download the latest version of SeleniumBasic v2.0.9.0 from this link and install it.

Download the corresponding version of Edge WebDriver from this link.

Find the path of SeleniumBasic which is C:\Users\%username%\AppData\Local\SeleniumBasic in my computer (it might also be in this path C:\Program Files\SeleniumBasic), copy the Edge WebDriver msedgedriver.exe to this path.

Rename msedgedriver.exe to edgedriver.exe.

Open Excel and write the VBA code.

In the VBA code interface, click Tools > References, add Selenium Type Library reference and click OK to save.

Sample VBA code to automate Edge using SeleniumBasic to get URL title:

```<code>Public Sub Selenium()
        Dim bot As New WebDriver
        bot.Start "edge", "https://www.bing.com"
        bot.Get "/"
        bot.Wait 5000
        Debug.Print bot.Window.Title  'this line of code can get title
End Sub
</code>```

Body:
I am working on a VBA project to get Page title and created date from an URL. I found this code online but it's not working since IE is not available. Is there any way I can get the title without IE?

Function GetPageTitle(a As String)

Set ie = CreateObject("InternetExplorer.Application")
With ie
    .Visible = False
    .Navigate a
    Do Until .ReadyState = 4
        DoEvents
    Loop
    GetPageTitle = .document.Title
    .Quit
End With

End Function

I have tried to use Edge as Internet Explorer but it's not working.
I have tried this code also HTML Page Title in Excel VBA

Body:
If you want to automate Edge with VBA, you need to use SeleniumBasic. SeleniumBasic is a Selenium based browser automation framework for VB.Net, VBA and VBScript.

You can follow the steps below:

Download the latest version of SeleniumBasic v2.0.9.0 from this link and install it.

Download the corresponding version of Edge WebDriver from this link.

Find the path of SeleniumBasic which is C:\Users\%username%\AppData\Local\SeleniumBasic in my computer (it might also be in this path C:\Program Files\SeleniumBasic), copy the Edge WebDriver msedgedriver.exe to this path.

Rename msedgedriver.exe to edgedriver.exe.

Open Excel and write the VBA code.

In the VBA code interface, click Tools > References, add Selenium Type Library reference and click OK to save.

Sample VBA code to automate Edge using SeleniumBasic to get URL title:

Public Sub Selenium()
        Dim bot As New WebDriver
        bot.Start "edge", "https://www.bing.com"
        bot.Get "/"
        bot.Wait 5000
        Debug.Print bot.Window.Title  'this line of code can get title
End Sub


问:
Using struct in different .cpp file
I have two .cpp files in one project, main.cpp and myfile.cpp

I have globaly defined struct mystruct in main.cpp, now I want to use this struct in myfile.cpp.
When I write mystruct in a header file and include in both cpp files I get an error, saying mystruct redefinition. How should I solve this problem.

答:
If you are trying to share the definition of a struct among several compilation units (cpp files), the common way is this: Place the definition of your struct in a header file (mystruct.h). If the struct contains any methods (i.e. it is rather a class with all member public by default), you can implement them in mystruct.CPP file, or, if they're lightweight, directly within the struct (which makes them inline by default).

mystruct.h:

```<code>#ifndef MYSTRUCT_H
#define MYSTRUCT_H

struct MyStruct
{
    int x;
    void f1() { /* Implementation here. */ }
    void f2(); /* Implemented in mystruct.cpp */
};

#endif
</code>```

mystruct.cpp

```<code>#include "mystruct.h"
// Implementation of f2() goes here
void MyStruct::f2() { ... }
</code>```

You can use your struct in as many cpp files as you like, simply #include mystruct.h:

main.cpp

```<code>#include "mystruct.h"
int main()
{
    MyStruct myStruct;
    myStruct.x = 1;
    myStruct.f2();
    // etc...
}
</code>```

If, on the other hand, you are trying to share a global instance of the struct across several compilation units (it's not absolutely clear from your question), do as above but also add

```<code>extern MyStruct globalStruct;
</code>```

to mystruct.h. This will announce that an instance is available with external linkage; in other words that a variable exists but is initialized elsewhere (in your case in mystruct.cpp). Add the initialization of the global instance to mystruct.cpp:

MyStruct globalStruct;

This is important. Without manually creating an instance of globalStruct, you'd get unresolved-external linker errors. Now you have access to globalStruct from each compilation unit that includes mystruct.h.

Title: Using struct in different .cpp file

Body:
If you are trying to share the definition of a struct among several compilation units (cpp files), the common way is this: Place the definition of your struct in a header file (mystruct.h). If the struct contains any methods (i.e. it is rather a class with all member public by default), you can implement them in mystruct.CPP file, or, if they're lightweight, directly within the struct (which makes them inline by default).

mystruct.h:

#ifndef MYSTRUCT_H
#define MYSTRUCT_H

struct MyStruct
{
    int x;
    void f1() { /* Implementation here. */ }
    void f2(); /* Implemented in mystruct.cpp */
};

#endif

mystruct.cpp

#include "mystruct.h"
// Implementation of f2() goes here
void MyStruct::f2() { ... }

You can use your struct in as many cpp files as you like, simply #include mystruct.h:

main.cpp

#include "mystruct.h"
int main()
{
    MyStruct myStruct;
    myStruct.x = 1;
    myStruct.f2();
    // etc...
}

If, on the other hand, you are trying to share a global instance of the struct across several compilation units (it's not absolutely clear from your question), do as above but also add

extern MyStruct globalStruct;

to mystruct.h. This will announce that an instance is available with external linkage; in other words that a variable exists but is initialized elsewhere (in your case in mystruct.cpp). Add the initialization of the global instance to mystruct.cpp:

MyStruct globalStruct;

This is important. Without manually creating an instance of globalStruct, you'd get unresolved-external linker errors. Now you have access to globalStruct from each compilation unit that includes mystruct.h.


问:
Price range facets are always disabled with zero count
I'm using the default setup by Oscar 2.0 with ElasticSearch 2.4.6, however, the price range data generated by facets are always disabled with zero count, the other data related to the fields (rating and product class) are fine

I've noticed that the output of self.results.facet_counts() is just counting the number of items which has a price and not using the provided query for ranges, however, the quert_facets info under the search_query() looks fine, showing the query ranges required

self.results.facet_counts() screenshot

Search_QuerySet.quert_facets screenshot

context output

# Search facets
OSCAR_SEARCH_FACETS = {
    'fields': OrderedDict([
        ('product_class', {'name': _('Type'), 'field': 'product_class'}),
        ('rating', {'name': _('Rating'), 'field': 'rating'}),
    ]),
    'queries': OrderedDict([
        ('price_range',
         {
             'name': _('Price range'),
             'field': 'price',
             'queries': [
                 # This is a list of (name, query) tuples where the name will
                 # be displayed on the front-end.
                 (_('0 to 20'), '[0 TO 20]'),
                 (_('20 to 40'), '[20 TO 40]'),
                 (_('40 to 60'), '[40 TO 60]'),
                 (_('60+'), '[60 TO *]'),
             ]
         }),
    ]),
}
```

答: Zero count indicates that there are no products indexed in that price range. Try setting the price of the product in the shown range and thereafter rebuild indexes.</p>


问:
error reading and writing files in cloud function
I am reading file from SharePoint and writitng in GCS bucket but when I run the function it gives me error "Error [Errno 30] Read-only file system: 'test.xlsx'"
here is the code

response = File.open_binary(ctx,location/file )

blob = bucket.blob('/sharepoint/' + doc)
print('connection')
with open("test.xlsx", "wb") as local_file:
    blob.upload_from_file(local_file)
    local_file.close()
```

please help if anyone know the solution of this error

答:
Doing this open("test.xlsx", "wb") destroys the file. The file is also locked while open which causes the error message.

Change your code to open the file in read mode:

```<code>with open("test.xlsx", "rb") as local_file:
    blob.upload_from_file(local_file)
    local_file.close()
</code>```

Body:
I am reading file from SharePoint and writitng in GCS bucket but when I run the function it gives me error "Error [Errno 30] Read-only file system: 'test.xlsx'"
here is the code

response = File.open_binary(ctx,location/file )

blob = bucket.blob('/sharepoint/' + doc)
print('connection')
with open("test.xlsx", "wb") as local_file:
    blob.upload_from_file(local_file)
    local_file.close()

please help if anyone know the solution of this error

Body:
Doing this open("test.xlsx", "wb") destroys the file. The file is also locked while open which causes the error message.

Change your code to open the file in read mode:

with open("test.xlsx", "rb") as local_file:
    blob.upload_from_file(local_file)
    local_file.close()


问:
Callback function behaviour in JS
I came across callback functions in JS and found it to be really amazing. Though there is something about how callbacks behave that i am not able to understand.
Example:

```<code>function add(num1, num2){
  return num1 + num2;
}

function displaySum(num1, num2, callback){
  let a = callback(num1, num2)
  console.log(a);
}

setTimeout(displaySum(3,5,add), 3000); // This displays the result instantly
</code>```

And in a similar case

function displayText(text){
    console.log('HEY JS');
}
setTimeout(displayText, 3000) //This seems to work
```

I am not able to understand why is this happening?

答:
The issue is that you are directly calling the function inside the setTimeout. That function gets invoked and nothing is sent back.

setTimeout expects a function to be executed after the timer expires. You should only specify the referene to that function.

```<code>setTimeout(displaySum(3,5,add), 3000);
</code>```

With the above statement you are instantly calling the displaySum function with 3 parameters. That is why you can see the result instantly. This function donot have a return value so there is no event that needs to be triggered after specified interval.

Replace that with

```<code>setTimeout(() => displaySum(3, 5, add), 3000);
</code>```

Here the arraw function returns displaySum(3, 5, add), and this function will be called after specified interval.

function add(num1, num2) {
    return num1 + num2;
}

function displaySum(num1, num2, callback) {
    let a = callback(num1, num2)
    console.log(a);
}

setTimeout(() => displaySum(3, 5, add), 3000);```

Title: Callback function behaviour in JS

Body:
I came across callback functions in JS and found it to be really amazing. Though there is something about how callbacks behave that i am not able to understand.
Example:

function add(num1, num2){
  return num1 + num2;
}

function displaySum(num1, num2, callback){
  let a = callback(num1, num2)
  console.log(a);
}

setTimeout(displaySum(3,5,add), 3000); // This displays the result instantly

And in a similar case

function displayText(text){
    console.log('HEY JS');
}
setTimeout(displayText, 3000) //This seems to work

I am not able to understand why is this happening?

Body:
The issue is that you are directly calling the function inside the setTimeout. That function gets invoked and nothing is sent back.

setTimeout expects a function to be executed after the timer expires. You should only specify the referene to that function.

setTimeout(displaySum(3,5,add), 3000);

With the above statement you are instantly calling the displaySum function with 3 parameters. That is why you can see the result instantly. This function donot have a return value so there is no event that needs to be triggered after specified interval.

Replace that with

setTimeout(() => displaySum(3, 5, add), 3000);

Here the arraw function returns displaySum(3, 5, add), and this function will be called after specified interval.

function add(num1, num2) {
    return num1 + num2;
}

function displaySum(num1, num2, callback) {
    let a = callback(num1, num2)
    console.log(a);
}

setTimeout(() => displaySum(3, 5, add), 3000);


问:
How to change the text based on suggestions through GAS and Google DOC API
As title, yesterday I learn how to retrieve the All-suggestion-accepted content of a document with API in this post, and I refer to the other post and know how to retrieve the insertion and deletion of the suggestion. Also, with the method above, I can retrieve the start-index(The position where insertion or deletion starts in a document) and end-index(The position where insertion or deletion ends in a document)  of the insertion and deletion.

So, can I make changes, such as underlining the insertion or deletion parts, to the All-suggestion-accepted content referring to the indexes as positions? Is there going to be an error if I do this?

This is the array Google Doc API returned to me, and its format is
[suggestedDeletionIds,"delete",content,startIndex,endIndex]

This is the insertion and the deletion I made to the document, and I want to underline the deletion and insertion part within the All-suggestion-accepted content of a document based on the index.

Below is the snippet and the result of the snippet, last two figures are the start and the end index of the insertion or deletion.

```<code>function get_all_insertion_deletion() {
  var documentId = "MYDOCUMENTID";
  var doc = Docs.Documents.get(documentId);
  remove_all(documentId);
  doc.body.content.forEach(function (content){
    if (content.paragraph) {
      var elements = content.paragraph.elements;

      elements.forEach(function (element){
        if(element.textRun.suggestedDeletionIds)
        {
          var d_length= element.endIndex-element.startIndex;
          var d= [element.textRun.suggestedDeletionIds,"delete",element.textRun.content,element.startIndex,element.endIndex];
          Logger.log(d);
          deletion++;
        }
        if(element.textRun.suggestedInsertionIds)
        {
          var i_length= element.endIndex-element.startIndex;
          var i= [element.textRun.suggestedInsertionIds,"insert",element.textRun.content,element.startIndex,element.endIndex];
          Logger.log(i);
          insertion++; }  }); }
      });
    }

</code>```

答:
I believe your goal is as follows.

You want to add the underline to "delete" and "insert" parts of your script in Google Document.

In order to achieve your goal, when your script is modified it becomes as follows.

Modified script:

function get_all_insertion_deletion() {
  var documentId = "MYDOCUMENTID";
  var doc = Docs.Documents.get(documentId);
  var requests = [];
  doc.body.content.forEach(function (content) {
    if (content.paragraph) {
      var elements = content.paragraph.elements;

      elements.forEach(function (element) {
        if (element.textRun.suggestedDeletionIds) {
          // var d_length = element.endIndex - element.startIndex;  // This is not used.
          var d = [element.textRun.suggestedDeletionIds, "delete", element.textRun.content, element.startIndex, element.endIndex];
          Logger.log(d);
          requests.push({ updateTextStyle: { range: { startIndex: element.startIndex, endIndex: element.endIndex }, textStyle: { underline: true }, fields: "underline" } });
          // deletion++; // This is not used.
        }
        if (element.textRun.suggestedInsertionIds) {
          // var i_length = element.endIndex - element.startIndex;  // This is not used.
          var i = [element.textRun.suggestedInsertionIds, "insert", element.textRun.content, element.startIndex, element.endIndex];
          requests.push({ updateTextStyle: { range: { startIndex: element.startIndex, endIndex: element.endIndex }, textStyle: { underline: true }, fields: "underline" } });
          Logger.log(i);
          // insertion++; // This is not used.
        }
      });
    }
  });
  Docs.Documents.batchUpdate({requests}, documentId);
}
```
<p>or, I thought that you can also the following modified script.</p>
<pre class="lang-js prettyprint-override"><code>function get_all_insertion_deletion() {
  var documentId = "MYDOCUMENTID";
  var doc = Docs.Documents.get(documentId);
  var requests = doc.body.content.flatMap(content => {
    if (content.paragraph) {
      var elements = content.paragraph.elements;
      return elements.flatMap(element => element.textRun.suggestedDeletionIds || element.textRun.suggestedInsertionIds ? { updateTextStyle: { range: { startIndex: element.startIndex, endIndex: element.endIndex }, textStyle: { underline: true }, fields: "underline" } } : []);
    }
    return [];
  });
  Docs.Documents.batchUpdate({requests}, documentId);
}
</code>```

Reference:

UpdateTextStyleRequest

Body:
As title, yesterday I learn how to retrieve the All-suggestion-accepted content of a document with API in this post, and I refer to the other post and know how to retrieve the insertion and deletion of the suggestion. Also, with the method above, I can retrieve the start-index(The position where insertion or deletion starts in a document) and end-index(The position where insertion or deletion ends in a document)  of the insertion and deletion.

So, can I make changes, such as underlining the insertion or deletion parts, to the All-suggestion-accepted content referring to the indexes as positions? Is there going to be an error if I do this?

This is the array Google Doc API returned to me, and its format is
[suggestedDeletionIds,"delete",content,startIndex,endIndex]

This is the insertion and the deletion I made to the document, and I want to underline the deletion and insertion part within the All-suggestion-accepted content of a document based on the index.

Below is the snippet and the result of the snippet, last two figures are the start and the end index of the insertion or deletion.

function get_all_insertion_deletion() {
  var documentId = "MYDOCUMENTID";
  var doc = Docs.Documents.get(documentId);
  remove_all(documentId);
  doc.body.content.forEach(function (content){
    if (content.paragraph) {
      var elements = content.paragraph.elements;

      elements.forEach(function (element){
        if(element.textRun.suggestedDeletionIds)
        {
          var d_length= element.endIndex-element.startIndex;
          var d= [element.textRun.suggestedDeletionIds,"delete",element.textRun.content,element.startIndex,element.endIndex];
          Logger.log(d);
          deletion++;
        }
        if(element.textRun.suggestedInsertionIds)
        {
          var i_length= element.endIndex-element.startIndex;
          var i= [element.textRun.suggestedInsertionIds,"insert",element.textRun.content,element.startIndex,element.endIndex];
          Logger.log(i);
          insertion++; }  }); }
      });
    }

Body:
I believe your goal is as follows.

You want to add the underline to "delete" and "insert" parts of your script in Google Document.

In order to achieve your goal, when your script is modified it becomes as follows.

Modified script:

function get_all_insertion_deletion() {
  var documentId = "MYDOCUMENTID";
  var doc = Docs.Documents.get(documentId);
  var requests = [];
  doc.body.content.forEach(function (content) {
    if (content.paragraph) {
      var elements = content.paragraph.elements;

      elements.forEach(function (element) {
        if (element.textRun.suggestedDeletionIds) {
          // var d_length = element.endIndex - element.startIndex;  // This is not used.
          var d = [element.textRun.suggestedDeletionIds, "delete", element.textRun.content, element.startIndex, element.endIndex];
          Logger.log(d);
          requests.push({ updateTextStyle: { range: { startIndex: element.startIndex, endIndex: element.endIndex }, textStyle: { underline: true }, fields: "underline" } });
          // deletion++; // This is not used.
        }
        if (element.textRun.suggestedInsertionIds) {
          // var i_length = element.endIndex - element.startIndex;  // This is not used.
          var i = [element.textRun.suggestedInsertionIds, "insert", element.textRun.content, element.startIndex, element.endIndex];
          requests.push({ updateTextStyle: { range: { startIndex: element.startIndex, endIndex: element.endIndex }, textStyle: { underline: true }, fields: "underline" } });
          Logger.log(i);
          // insertion++; // This is not used.
        }
      });
    }
  });
  Docs.Documents.batchUpdate({requests}, documentId);
}

or, I thought that you can also the following modified script.

function get_all_insertion_deletion() {
  var documentId = "MYDOCUMENTID";
  var doc = Docs.Documents.get(documentId);
  var requests = doc.body.content.flatMap(content => {
    if (content.paragraph) {
      var elements = content.paragraph.elements;
      return elements.flatMap(element => element.textRun.suggestedDeletionIds || element.textRun.suggestedInsertionIds ? { updateTextStyle: { range: { startIndex: element.startIndex, endIndex: element.endIndex }, textStyle: { underline: true }, fields: "underline" } } : []);
    }
    return [];
  });
  Docs.Documents.batchUpdate({requests}, documentId);
}

Reference:

UpdateTextStyleRequest


问:
React native: is it recommended to use PNG or SVG images?
I'm working on a react-native project and I have over 30 icons of SVG format. I want to know if it is recommended to convert those images to PNG or it's better to use as SVG files.
If it's better to use images as SVG what is the best way to show SVG file on react native?</p>

答:
Prefer PNG over SVG for react-native apps because its rendering is less CPU intensive, and comparing to web apps user don't need to load all images on each app launch but only on installation, so the size doesn't matter that much.

Just make sure you provide three (or at least the last two) sizes:

```<code>image.png
image@2x.png
image@3x.png
</code>```

Body:
Prefer PNG over SVG for react-native apps because its rendering is less CPU intensive, and comparing to web apps user don't need to load all images on each app launch but only on installation, so the size doesn't matter that much.

Just make sure you provide three (or at least the last two) sizes:

image.png
image@2x.png
image@3x.png


问:
Node.js: How to create paid node modules?
How to sell node modules?

I need to publish my CMS plugins to NPM and allow users to install them, so some of them could be paid.

How do i do it?

答:
Adding on to the previous answers, the best available approaches now is to create a private npm package and  share it over any market place.

Available options are

PRIV Js

Its an javascript marketplace where you can sell your JS packages or purchase from others.

Provides its own interface to create private packages so you don't need to have your own server.

It lets you control the pricing and track downloads or grant special access as required.

Supports scoped packages as well.

Base Tools

Helps to create a paywall for your npm package

Provides github integration to your private repositories.

Github sponsor only repos

Github has recently enabled sponsor only repositories

This enables you to give access to only those who are willing to sponsor to your project.

Gumroad

Its an marketplace to sell anything


问:
Pivot an observable collection
I have records like this in observable collection

```
ID Department salary joingdate
1    .NET   5000  04/08/2011
2    .NET   6000  04/07/2011
3    JAVA   7000  04/08/2011
4    JAVA   8000  04/07/2011
5    .NET   9000  04/06/2011
```

now I want new observable collection like

```
Joingdate    .NET(Salary)  JAVA(Salary)
04/08/2011  5000        7000
04/07/2011  6000        8000
04/06/2011  9000        NULL

```

How would I get this type of observable collection?

答:
Assuming you have follwing structure that resembles your structure:

```<code>public class Data1
{
    public int Id { get; set; }
    public String Dep { get; set; }
    public int Sal { get; set; }
    public String JoinDate { get; set; }
}

public class Data2
{
    public Data2()
    {
        Sal = new List<int>();
    }

    public List<int> Sal { get; set; }
    public String JoinDate { get; set; }

    public override string ToString()
    {
        return Sal.Aggregate(JoinDate, (current, s) => current + s.ToString());
    }
}
</code>```

And following observable collections:

```<code>public class Data1List : ObservableCollection<Data1>
{
    public Data1List()
    {
        Add(new Data1{ Id = 1, Dep = ".NET", Sal = 5000, JoinDate = "04/08/2011"});
        Add(new Data1{ Id = 2, Dep = ".NET", Sal = 6000, JoinDate = "04/07/2011"});
        Add(new Data1{ Id = 3, Dep = "JAVA", Sal = 7000, JoinDate = "04/08/2011"});
        Add(new Data1{ Id = 4, Dep = "JAVA", Sal = 8000, JoinDate = "04/07/2011"});
        Add(new Data1{ Id = 5, Dep = ".NET", Sal = 9000, JoinDate = "04/06/2011"});
    }
}

public class Data2List : ObservableCollection<Data2>
{
}
</code>```

You could try this code to solve your problem or at least get you on the way to a maybe better solution:

```<code>var l1 = new Data1List();
var l2 = new Data2List();

foreach (var items in l1.GroupBy(d => d.JoinDate))
{
    var d2 = new Data2 { JoinDate = items.Key };
    foreach (var item in items)
        d2.Sal.Add(item.Sal);
    l2.Add(d2);
}
</code>```

I hope this helps you getting to a solution! :)

Title: Pivot an observable collection

Body:
I have records like this in observable collection

ID Department salary joingdate
1    .NET   5000  04/08/2011
2    .NET   6000  04/07/2011
3    JAVA   7000  04/08/2011
4    JAVA   8000  04/07/2011
5    .NET   9000  04/06/2011

now I want new observable collection like

Joingdate    .NET(Salary)  JAVA(Salary)
04/08/2011  5000        7000
04/07/2011  6000        8000
04/06/2011  9000        NULL

How would I get this type of observable collection?

Body:
Assuming you have follwing structure that resembles your structure:

public class Data1
{
    public int Id { get; set; }
    public String Dep { get; set; }
    public int Sal { get; set; }
    public String JoinDate { get; set; }
}

public class Data2
{
    public Data2()
    {
        Sal = new List<int>();
    }

    public List<int> Sal { get; set; }
    public String JoinDate { get; set; }

    public override string ToString()
    {
        return Sal.Aggregate(JoinDate, (current, s) => current + s.ToString());
    }
}

And following observable collections:

public class Data1List : ObservableCollection<Data1>
{
    public Data1List()
    {
        Add(new Data1{ Id = 1, Dep = ".NET", Sal = 5000, JoinDate = "04/08/2011"});
        Add(new Data1{ Id = 2, Dep = ".NET", Sal = 6000, JoinDate = "04/07/2011"});
        Add(new Data1{ Id = 3, Dep = "JAVA", Sal = 7000, JoinDate = "04/08/2011"});
        Add(new Data1{ Id = 4, Dep = "JAVA", Sal = 8000, JoinDate = "04/07/2011"});
        Add(new Data1{ Id = 5, Dep = ".NET", Sal = 9000, JoinDate = "04/06/2011"});
    }
}

public class Data2List : ObservableCollection<Data2>
{
}

You could try this code to solve your problem or at least get you on the way to a maybe better solution:

var l1 = new Data1List();
var l2 = new Data2List();

foreach (var items in l1.GroupBy(d => d.JoinDate))
{
    var d2 = new Data2 { JoinDate = items.Key };
    foreach (var item in items)
        d2.Sal.Add(item.Sal);
    l2.Add(d2);
}

I hope this helps you getting to a solution! :)


问:
Getting CUDA out of memory under pytorch in Google Colab
I am trying to replicate the work described here (https://www.analyticsvidhya.com/blog/2019/02/building-crowd-counting-model-python/) in google colab. Unfortunately at first it was working but after a some time it is showing cuda out of memory error for this line of code.

output = model(img.unsqueeze(0))
```

<p>Here is the error description:</p>

```RuntimeError: CUDA out of memory. Tried to allocate 98.00 MiB (GPU 0; 11.17 GiB total capacity; 10.78 GiB already allocated; 40.81 MiB free; 34.25 MiB cached)
```

I tried to run this code in different google account but shows same error.

答: You could also resolve the issue by lowering the batch size and not the image resolution - as lowering the latter will affect the classification accuracy</p>

Body:
I am trying to replicate the work described here (https://www.analyticsvidhya.com/blog/2019/02/building-crowd-counting-model-python/) in google colab. Unfortunately at first it was working but after a some time it is showing cuda out of memory error for this line of code.

output = model(img.unsqueeze(0))

Here is the error description:

RuntimeError: CUDA out of memory. Tried to allocate 98.00 MiB (GPU 0; 11.17 GiB total capacity; 10.78 GiB already allocated; 40.81 MiB free; 34.25 MiB cached)

I tried to run this code in different google account but shows same error.


问:
How can I reshape the tensor
```<code>tensor([[17,  0],
        [93,  0],
        [ 4,  0],
        [72,  0],
        [83,  0],
        [67,  0],
        [34,  0],
        [21,  0],
        [19,  0])
</code>```

I want to remove 0 from this tensor, which is a two-dimensional array, and make it a one-dimensional array.

How can I make this tensor with the tensor below?

```<code>tensor([[17],
        [93],
        [4],
        [72],
        [83],
        [67],
        [34],
        [21],
        [19])
</code>```

答:
In Tensorflow, you can simply use a boolean_mask:

import tensorflow as tf

tensor = tf.constant([[17,  0],
        [93,  0],
        [ 4,  0],
        [72,  0],
        [83,  0],
        [67,  0],
        [34,  0],
        [21,  0],
        [19,  0]])
tensor = tf.boolean_mask(tensor, tf.cast(tensor, dtype=tf.bool), axis=0)
```
```tf.Tensor([17 93  4 72 83 67 34 21 19], shape=(9,), dtype=int32)
```

Title: How can I reshape the tensor

Body:
tensor([[17,  0],
        [93,  0],
        [ 4,  0],
        [72,  0],
        [83,  0],
        [67,  0],
        [34,  0],
        [21,  0],
        [19,  0])

I want to remove 0 from this tensor, which is a two-dimensional array, and make it a one-dimensional array.

How can I make this tensor with the tensor below?

tensor([[17],
        [93],
        [4],
        [72],
        [83],
        [67],
        [34],
        [21],
        [19])

Body:
In Tensorflow, you can simply use a boolean_mask:

import tensorflow as tf

tensor = tf.constant([[17,  0],
        [93,  0],
        [ 4,  0],
        [72,  0],
        [83,  0],
        [67,  0],
        [34,  0],
        [21,  0],
        [19,  0]])
tensor = tf.boolean_mask(tensor, tf.cast(tensor, dtype=tf.bool), axis=0)

tf.Tensor([17 93  4 72 83 67 34 21 19], shape=(9,), dtype=int32)


问:
Opening colab from github jupyter notebook converts code to markdown
Example notebook:
When I open it in colab by clicking the 'Open in colab' banner or directly:
the code cells convert to markdown even though they are code cells in the original jupyter notebook. What am I doing wrong?</p>

答:
I managed to resolve the issue by editing metadata of jupyter notebook, replacing "text" by "code" in "colab_type":

"cell_type": "code",
"execution_count": null,
"metadata": {
"colab_type": "text"


问:
How to compare large text files?
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

```<code>mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT
</code>```

file_2looks like this:

```<code>mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT
</code>```

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!

答:
try to avoid memory consuming and make it disc consuming.
i mean divide each file into loadable size parts and compare them, this may take some extra time but will keep you safe dealing with memory limits. </p>

Title: How to compare large text files?

Body:
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT

file_2looks like this:

mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!


问:
Changing channel from unbuffered to buffered prevents goroutine from running
Here is an exercise using channels and select in a goroutine.  If the disconnect channel is changed to a buffered channel the goroutine doesn't run at all.

Why does changing from an unbuffered to a buffered channel prevent running the goroutine?

```<code>func SelectDemo(wg *sync.WaitGroup) {

    messageCh := make(chan int, 10)
    disconnectCh := make(chan struct{})
    //  go routine won't run if channel is buffered
    //disconnectCh := make(chan struct{}, 1)

    defer close(messageCh)
    defer close(disconnectCh)
    go func() {
        fmt.Println("  goroutine")
        wg.Add(1)
        for {
            select {
            case v := <-messageCh:
                fmt.Println(v)
            case <-disconnectCh:
                fmt.Println("  disconnectCh")
                //  empty the buffered channel before exiting
                for {
                    select {
                    case v := <-messageCh:
                        fmt.Println(v)
                    default:
                        fmt.Println("  disconnection, return")
                        wg.Done()
                        return
                    }
                }
            }
        }
    }()

    fmt.Println("Sending ints")
    for i := 0; i < 10; i++ {
        messageCh <- i
    }

    fmt.Println("Sending done")
    disconnectCh <- struct{}{}
}
</code>```

Here's the code to call the function from main.  I use the wait group to assure that the goroutine completes before the program exits:

```<code>wg := sync.WaitGroup{}
ch09.SelectDemo(&wg)
wg.Wait()
</code>```

答:
Program execution is fast

Visit URL: https://pkg.go.dev/sync#WaitGroup.Add

Note that calls with a positive delta that occur when the counter is zero must happen before a Wait. Calls with a negative delta, or calls with a positive delta that start when the counter is greater than zero, may happen at any time. Typically this means the calls to Add should execute before the statement creating the goroutine or other event to be waited for. If a WaitGroup is reused to wait for several independent sets of events, new Add calls must happen after all previous Wait calls have returned. See the WaitGroup example.

```<code>func SelectDemo(wg *sync.WaitGroup) {

    messageCh := make(chan int, 10)
    disconnectCh := make(chan struct{}, 1)
    //  go routine won't run if channel is buffered
    //disconnectCh := make(chan struct{}, 1)

    wg.Add(1)

    defer close(messageCh)
    defer close(disconnectCh)
    go func() {
        fmt.Println("  goroutine")
        for {
            select {
            case v := <-messageCh:
                fmt.Println(v)
            case <-disconnectCh:
                fmt.Println("  disconnectCh")
                //  empty the buffered channel before exiting

                fmt.Println("  disconnection, return")
                wg.Done()
                return
            }
        }
    }()

    fmt.Println("Sending ints")
    for i := 0; i < 10; i++ {
        messageCh <- i
    }

    //Delay sending exit signal
    time.Sleep(3 * time.Second)

    fmt.Println("Sending done")
    disconnectCh <- struct{}{}
}

</code>```

I modified your code

try again!!!

Body:
Here is an exercise using channels and select in a goroutine.  If the disconnect channel is changed to a buffered channel the goroutine doesn't run at all.

Why does changing from an unbuffered to a buffered channel prevent running the goroutine?

func SelectDemo(wg *sync.WaitGroup) {

    messageCh := make(chan int, 10)
    disconnectCh := make(chan struct{})
    //  go routine won't run if channel is buffered
    //disconnectCh := make(chan struct{}, 1)

    defer close(messageCh)
    defer close(disconnectCh)
    go func() {
        fmt.Println("  goroutine")
        wg.Add(1)
        for {
            select {
            case v := <-messageCh:
                fmt.Println(v)
            case <-disconnectCh:
                fmt.Println("  disconnectCh")
                //  empty the buffered channel before exiting
                for {
                    select {
                    case v := <-messageCh:
                        fmt.Println(v)
                    default:
                        fmt.Println("  disconnection, return")
                        wg.Done()
                        return
                    }
                }
            }
        }
    }()

    fmt.Println("Sending ints")
    for i := 0; i < 10; i++ {
        messageCh <- i
    }

    fmt.Println("Sending done")
    disconnectCh <- struct{}{}
}

Here's the code to call the function from main.  I use the wait group to assure that the goroutine completes before the program exits:

wg := sync.WaitGroup{}
ch09.SelectDemo(&wg)
wg.Wait()

Body:
Program execution is fast

Visit URL: https://pkg.go.dev/sync#WaitGroup.Add

Note that calls with a positive delta that occur when the counter is zero must happen before a Wait. Calls with a negative delta, or calls with a positive delta that start when the counter is greater than zero, may happen at any time. Typically this means the calls to Add should execute before the statement creating the goroutine or other event to be waited for. If a WaitGroup is reused to wait for several independent sets of events, new Add calls must happen after all previous Wait calls have returned. See the WaitGroup example.

func SelectDemo(wg *sync.WaitGroup) {

    messageCh := make(chan int, 10)
    disconnectCh := make(chan struct{}, 1)
    //  go routine won't run if channel is buffered
    //disconnectCh := make(chan struct{}, 1)

    wg.Add(1)

    defer close(messageCh)
    defer close(disconnectCh)
    go func() {
        fmt.Println("  goroutine")
        for {
            select {
            case v := <-messageCh:
                fmt.Println(v)
            case <-disconnectCh:
                fmt.Println("  disconnectCh")
                //  empty the buffered channel before exiting

                fmt.Println("  disconnection, return")
                wg.Done()
                return
            }
        }
    }()

    fmt.Println("Sending ints")
    for i := 0; i < 10; i++ {
        messageCh <- i
    }

    //Delay sending exit signal
    time.Sleep(3 * time.Second)

    fmt.Println("Sending done")
    disconnectCh <- struct{}{}
}

I modified your code

try again!!!


问:
How to Hide Continue and Cancel button on Flutter Stepper
I wanna hide Continue and Cancel Button on Stepper
And change to On Enter Text Filed for continuing the step.
Is it possible?
How to do that?

Thanks

答:
I have already used this code for hiding Continue and Cancel.

Firt declare variable hide as bool and the value is false

```<code>bool hide = false;
</code>```

Then use controlsBuilder in the stapper.

For Flutter >2.6

```<code>controlsBuilder: (BuildContext ctx, ControlsDetails dtl){
           return Row(
            children: <Widget>[
              TextButton(
                onPressed: dtl.onStepContinue,
                child: Text(hide == true ? '' : 'NEXT'),
              ),
              TextButton(
                onPressed: dtl.onStepCancel,
                child: Text(hide == true ? '' :'CANCEL'),
              ),
            ],
          );
        },
</code>```

And for flutter <= 2.5

```<code>controlsBuilder: (BuildContext context, { VoidCallback? onStepContinue, VoidCallback? onStepCancel }) {
         return Row(
           children: <Widget>[
             TextButton(
               onPressed: onStepContinue,
               child:  Text(hide == true ? '' : 'NEXT'),
             ),
             TextButton(
               onPressed: onStepCancel,
               child: Text(hide == true ? '' : 'CANCEL'),
             ),
           ],
         );
      },
</code>```

CMIIW

Thanks,

Body:
I have already used this code for hiding Continue and Cancel.

Firt declare variable hide as bool and the value is false

bool hide = false;

Then use controlsBuilder in the stapper.

For Flutter >2.6

controlsBuilder: (BuildContext ctx, ControlsDetails dtl){
           return Row(
            children: <Widget>[
              TextButton(
                onPressed: dtl.onStepContinue,
                child: Text(hide == true ? '' : 'NEXT'),
              ),
              TextButton(
                onPressed: dtl.onStepCancel,
                child: Text(hide == true ? '' :'CANCEL'),
              ),
            ],
          );
        },

And for flutter <= 2.5

controlsBuilder: (BuildContext context, { VoidCallback? onStepContinue, VoidCallback? onStepCancel }) {
         return Row(
           children: <Widget>[
             TextButton(
               onPressed: onStepContinue,
               child:  Text(hide == true ? '' : 'NEXT'),
             ),
             TextButton(
               onPressed: onStepCancel,
               child: Text(hide == true ? '' : 'CANCEL'),
             ),
           ],
         );
      },

CMIIW

Thanks,


问:
How to add classpath dependencies in build.gradle project?
After the Gradle update, every new project has this type of format in build.gradle (project:"...")

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Now how can I add classpath dependencies here?

答:
Just add a dependencies section/method as shown in the gradle docs:

```<code>dependencies{
    implementation 'group.id:artifact-id:version'
}
</code>```

If a dependency should be available both at compile- and runtime, declare it as implementation (not available for dependents) or api (also available for dependents). See this for more details on the difference between api and implementation.

If it should be available at compile-time only, use compileOnly.

Similarly, you can use runtimeOnly for dependencies that should only be used at runtime.

If a dependency should be available only during tests, add test before it, e.g. testImplementation.

The docs on the Java Library Plugin provide more details on that.

Body:
After the Gradle update, every new project has this type of format in build.gradle (project:"...")

// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Now how can I add classpath dependencies here?

Body:
Just add a dependencies section/method as shown in the gradle docs:

dependencies{
    implementation 'group.id:artifact-id:version'
}

If a dependency should be available both at compile- and runtime, declare it as implementation (not available for dependents) or api (also available for dependents). See this for more details on the difference between api and implementation.

If it should be available at compile-time only, use compileOnly.

Similarly, you can use runtimeOnly for dependencies that should only be used at runtime.

If a dependency should be available only during tests, add test before it, e.g. testImplementation.

The docs on the Java Library Plugin provide more details on that.


问:
How to change date format in a column in .pkl file in python?
I have a file in pickle format that I import to jupyter notebook using:

```<code>news_data = pd.read_pickle('/Users/Final/Data/news_articles cleaned.pickle')
</code>```

Data has two columns as shown in this picture

The Date column is in the format:
Weekday Date Month Year
eg. Monday 3rd January 2011

How can I change this format to:
Year-Month-Date
eg. 2011-01-03 ?

答:
with this script, you can change the date format to what you mentioned:

How can I change this format to: Year-Month-Date eg. 2011-01-03 ?

import pandas as pd
news_data = pd.read_pickle('/Users/Final/Data/news_articles cleaned.pickle')

news_data.Date = pd.to_datetime(news_data.Date)
news_data.Date = news_data.Date.strftime("%Y-%m-%d")
```

The conversion happens where i mentioned news_data.Date.strftime("%Y-%m-%d").

Body:
I have a file in pickle format that I import to jupyter notebook using:

news_data = pd.read_pickle('/Users/Final/Data/news_articles cleaned.pickle')

Data has two columns as shown in this picture

The Date column is in the format:
Weekday Date Month Year
eg. Monday 3rd January 2011

How can I change this format to:
Year-Month-Date
eg. 2011-01-03 ?

Body:
with this script, you can change the date format to what you mentioned:

How can I change this format to: Year-Month-Date eg. 2011-01-03 ?

import pandas as pd
news_data = pd.read_pickle('/Users/Final/Data/news_articles cleaned.pickle')

news_data.Date = pd.to_datetime(news_data.Date)
news_data.Date = news_data.Date.strftime("%Y-%m-%d")

The conversion happens where i mentioned news_data.Date.strftime("%Y-%m-%d").


问:
Update Intelliji Idea Java Console Printed Text (No Refresh)
Is it possible to update the Java consoles already printed text without creating a new altered line?</p>

答:
If you re-runan application, the new output overwrites the contents of
the tab. To preserve the output of an application, even if you re-run
it, pin the output tab.

please visit jetbrains official site for more details.

In order to pin tab right click on the tab in run-tool-window and select pin option. Similarly to unpin right click on the tab and select unpin option.


问:
Vue js - :v-for loop is not iterating through array to create list items
I am struggling to get my v-for loop to create a list based on the size of an array. I thought it was straight forward but am having a hard time figuring out where I've gone wrong. I can only seem to get it to produce the first list item. Any ideas? When I inspect in dev tools I see the following:

.vue:

```<code><template>
    <ul>
        <li :v-for="item in items">item
        </li>
    </ul>

</template>

<script>

export default {

    data(){
        return{
            items: [
                {name: 'item1'},
                {name: 'item2'},
                {name: 'item3'},
                {name: 'item4'},
            ]
        }
    }
}

</script>
</code>```

答:
One observation : The colon (:) is a shorthand for v-bind. Meaning, you are binding a property to the element. But in our case we are going to iterate the array instead of binding any data.

Working Demo :

var vm = new Vue({
  el:"#app",
  data:{
    items: [
      {name: 'item1'},
      {name: 'item2'},
      {name: 'item3'},
      {name: 'item4'},
    ]
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <ul>
      <li v-for="item in items" :key="item.name">
        {{ item.name }}
      </li>
    </ul>
</div></code>```

Body:
I am struggling to get my v-for loop to create a list based on the size of an array. I thought it was straight forward but am having a hard time figuring out where I've gone wrong. I can only seem to get it to produce the first list item. Any ideas? When I inspect in dev tools I see the following:

.vue:

<template>

item

</template>

Body:
One observation : The colon (:) is a shorthand for v-bind. Meaning, you are binding a property to the element. But in our case we are going to iterate the array instead of binding any data.

Working Demo :

var vm = new Vue({
  el:"#app",
  data:{
    items: [
      {name: 'item1'},
      {name: 'item2'},
      {name: 'item3'},
      {name: 'item4'},
    ]
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <ul>
      <li v-for="item in items" :key="item.name">
        {{ item.name }}
      </li>
    </ul>
</div>


问:
I want to have a json response from a controller in mvc (dictionary to json)
I have a dictionary of FormCollection named values and I want to add a FormNumber that is only a string to it like the response below:

```<code>Dictionary<string, string> Values = FC.AllKeys.ToDictionary(k => k, v => FC[v]);

string FormNumber="6";
</code>```

答:
You would need a model class as a dictionary is limited to the Key and Value properties.</p>
```<code>public class Model {
    public Model(int num, Dictionary<string, string> values)
    {
        FormNumber = num;
        Values = values;
    }

    public int FormNumber { get; set; }
    public Dictionary<string, string> Values {get; set;}
}

string FormNumber = "6"
Dictionary<string, string> Values = FC.AllKeys.ToDictionary(k => k, v => FC[v]);

// convert to int as your JSON format is int
int number = int.Parse(FormNumber);

Model model = new Model(number, Values);

string json = JsonSerializer.Serialize(model);
</code>```

Body:
I have a dictionary of FormCollection named values and I want to add a FormNumber that is only a string to it like the response below:

Dictionary<string, string> Values = FC.AllKeys.ToDictionary(k => k, v => FC[v]);

string FormNumber="6";

Body:
You would need a model class as a dictionary is limited to the Key and Value properties.

public class Model {
    public Model(int num, Dictionary<string, string> values)
    {
        FormNumber = num;
        Values = values;
    }

    public int FormNumber { get; set; }
    public Dictionary<string, string> Values {get; set;}
}

string FormNumber = "6"
Dictionary<string, string> Values = FC.AllKeys.ToDictionary(k => k, v => FC[v]);

// convert to int as your JSON format is int
int number = int.Parse(FormNumber);

Model model = new Model(number, Values);

string json = JsonSerializer.Serialize(model);


问:
Is there a way to handle files within google cloud storage?
There are many compressed files inside google cloud storage.

I want to unzip the zipped file, rename it and save it back to another bucket.

I've seen a lot of posts, but I couldn't find a way other than how to download it with gsutil and handle it.

Do you have any other way?

答:
To modify a file, such as unzipping, you must read, modify and then write. This means download, unzip and upload the extracted files.

Use gsutil or another tool, one of the SDKs, or the REST APIs. To unzip a file, use a zip tool or one of the libraries that support zip operations.


问:
How to set dynamically array object to the for loop in javascript when for loop iterates
I need to set my for loop length dynamically.

I have an object array.

After my condition is true, I need to set dynamically objects in my permission array inside for loop.

Heare is my code:

```<code>if (obj[k]===pathData[i]){
         //pathData[i]=order
        for (let l = 0; l <permission[j].pathData[i].statusChange.length; l+=1) {

             }
          }
</code>```

My code is not working...I really need your help.

答:
```<code>var permissionObjKeys = Object.keys(permissions[j])
         for(permissionObjKey of permissionObjKeys){
            permissions[j][permissionObjKey].statusChange.push('new-permission')
         }
</code>```

try this it will work inside the dynamic object present in the permission array.

Body:
I need to set my for loop length dynamically.

I have an object array.

After my condition is true, I need to set dynamically objects in my permission array inside for loop.

Heare is my code:

if (obj[k]===pathData[i]){
         //pathData[i]=order
        for (let l = 0; l <permission[j].pathData[i].statusChange.length; l+=1) {

             }
          }

My code is not working...I really need your help.

Body:
var permissionObjKeys = Object.keys(permissions[j])
         for(permissionObjKey of permissionObjKeys){
            permissions[j][permissionObjKey].statusChange.push('new-permission')
         }

try this it will work inside the dynamic object present in the permission array.


问:
How to send cookies with selenium webdriver?
Every time when I run my test first step is log in and than I get to desire page. If run this test often log in operation takes a lot of time.

How can I pass log in operation?

Using Chrome and Firefox drivers, java language.

答:
Cookies failed to load onto some websites, so, the way I handled this problem was to create a user profile/data folder. My browser then behaves like a regular browser, you wouldn't have to manually store the cookies yourself.

JAVA

```<code>ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=USER_DATA_PATH");
driver = new ChromeDriver(options);
</code>```

Python

```<code>chrome_options = Options()
chrome_options.add_argument(f"user-data-dir={USER_DATA_PATH}")
driver = webdriver.Chrome(options=chrome_options)
</code>```

Body:
Cookies failed to load onto some websites, so, the way I handled this problem was to create a user profile/data folder. My browser then behaves like a regular browser, you wouldn't have to manually store the cookies yourself.

JAVA

ChromeOptions options = new ChromeOptions();
options.addArguments("user-data-dir=USER_DATA_PATH");
driver = new ChromeDriver(options);

Python

chrome_options = Options()
chrome_options.add_argument(f"user-data-dir={USER_DATA_PATH}")
driver = webdriver.Chrome(options=chrome_options)


问:
Android: Retrieve contact name from phone number
I would like to retrieve the name of a contact associated with an incoming telephone number. As I process the incoming number in the broascastreceiver having a String with the name of the incoming caller would help my project greatly.

I would think this involves a query using the sql WHERE clause as a filter, but do I need to sort the contacts? An example or hint would be of great assistance.

答:
For that, we can use the  PhoneLookup provider to get the names or contact details using the mobile number.

Add the permission to AndroidManifest.xml:

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

Add the following custom kotlin method in your activity and call the same with the required mobile number.

```<code>fun getContactNameByPhoneNumber(context: Context, phoneNumber: String): String? {
        var phone = phoneNumber
        if(phoneNumber != null && phoneNumber.length > 0 && phoneNumber[0].equals('+'))
            phone = phoneNumber.substring(3)

        val projection = arrayOf(
            ContactsContract.PhoneLookup.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER
        )
        val cursor = context.contentResolver.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            projection,
            ContactsContract.CommonDataKinds.Phone.NUMBER, null, null
        ) ?: return ""
        for (i in 0 until cursor.count) {
            cursor.moveToPosition(i)
            val nameFieldColumnIndex = cursor
                .getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)
            val phoneFieldColumnIndex = cursor
                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)

            if(phone.equals(cursor.getString(phoneFieldColumnIndex)))
                return cursor.getString(nameFieldColumnIndex)
        }
        return "Unknown"
    }
</code>```

For more: https://developer.android.com/training/contacts-provider/retrieve-names

Body:
For that, we can use the  PhoneLookup provider to get the names or contact details using the mobile number.

Add the permission to AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_CONTACTS"/>

Add the following custom kotlin method in your activity and call the same with the required mobile number.

fun getContactNameByPhoneNumber(context: Context, phoneNumber: String): String? {
        var phone = phoneNumber
        if(phoneNumber != null && phoneNumber.length > 0 && phoneNumber[0].equals('+'))
            phone = phoneNumber.substring(3)

        val projection = arrayOf(
            ContactsContract.PhoneLookup.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER
        )
        val cursor = context.contentResolver.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            projection,
            ContactsContract.CommonDataKinds.Phone.NUMBER, null, null
        ) ?: return ""
        for (i in 0 until cursor.count) {
            cursor.moveToPosition(i)
            val nameFieldColumnIndex = cursor
                .getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)
            val phoneFieldColumnIndex = cursor
                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)

            if(phone.equals(cursor.getString(phoneFieldColumnIndex)))
                return cursor.getString(nameFieldColumnIndex)
        }
        return "Unknown"
    }

For more: https://developer.android.com/training/contacts-provider/retrieve-names


问:
How Can I exclude some files in visual studio finding?
I have a project in asp.net web form  and I want to search all files which contains "~/Products" with ctrl+shift+f but I want to exclude a file which is Server.Transfer("~/Products"). I tried regex but it did not work. How Can I do this with regex or something else?

I tried

*~/Products*;!*Server.Transfer("~/Products")*;
```

答:
If you want to search all files which contains "~/Products" and exclude a file which is Server.Transfer("~/Products").

You can try this regex:

```<code>^((?!Server\.Transfer).)*~/Products((?!Server\.Transfer).)*$
</code>```

Body:
If you want to search all files which contains "~/Products" and exclude a file which is Server.Transfer("~/Products").

You can try this regex:

^((?!Server\.Transfer).)*~/Products((?!Server\.Transfer).)*$


问:
used an API. import and in components>DrinkList.js handleTextShow function not running
In my react program i have made a DrinkList.js in which i show the images of drink. but when i start make it clickable using Onclick and passing a function to display its name in console. error start flooding.

```<code>import React from "react";

// import index from "./src"

const DrinkList = (props) => {
  const handleTextShow = (drinkDetail) => {
    console.log(drinkDetail.strGlass);
  };
  return (
    <>
      {props.drinks.map((drink, index) => (
        <div>
          <img src={drink.strDrinkThumb} alt="drink" width="300" height="300">
            {/* hello */}
            onClick={() => handleTextShow(handleTextShow)}
          </img>
          {/* <h4> {drink.strInstructions} </h4> */}

          {/* <Details /> */}
        </div>
      ))}
    </>
  );
};

export default DrinkList;

</code>```

say strGlass is detail strDrinkThumb is photo.

答:
The problem is that , in handleTextShow function, instead of  passing name of drink to want to console, you're passing handleTextShow function as argument, to solve it replace handleTextShow argument with drink name,</p>
```<code>onClick={() => handleTextShow(drink.name)}
</code>```

Body:
In my react program i have made a DrinkList.js in which i show the images of drink. but when i start make it clickable using Onclick and passing a function to display its name in console. error start flooding.

import React from "react";

// import index from "./src"

const DrinkList = (props) => {
  const handleTextShow = (drinkDetail) => {
    console.log(drinkDetail.strGlass);
  };
  return (
    <>
      {props.drinks.map((drink, index) => (

            {/* hello */}
            onClick={() => handleTextShow(handleTextShow)}

          {/*
 {drink.strInstructions}
 */}

          {/*  */}

      ))}
    </>
  );
};

export default DrinkList;

say strGlass is detail strDrinkThumb is photo.

Body:
The problem is that , in handleTextShow function, instead of  passing name of drink to want to console, you're passing handleTextShow function as argument, to solve it replace handleTextShow argument with drink name,

onClick={() => handleTextShow(drink.name)}


问:
why is git pull request not working and i always get errors?
when i use git pull command I came with an error as below

答:
It seems you are trying to pull from an unknown branch.

You can try pull from master branch

```<code>git pull origin master
</code>```

Or you can pair your local master branch with remote master branch using

```<code>git branch --set-upstream-to=origin/master master
</code>```

After setting upstream, normal "git pull" command will work. You don't have to specify branch name with "git pull".

Body:
It seems you are trying to pull from an unknown branch.

You can try pull from master branch

git pull origin master

Or you can pair your local master branch with remote master branch using

git branch --set-upstream-to=origin/master master

After setting upstream, normal "git pull" command will work. You don't have to specify branch name with "git pull".