问:
Format a databound label event
I have Windows Form application and a label which is databound based on a selection from a DataGridView. What I am trying to do is format the label text (which is filesize in bytes) after a new row in the grid is selected. How do I hook this up ? I tried using TextChanged but my formatting function is called twice, once for when the databound text is added to the label and once again AFTER I have formatted the text to what I want. I can put an if or try catch here to stop it the second time but was hoping there is a better way to do this. Thanks</p>

答:
Don't use the TextChanged event.  Rather, get the Binding instance that is connected to the Label and attach to the Format event on the binding.

Then, when the data changes and updates the label, the Format event will fire, and it is in that event handler where you can set your format in a custom manner (which I assume is not expressible using regular format strings).

OwnerDisplayName: kramed

Title: Format a databound label event

OwnerDisplayName: casperOne


来源: stackexchange

问:
Delphi: TabStop problems of TRadioButton
When TRadioButton has TabStop=True, it's acting very strange.

If you will try to switch focus between many radio buttons on a form using Tab key, you would do it only 1 time per app session. The tabulation is one-way, never returning back to the first radio button. Also when the focus is moving across radio buttons, they becoming "checked" automatically.

Can this behavior be fixed without creating my own component?

I want standard radio buttons to

switch focus cyclically

prevent radio button from checking when the focus comes into it (I want my users to check them using Space key)

答: I have found an interesting article of Craig Stuntz about this problem. As I can see, I'll need to create my own control to solve it. </p>

ContentLicense: CC BY-SA 3.0


问:
Flutter:Build Failed Gradle task assembleDebug failed with exit code 1
FAILURE: Build failed with an exception.

Where:
Build file 'C:\Users\"myUsername"\Desktop\test1\android\app\build.gradle' line: 24

What went wrong:
A problem occurred evaluating project ':app'.

Failed to apply plugin [class 'org.gradle.api.plugins.BasePlugin']
  Could not create service of type OutputFilesRepository using ExecutionGradleServices.createOutputFilesRepository().

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 3m 32s
Finished with error: Gradle task assembleDebug failed with exit code 1

答: Just downgrade your jdk to version 8, it might work. Let me know if it works</p>

ContentLicense: CC BY-SA 4.0


问:
Trouble with storybook in IE11. "WeakSet is not defined"
I have a trouble with running storybook in IE11.
This is the error that I see in IE11 console:

I`m using core-js in babel like that:

```<code>presets: [
    ['@babel/preset-env', {
      modules: false,
      loose: true,
      useBuiltIns: "usage",
      corejs: 2,
      debug: true,
      targets: {
        browsers: [
          'last 2 Chrome versions',
          'last 2 Firefox versions',
          'last 2 Safari versions',
          'last 2 Opera versions',
          'last 2 Edge versions',
          'last 2 iOS versions',
          'last 2 ChromeAndroid versions',
          'IE 11'
        ]
      }
    }],
    '@babel/preset-react'
  ]
</code>```

This is babel-loader in webpack:

```<code>{
  test: /\.jsx?$/,
  include: [resolve(__dirname, 'src')],
  exclude: /node_modules/,
  loader: 'babel-loader'
}
</code>```

Tryed it also with core-js@3.6.1, but I`ve got the same result.

UPD: The translation of error: WeakSet is not defined.

答:
Tried a lot of solutions, but the only thing that worked for me was an old school script src to the above CDN. In your storybook folder, add a file named preview-head.html and add this script link:

```

Body:
I have a trouble with running storybook in IE11.
This is the error that I see in IE11 console:

I`m using core-js in babel like that:

presets: [
    ['@babel/preset-env', {
      modules: false,
      loose: true,
      useBuiltIns: "usage",
      corejs: 2,
      debug: true,
      targets: {
        browsers: [
          'last 2 Chrome versions',
          'last 2 Firefox versions',
          'last 2 Safari versions',
          'last 2 Opera versions',
          'last 2 Edge versions',
          'last 2 iOS versions',
          'last 2 ChromeAndroid versions',
          'IE 11'
        ]
      }
    }],
    '@babel/preset-react'
  ]

This is babel-loader in webpack:

{
  test: /\.jsx?$/,
  include: [resolve(__dirname, 'src')],
  exclude: /node_modules/,
  loader: 'babel-loader'
}

Tryed it also with core-js@3.6.1, but I`ve got the same result.

UPD: The translation of error: WeakSet is not defined.

Body:
Tried a lot of solutions, but the only thing that worked for me was an old school script src to the above CDN. In your storybook folder, add a file named preview-head.html and add this script link:

<script src="https://unpkg.com/@ungap/weakset"></script>


问:
Get first day of week T-SQL
How get first day of week (Monday) where week = 6 and year = 2020 I need get 10.02.2020

eg. week 1 in 2020 is  date from 06.01.2020 - 12.01.2020
week 6 in 2020 is  date from 10.02.2020 - 16.02.2020

答:
The following code will get the date of Monday in the week of a given date regardless of the setting of DateFirst or Language:

```<code>Cast( DateAdd( day, - ( @@DateFirst + DatePart( weekday, Datum ) - 2 ) % 7, Datum ) as Date )
</code>```

An example with sample data:

```<code>with SampleData as (
  select GetDate() - 30 as Datum
  union all
  select DateAdd( day, 1, Datum )
    from SampleData
    where Datum < GetDate() )
select Datum,
  -- 1 = Monday through 7 = Sunday.
  ( @@DateFirst + DatePart( weekday, Datum ) - 2 ) % 7 + 1 as WeekDay,
  -- Date of Monday in the week of the supplied date.
  Cast( DateAdd( day, - ( @@DateFirst + DatePart( weekday, Datum ) - 2 ) % 7, Datum ) as Date ) as Monday
  from SampleData;
</code>```

Title: Get first day of week T-SQL

Body:
The following code will get the date of Monday in the week of a given date regardless of the setting of DateFirst or Language:

Cast( DateAdd( day, - ( @@DateFirst + DatePart( weekday, Datum ) - 2 ) % 7, Datum ) as Date )

An example with sample data:

with SampleData as (
  select GetDate() - 30 as Datum
  union all
  select DateAdd( day, 1, Datum )
    from SampleData
    where Datum < GetDate() )
select Datum,
  -- 1 = Monday through 7 = Sunday.
  ( @@DateFirst + DatePart( weekday, Datum ) - 2 ) % 7 + 1 as WeekDay,
  -- Date of Monday in the week of the supplied date.
  Cast( DateAdd( day, - ( @@DateFirst + DatePart( weekday, Datum ) - 2 ) % 7, Datum ) as Date ) as Monday
  from SampleData;


问:
enable and disable TextView's editable mode
I'm creating an spread sheet app. I use a lot of textView in a table layout as the cells of the spread sheet. I want as the user double tap on a cell(TextView), the cell become editable (just like an editText). also, I need to disable the cell's edit mode after the user tap on another cell. I tried these methods but nothing happened.</p>

```

    private void enableEditMode(TextView cell) {
       cell.setFocusable(true);
       cell.setEnabled(true);
       cell.setClickable(true);
       cell.setFocusableInTouchMode(true);
       cell.setCursorVisible(true);
    }

    private void disableEditMode(TextView cell) {
       cell.setFocusable(false);
       cell.setEnabled(false);
       cell.setClickable(false);
       cell.setFocusableInTouchMode(false);
       cell.setCursorVisible(false);
    }

```

答:
It's easier to make EditText uneditable.

```<code>private void enableEditMode(EditText cell) {
       cell.setFocusable(true);
    }

    private void disableEditMode(EditText cell) {
       cell.setFocusable(false);
    }
</code>```

should work

Body:
I'm creating an spread sheet app. I use a lot of textView in a table layout as the cells of the spread sheet. I want as the user double tap on a cell(TextView), the cell become editable (just like an editText). also, I need to disable the cell's edit mode after the user tap on another cell. I tried these methods but nothing happened.

    private void enableEditMode(TextView cell) {
       cell.setFocusable(true);
       cell.setEnabled(true);
       cell.setClickable(true);
       cell.setFocusableInTouchMode(true);
       cell.setCursorVisible(true);
    }

    private void disableEditMode(TextView cell) {
       cell.setFocusable(false);
       cell.setEnabled(false);
       cell.setClickable(false);
       cell.setFocusableInTouchMode(false);
       cell.setCursorVisible(false);
    }

Body:
It's easier to make EditText uneditable.

private void enableEditMode(EditText cell) {
       cell.setFocusable(true);
    }

    private void disableEditMode(EditText cell) {
       cell.setFocusable(false);
    }

should work


问:
How to load all data's in a MongoDB Collection using mongoose?
i want to load and return all data's in a collection for example all of the users in Users collection ,
i've searched and found User.find() or User.find({}) without any expression or object as input but it throws an error when i program tries to send the result as JSON : TypeError: Converting circular structure to JSON

Route Code :

```<code>router.get('/getAllUser',auth,async(req,res)=>{ let users= User.find(); console.log(users) return res.status(200).send(users); }
</code>```

答:
Try this:

Assume that your collection name is "customers":

```<code>dbo.collection("customers").find({}).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });

</code>```

Hope this wil be helpfull

Body:
i want to load and return all data's in a collection for example all of the users in Users collection ,
i've searched and found User.find() or User.find({}) without any expression or object as input but it throws an error when i program tries to send the result as JSON : TypeError: Converting circular structure to JSON

Route Code :

router.get('/getAllUser',auth,async(req,res)=>{ let users= User.find(); console.log(users) return res.status(200).send(users); }

Body:
Try this:

Assume that your collection name is "customers":

dbo.collection("customers").find({}).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });

Hope this wil be helpfull


问:
Compare size of file and size of byte array of that file
When we convert the file (say - image)
To byteArray how can be approximately compared between them (image file and byteArray) ?

Is there also a way to first convert image file to byteArray and this byteArray has to be written in a text-file..
Again after this read these lines of byteArray from text-file and make byteArray and hence converted to image file...... I'm beginner and just for knowledge purpose i want to know....

答:
You can convert your image to byte array like this.

```<code>  BufferedImage bImage = ImageIO.read(new File("sample.jpg"));
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  ImageIO.write(bImage, "jpg", bos );
  byte [] data = bos.toByteArray();
</code>```

Yes you can directly compare 2 byteArray.

Just do something like

```<code>if (bytearray1.length == bytearray2.length)
   //its same
</code>```

Try this to write the ByteArray in text file

```<code>public void writeToFile(byte[] array)
{
   try
   {
       String path = "/data/data/YOURFILE.txt"; //provide your path here
       File file = new File(path);
       if (!file.exists()) { //just to check if file is actually present
          file.createNewFile();
       }
       FileOutputStream stream = new FileOutputStream(path);
       stream.write(array);
   } catch (FileNotFoundException e1)
   {
      e1.printStackTrace();
   }
}
</code>```

Body:
You can convert your image to byte array like this.

  BufferedImage bImage = ImageIO.read(new File("sample.jpg"));
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  ImageIO.write(bImage, "jpg", bos );
  byte [] data = bos.toByteArray();

Yes you can directly compare 2 byteArray.

Just do something like

if (bytearray1.length == bytearray2.length)
   //its same

Try this to write the ByteArray in text file

public void writeToFile(byte[] array)
{
   try
   {
       String path = "/data/data/YOURFILE.txt"; //provide your path here
       File file = new File(path);
       if (!file.exists()) { //just to check if file is actually present
          file.createNewFile();
       }
       FileOutputStream stream = new FileOutputStream(path);
       stream.write(array);
   } catch (FileNotFoundException e1)
   {
      e1.printStackTrace();
   }
}


问:
Missing Node Methods?
Working with Node 12.16.1 I can't seem to call the createServer method from the http module in IntelliJ. Also, I'm a noob (2nd post on stackoverflow) so I'm sure there is something really basic I'm missing. The first step toward learning from my mistakes is identifying them so your help is appreciated.

I know createServer is no longer used in Express 4, but it still shows as being a current method for the http Node 12.16.1 documentation online:

https://nodejs.org/dist/latest-v12.x/docs/api/http.html
https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_createserver_options_requestlistener

So when I start a file with

```<code>var http = require('http');
</code>```

I figure I should be able to see createServer as an available method when I enter:

```<code>http.
</code>```

I know there are other ways to create a server using express 4 and coding a function, so I'm not trying to figure out how to enable a server. I want to better understand the behavior of modules and methods and installing them. I have run into "missing methods" from node a couple of times and have usually found a work around.

This time I want to better understand the reason I'm not finding the method in my IDE. Is it deprecated? Is there something I need to configure differently? I have tried

```<code>npm install http
</code>```

a couple of times and still don't find the method. The module call is recognized and numerous methods are available. Again I'm a noob and just looking to learn / understand this behavior. Any help is appreciated.

Thanks

答:
With require it won't popup with intellisense, only if you use ES6 import syntax like this. So basically it will work with require too, but with import you can use only those parts which are needed for you. Take a look at here: The difference between "require(x)" and "import x"</p>

```<code>import http, { createServer } from 'http';

http.createServer()
</code>```

Title: Missing Node Methods?

Body:
Working with Node 12.16.1 I can't seem to call the createServer method from the http module in IntelliJ. Also, I'm a noob (2nd post on stackoverflow) so I'm sure there is something really basic I'm missing. The first step toward learning from my mistakes is identifying them so your help is appreciated.

I know createServer is no longer used in Express 4, but it still shows as being a current method for the http Node 12.16.1 documentation online:

https://nodejs.org/dist/latest-v12.x/docs/api/http.html
https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_createserver_options_requestlistener

So when I start a file with

var http = require('http');

I figure I should be able to see createServer as an available method when I enter:

http.

I know there are other ways to create a server using express 4 and coding a function, so I'm not trying to figure out how to enable a server. I want to better understand the behavior of modules and methods and installing them. I have run into "missing methods" from node a couple of times and have usually found a work around.

This time I want to better understand the reason I'm not finding the method in my IDE. Is it deprecated? Is there something I need to configure differently? I have tried

npm install http

a couple of times and still don't find the method. The module call is recognized and numerous methods are available. Again I'm a noob and just looking to learn / understand this behavior. Any help is appreciated.

Thanks

Body:
With require it won't popup with intellisense, only if you use ES6 import syntax like this. So basically it will work with require too, but with import you can use only those parts which are needed for you. Take a look at here: The difference between "require(x)" and "import x"

import http, { createServer } from 'http';

http.createServer()


问:
How to use CMake to get command line output as an argument?
I'm using CMake to build linux module mode, so I'm retrieving header files on ubuntu, currently I'm running ubuntu in docker and it has:

```<code>/lib/modules/4.15.0-76-generic
</code>```

Well, several days later if I build a new image, it will become updated value:

```<code>/lib/modules/4.15.0-78-generic
</code>```

So this number is changing, but there's only one directory under /lib/module, and it's not 'uname -a' output.

```<code>Linux 0a08e87c0a18 4.15.0-50-generic
</code>```

So I wish to know if there's a convenient way in CMake just like shell ls /lib/module, and then I can use command line output as a parameter for header/library root directory?

Thanks a lot.

答:
You can use CMake's file(GLOB ...) command to list the contents (files and sub-directories) within a particular directory. If the /lib/modules directory only contains one sub-directory (and no files), you could do something like this:

```<code>file(GLOB MY_VERSIONED_DIR /lib/modules/*)
</code>```

You can now use the ${MY_VERSIONED_DIR} variable elsewhere in your CMake code, as it will be populated with the sub-directory path, for example:

```<code>/lib/modules/4.15.0-78-generic
</code>```

You could also use CMake's execute_process() command, which runs commands in a child process during CMake configure-time. Use the OUTPUT_VARIABLE argument to capture the output of your command:

```<code>if(UNIX)
    execute_process(
        COMMAND ls /lib/modules
        OUTPUT_VARIABLE MY_VERSIONED_DIR
    )
endif()
</code>```

Body:
I'm using CMake to build linux module mode, so I'm retrieving header files on ubuntu, currently I'm running ubuntu in docker and it has:

/lib/modules/4.15.0-76-generic

Well, several days later if I build a new image, it will become updated value:

/lib/modules/4.15.0-78-generic

So this number is changing, but there's only one directory under /lib/module, and it's not 'uname -a' output.

Linux 0a08e87c0a18 4.15.0-50-generic

So I wish to know if there's a convenient way in CMake just like shell ls /lib/module, and then I can use command line output as a parameter for header/library root directory?

Thanks a lot.

Body:
You can use CMake's file(GLOB ...) command to list the contents (files and sub-directories) within a particular directory. If the /lib/modules directory only contains one sub-directory (and no files), you could do something like this:

file(GLOB MY_VERSIONED_DIR /lib/modules/*)

You can now use the ${MY_VERSIONED_DIR} variable elsewhere in your CMake code, as it will be populated with the sub-directory path, for example:

/lib/modules/4.15.0-78-generic

You could also use CMake's execute_process() command, which runs commands in a child process during CMake configure-time. Use the OUTPUT_VARIABLE argument to capture the output of your command:

if(UNIX)
    execute_process(
        COMMAND ls /lib/modules
        OUTPUT_VARIABLE MY_VERSIONED_DIR
    )
endif()


问:
iPhone, Core Data and JSON
I have a web site with an API which publishes the information using JSON.  I can access this API fine, but I would really like to store the information in an iPhone application using Core Data.  Is there a way to hook the Persistent Store to the JSON API so rather than having to keep them in sync using some algorithm I can just use the web site as the back end for Core Data.

I hope that is clear.

答: There is a lib that does JSON => Core Data synchronization : https://github.com/sixdegrees/lidenbrock</p>

ContentLicense: CC BY-SA 2.5

Title: iPhone, Core Data and JSON


问:
Pandas how to replace multiple columns of str% to float number?
```<code>          A        B         C       D        E      F
0    CEKAPE   23.60%   117.374   0.53%    0.11%    <2%
1    HYTFFZ   25.32%   116.250   1.88%    0.38%     5%
</code>```

The df has several columns that contain percetage numbers as string type. This code only process one column at a time. df['D'] = df['D'].str.strip('%').astype(float) / 100 How to write the code while dozens of cloumns need to be processed?

```<code>          A        B         C        D        E      F
0    CEKAPE   0.2360   117.374   0.0053   0.0011    <2%
1    HYTFFZ   0.2532   116.250   0.0188   0.0038   0.05
</code>```

答:
Use pd.to_numeric with errors = coerce and DataFrame.stack + DataFrame.unstack
avoiding having to use apply:

```<code>new_df = (pd.to_numeric(df.replace('%','',regex = True).stack(),
                        errors = 'coerce')
            .div(100)
            .unstack()
            .fillna(df))
print(new_df)
        A       B        C       D       E     F
0  CEKAPE   0.236  1.17374  0.0053  0.0011   <2%
1  HYTFFZ  0.2532   1.1625  0.0188  0.0038  0.05
</code>```

or dropna = False and Series.str.replace

```<code>new_df = (pd.to_numeric(df.stack(dropna = False).str.replace('%',''),
                        errors = 'coerce')
            .div(100)
            .unstack()
            .fillna(df)
         )
</code>```

Body:
          A        B         C       D        E      F
0    CEKAPE   23.60%   117.374   0.53%    0.11%    <2%
1    HYTFFZ   25.32%   116.250   1.88%    0.38%     5%

The df has several columns that contain percetage numbers as string type. This code only process one column at a time. df['D'] = df['D'].str.strip('%').astype(float) / 100 How to write the code while dozens of cloumns need to be processed?

          A        B         C        D        E      F
0    CEKAPE   0.2360   117.374   0.0053   0.0011    <2%
1    HYTFFZ   0.2532   116.250   0.0188   0.0038   0.05

Body:
Use pd.to_numeric with errors = coerce and DataFrame.stack + DataFrame.unstack
avoiding having to use apply:

new_df = (pd.to_numeric(df.replace('%','',regex = True).stack(),
                        errors = 'coerce')
            .div(100)
            .unstack()
            .fillna(df))
print(new_df)
        A       B        C       D       E     F
0  CEKAPE   0.236  1.17374  0.0053  0.0011   <2%
1  HYTFFZ  0.2532   1.1625  0.0188  0.0038  0.05

or dropna = False and Series.str.replace

new_df = (pd.to_numeric(df.stack(dropna = False).str.replace('%',''),
                        errors = 'coerce')
            .div(100)
            .unstack()
            .fillna(df)
         )


问:
Store variables entered in tkinter form
I am creating a Tkinter-based form where I want to store each item that the user types in as a separate variable. I understand how to generate the form, but I am lost on how to handle the program after the user presses the Enter button. I really just need everything stored as a string.

```<code>from tkinter import *
import pandas as pd

fields = ('Event', 'Event Folder', 'Session', 'Date: (MM/DD/YYYY)', 'StartTime: 24HR(HH:MM)', 'EndTime: 24HR(HH:MM)')

def saveVars(entries):
    locals().update(entries)
    return

def makeform(root, fields):
   entries = {}
   for field in fields:
      row = Frame(root)
      lab = Label(row, width=22, text=field+": ", anchor='w')
      ent = Entry(row)
      ent.insert(0,"")
      row.pack(side = TOP, fill = X, padx = 5 , pady = 5)
      lab.pack(side = LEFT)
      ent.pack(side = RIGHT, expand = YES, fill = X)
      entries[field] = ent
   return entries

if __name__ == '__main__':
   root = Tk()
   ents = makeform(root, fields)
   b1 = Button(root, text = 'Enter', command = lambda e = ents: saveVars(e))
   b1.pack(side = LEFT, padx = 5, pady = 5)
   root.mainloop()
</code>```

答:
What you need to do is build a function that does something with your entry fields. That said you may want to change up you code a little bit to make this easier. Instead of building your labels and entry fields in a function build them in the global namespace and then store the entry fields in a list.

```<code>import tkinter as tk

fields = ('Event', 'Event Folder', 'Session', 'Date: (MM/DD/YYYY)',
          'StartTime: 24HR(HH:MM)', 'EndTime: 24HR(HH:MM)')

def do_something_with_entries():
    for ndex, entry in enumerate(entry_list):
        print(fields[ndex], ': ', entry.get())

if __name__ == '__main__':
    root = tk.Tk()
    entry_list = []
    for field in fields:
        row = tk.Frame(root)
        lab = tk.Label(row, width=22, text=field + ": ", anchor='w')
        ent = tk.Entry(row)
        entry_list.append(ent)
        row.pack(side='top', fill='x', padx=5, pady=5)
        lab.pack(side='left')
        ent.pack(side='right', expand='yes', fill='x')

    tk.Button(root, text='Enter', command=do_something_with_entries).pack(side='left', padx=5, pady=5)
    root.mainloop()
</code>```

Results:

Here is an example using pandas:

```<code>import tkinter as tk
import pandas as pd

fields = ['Event', 'Event Folder', 'Session', 'Date: (MM/DD/YYYY)', 'StartTime: 24HR(HH:MM)', 'EndTime: 24HR(HH:MM)']
df = pd.DataFrame(columns=fields)

def do_something_with_entries():
    global df
    stored_values = []
    for ndex, entry in enumerate(entry_list):
        stored_values.append(entry.get())

    series = pd.Series(stored_values, index=fields)
    df = df.append(series, ignore_index=True)

if __name__ == '__main__':
    root = tk.Tk()
    entry_list = []
    for field in fields:
        row = tk.Frame(root)
        lab = tk.Label(row, width=22, text=field + ": ", anchor='w')
        ent = tk.Entry(row)
        entry_list.append(ent)
        row.pack(side='top', fill='x', padx=5, pady=5)
        lab.pack(side='left')
        ent.pack(side='right', expand='yes', fill='x')

    tk.Button(root, text='Enter', command=do_something_with_entries).pack(side='left', padx=5, pady=5)
    root.mainloop()
</code>```

Title: Store variables entered in tkinter form

Body:
I am creating a Tkinter-based form where I want to store each item that the user types in as a separate variable. I understand how to generate the form, but I am lost on how to handle the program after the user presses the Enter button. I really just need everything stored as a string.

from tkinter import *
import pandas as pd

fields = ('Event', 'Event Folder', 'Session', 'Date: (MM/DD/YYYY)', 'StartTime: 24HR(HH:MM)', 'EndTime: 24HR(HH:MM)')

def saveVars(entries):
    locals().update(entries)
    return

def makeform(root, fields):
   entries = {}
   for field in fields:
      row = Frame(root)
      lab = Label(row, width=22, text=field+": ", anchor='w')
      ent = Entry(row)
      ent.insert(0,"")
      row.pack(side = TOP, fill = X, padx = 5 , pady = 5)
      lab.pack(side = LEFT)
      ent.pack(side = RIGHT, expand = YES, fill = X)
      entries[field] = ent
   return entries

if __name__ == '__main__':
   root = Tk()
   ents = makeform(root, fields)
   b1 = Button(root, text = 'Enter', command = lambda e = ents: saveVars(e))
   b1.pack(side = LEFT, padx = 5, pady = 5)
   root.mainloop()

Body:
What you need to do is build a function that does something with your entry fields. That said you may want to change up you code a little bit to make this easier. Instead of building your labels and entry fields in a function build them in the global namespace and then store the entry fields in a list.

import tkinter as tk

fields = ('Event', 'Event Folder', 'Session', 'Date: (MM/DD/YYYY)',
          'StartTime: 24HR(HH:MM)', 'EndTime: 24HR(HH:MM)')

def do_something_with_entries():
    for ndex, entry in enumerate(entry_list):
        print(fields[ndex], ': ', entry.get())

if __name__ == '__main__':
    root = tk.Tk()
    entry_list = []
    for field in fields:
        row = tk.Frame(root)
        lab = tk.Label(row, width=22, text=field + ": ", anchor='w')
        ent = tk.Entry(row)
        entry_list.append(ent)
        row.pack(side='top', fill='x', padx=5, pady=5)
        lab.pack(side='left')
        ent.pack(side='right', expand='yes', fill='x')

    tk.Button(root, text='Enter', command=do_something_with_entries).pack(side='left', padx=5, pady=5)
    root.mainloop()

Results:

Here is an example using pandas:

import tkinter as tk
import pandas as pd

fields = ['Event', 'Event Folder', 'Session', 'Date: (MM/DD/YYYY)', 'StartTime: 24HR(HH:MM)', 'EndTime: 24HR(HH:MM)']
df = pd.DataFrame(columns=fields)

def do_something_with_entries():
    global df
    stored_values = []
    for ndex, entry in enumerate(entry_list):
        stored_values.append(entry.get())

    series = pd.Series(stored_values, index=fields)
    df = df.append(series, ignore_index=True)

if __name__ == '__main__':
    root = tk.Tk()
    entry_list = []
    for field in fields:
        row = tk.Frame(root)
        lab = tk.Label(row, width=22, text=field + ": ", anchor='w')
        ent = tk.Entry(row)
        entry_list.append(ent)
        row.pack(side='top', fill='x', padx=5, pady=5)
        lab.pack(side='left')
        ent.pack(side='right', expand='yes', fill='x')

    tk.Button(root, text='Enter', command=do_something_with_entries).pack(side='left', padx=5, pady=5)
    root.mainloop()


问:
How to test admin change views?
I got a rather complex admin change view for my Django model.

There is a lot of resources about how to test the admin list views (e.g. here), but not for the change view.

How can I create a test cases for it?

答:
Here's a version that's more flexible to other models based off of Erik's answer.</p>
```<code>from django.contrib.auth.models import User, Group
from django.test import TestCase, Client
from django.urls import reverse

def get_admin_change_view_url(obj: object) -> str:
    return reverse(
        'admin:{}_{}_change'.format(
            obj._meta.app_label,
            type(obj).__name__.lower()
        ),
        args=(obj.pk,)
    )

class BaseAdminTestCaseMixin:
    def setUp(self):
        self.client = Client()
        user = User.objects.create_superuser(
            username='superuser', password='secret', email='admin@example.com'
        )
        self.c.force_login(user)

    def get_instance(self):
        raises NotImplementedError()
        instance, _ = Group.objects.get_or_create(name='Test Group')
        return instance

    def test_change_view_loads_normally(self):
        instance = self.get_instance()
        response = self.client.get(get_admin_change_view_url(instance))
        self.assertEqual(response.status_code, 200)

class TestGroupAdmin(BaseAdminTestCaseMixin, TestCase):
    def get_instance(self):
        instance, _ = Group.objects.get_or_create(name='Test Group')
        return instance
</code>```

Title: How to test admin change views?

Body:
Here's a version that's more flexible to other models based off of Erik's answer.

from django.contrib.auth.models import User, Group
from django.test import TestCase, Client
from django.urls import reverse

def get_admin_change_view_url(obj: object) -> str:
    return reverse(
        'admin:{}_{}_change'.format(
            obj._meta.app_label,
            type(obj).__name__.lower()
        ),
        args=(obj.pk,)
    )

class BaseAdminTestCaseMixin:
    def setUp(self):
        self.client = Client()
        user = User.objects.create_superuser(
            username='superuser', password='secret', email='admin@example.com'
        )
        self.c.force_login(user)

    def get_instance(self):
        raises NotImplementedError()
        instance, _ = Group.objects.get_or_create(name='Test Group')
        return instance

    def test_change_view_loads_normally(self):
        instance = self.get_instance()
        response = self.client.get(get_admin_change_view_url(instance))
        self.assertEqual(response.status_code, 200)

class TestGroupAdmin(BaseAdminTestCaseMixin, TestCase):
    def get_instance(self):
        instance, _ = Group.objects.get_or_create(name='Test Group')
        return instance


问:
Cucumber Length?
I am creating a Cucumber test for a multistep registration process and am a little unsure about the best practice for the Scenario Steps...

There are 4 forms / pages in the registration.  Should I loop through the Given, When & Then 4 times in the one scenario or is there a better way to organise it?

So far, I have got...

```<code>Scenario: Company User
Given I am on the registration page
When I follow "Register as a supplier"
When I fill in the following:
  | user_email | test@test.com |
  | user_password | secret |
  | user_password_confirmation | secret |
And I press "Create login - Proceed to step 2"
Then I should see "Create Company Profile"
When I fill in the following:
  | company_name | Test Company |
  | company_description | Lorem |
  | company_telephone | 01928740436 |
  | company_email | info@agency.com |
And I press "Create company - Proceed to step 3"
Then I should see "Test Company office(s)"
</code>```

答:
I think Andy Waite has given good advice, but rather than generic names like step 1, step2, etc. I would be more descriptive:</p>

```<code>When I register as a supplier with valid information
And I create company profile with valid information
And I ... with valid information
And I ... with valid information
Then I should see "Thank you for registering"
</code>```

Title: Cucumber Length?

Body:
I am creating a Cucumber test for a multistep registration process and am a little unsure about the best practice for the Scenario Steps...

There are 4 forms / pages in the registration.  Should I loop through the Given, When & Then 4 times in the one scenario or is there a better way to organise it?

So far, I have got...

Scenario: Company User
Given I am on the registration page
When I follow "Register as a supplier"
When I fill in the following:
  | user_email | test@test.com |
  | user_password | secret |
  | user_password_confirmation | secret |
And I press "Create login - Proceed to step 2"
Then I should see "Create Company Profile"
When I fill in the following:
  | company_name | Test Company |
  | company_description | Lorem |
  | company_telephone | 01928740436 |
  | company_email | info@agency.com |
And I press "Create company - Proceed to step 3"
Then I should see "Test Company office(s)"

Body:
I think Andy Waite has given good advice, but rather than generic names like step 1, step2, etc. I would be more descriptive:

When I register as a supplier with valid information
And I create company profile with valid information
And I ... with valid information
And I ... with valid information
Then I should see "Thank you for registering"


问:
What does it mean that Android Studio has appended the word "dirty" into my release apk name?
As per the title, I have just built a release apk for my app and Android Studio has appended -dirty.apk to the file name.

So now I have myapp-v1-dirty.apk

What does this mean?

答: Ok, I now realise it's because there are changes that have not been committed at the time that the release apk was built. </p>


问:
Readium js viewer config language
How do i configure the language from readium js viewer to translate the buttons in the audio player.

This is my current configuration:

```<code>    config : {
    'readium_js_viewer/ModuleConfig' : {
        'fonts': fontsArray,
        'useSimpleLoader' : false,
        'epubLibraryPath': undefined,
        'canHandleUrl' : false,
        'canHandleDirectory' : false,
        'workerUrl': undefined,
        'epubReadingSystemUrl': undefined
    }
}
</code>```

答:
Just add
navigator.userLanguage = 'es' or the language that you want

Title: Readium js viewer config language

Body:
How do i configure the language from readium js viewer to translate the buttons in the audio player.

This is my current configuration:

    config : {
    'readium_js_viewer/ModuleConfig' : {
        'fonts': fontsArray,
        'useSimpleLoader' : false,
        'epubLibraryPath': undefined,
        'canHandleUrl' : false,
        'canHandleDirectory' : false,
        'workerUrl': undefined,
        'epubReadingSystemUrl': undefined
    }
}


问:
Find any negative values in a given set of dataframes and replace whole column with np.nan
I have a large dataframe and I want to search 144 of the columns to check if there are any negative values in them. If there is even one negative value in a column, I want to replace the whole column with np.nan. I then want to use the new version of the dataframe for later analysis.

I've tried a varied of methods but can't seem to find one that works. I think this is almost there but I can't seem to find a solution to what I'm trying to do.

```<code>clean_data_df.loc[clean_data_df.cols < 0, cols] = np.nan   #cols is a list of the column names I want to check
null_columns=clean_data_df.columns[clean_data_df.isnull().any(axis=1)]
clean_data_df[null_columns] = np.nan
</code>```

When I run the above code I get the following error: AttributeError: 'DataFrame' object has no attribute 'cols'

Thanks in advance!

答:
Idea is filter only filtered rows by cols by DataFrame.lt and DataFrame.any and then add all another columns filled by False in Series.reindex, last set values by DataFrame.loc, here first : means all rows:

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

cols = ['b','c']
df.loc[:, df[cols].lt(0).any().reindex(df.columns, fill_value=False)] = np.nan
print(df)
   a   b  c
0  a NaN  1
1  b NaN  2
2  c NaN  3
</code>```

Detail:

```<code>print(df[cols].lt(0).any())
b     True
c    False
dtype: bool

print (df[cols].lt(0).any().reindex(df.columns, fill_value=False))
a    False
b     True
c    False
dtype: bool
</code>```

Body:
I have a large dataframe and I want to search 144 of the columns to check if there are any negative values in them. If there is even one negative value in a column, I want to replace the whole column with np.nan. I then want to use the new version of the dataframe for later analysis.

I've tried a varied of methods but can't seem to find one that works. I think this is almost there but I can't seem to find a solution to what I'm trying to do.

clean_data_df.loc[clean_data_df.cols < 0, cols] = np.nan   #cols is a list of the column names I want to check
null_columns=clean_data_df.columns[clean_data_df.isnull().any(axis=1)]
clean_data_df[null_columns] = np.nan

When I run the above code I get the following error: AttributeError: 'DataFrame' object has no attribute 'cols'

Thanks in advance!

Body:
Idea is filter only filtered rows by cols by DataFrame.lt and DataFrame.any and then add all another columns filled by False in Series.reindex, last set values by DataFrame.loc, here first : means all rows:

df = pd.DataFrame({'a':list('abc'), 'b':[-2,-1,-3],'c':[1,2,3]})

cols = ['b','c']
df.loc[:, df[cols].lt(0).any().reindex(df.columns, fill_value=False)] = np.nan
print(df)
   a   b  c
0  a NaN  1
1  b NaN  2
2  c NaN  3

Detail:

print(df[cols].lt(0).any())
b     True
c    False
dtype: bool

print (df[cols].lt(0).any().reindex(df.columns, fill_value=False))
a    False
b     True
c    False
dtype: bool


问:
How to force remounting on React components?
Lets say I have a view component that has a conditional render:

```<code>render(){
    if (this.state.employed) {
        return (
            <div>
                <MyInput ref="job-title" name="job-title" />
            </div>
        );
    } else {
        return (
            <div>
                <MyInput ref="unemployment-reason" name="unemployment-reason" />
                <MyInput ref="unemployment-duration" name="unemployment-duration" />
            </div>
        );
    }
}
</code>```

MyInput looks something like this:

```<code>class MyInput extends React.Component {

    ...

    render(){
        return (
            <div>
                <input name={this.props.name}
                    ref="input"
                    type="text"
                    value={this.props.value || null}
                    onBlur={this.handleBlur.bind(this)}
                    onChange={this.handleTyping.bind(this)} />
            </div>
        );
    }
}
</code>```

Lets say employed is true. Whenever I switch it to false and the other view renders, only unemployment-duration is re-initialized. Also unemployment-reason gets prefilled with the value from job-title (if a value was given before the condition changed).

If I change the markup in the second rendering routine to something like this:

```<code>render(){
    if (this.state.employed) {
        return (
            <div>
                <MyInput ref="job-title" name="job-title" />
            </div>
        );
    } else {
        return (
            <div>
                <span>Diff me!</span>
                <MyInput ref="unemployment-reason" name="unemployment-reason" />
                <MyInput ref="unemployment-duration" name="unemployment-duration" />
            </div>
        );
    }
}
</code>```

It seems like everything works fine. Looks like React just fails to diff 'job-title' and 'unemployment-reason'.

Please tell me what I'm doing wrong...

答:
I'm working on Crud for my app. This is how I did it Got Reactstrap as my dependency.

```<code>import React, { useState, setState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import firebase from 'firebase';
// import { LifeCrud } from '../CRUD/Crud';
import { Row, Card, Col, Button } from 'reactstrap';
import InsuranceActionInput from '../CRUD/InsuranceActionInput';

const LifeActionCreate = () => {
  let [newLifeActionLabel, setNewLifeActionLabel] = React.useState();

  const onCreate = e => {
    const db = firebase.firestore();

    db.collection('actions').add({
      label: newLifeActionLabel
    });
    alert('New Life Insurance Added');
    setNewLifeActionLabel('');
  };

  return (
    <Card style={{ padding: '15px' }}>
      <form onSubmit={onCreate}>
        <label>Name</label>
        <input
          value={newLifeActionLabel}
          onChange={e => {
            setNewLifeActionLabel(e.target.value);
          }}
          placeholder={'Name'}
        />

        <Button onClick={onCreate}>Create</Button>
      </form>
    </Card>
  );
};
</code>```

Some React Hooks in there

Body:
Lets say I have a view component that has a conditional render:

render(){
    if (this.state.employed) {
        return (

                <MyInput ref="job-title" name="job-title" />

        );
    } else {
        return (

                <MyInput ref="unemployment-reason" name="unemployment-reason" />
                <MyInput ref="unemployment-duration" name="unemployment-duration" />

        );
    }
}

MyInput looks something like this:

class MyInput extends React.Component {

    ...

    render(){
        return (

                <input name={this.props.name}
                    ref="input"
                    type="text"
                    value={this.props.value || null}
                    onBlur={this.handleBlur.bind(this)}
                    onChange={this.handleTyping.bind(this)} />

        );
    }
}

Lets say employed is true. Whenever I switch it to false and the other view renders, only unemployment-duration is re-initialized. Also unemployment-reason gets prefilled with the value from job-title (if a value was given before the condition changed).

If I change the markup in the second rendering routine to something like this:

render(){
    if (this.state.employed) {
        return (

                <MyInput ref="job-title" name="job-title" />

        );
    } else {
        return (

                Diff me!
                <MyInput ref="unemployment-reason" name="unemployment-reason" />
                <MyInput ref="unemployment-duration" name="unemployment-duration" />

        );
    }
}

It seems like everything works fine. Looks like React just fails to diff 'job-title' and 'unemployment-reason'.

Please tell me what I'm doing wrong...

Body:
I'm working on Crud for my app. This is how I did it Got Reactstrap as my dependency.

import React, { useState, setState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import firebase from 'firebase';
// import { LifeCrud } from '../CRUD/Crud';
import { Row, Card, Col, Button } from 'reactstrap';
import InsuranceActionInput from '../CRUD/InsuranceActionInput';

const LifeActionCreate = () => {
  let [newLifeActionLabel, setNewLifeActionLabel] = React.useState();

  const onCreate = e => {
    const db = firebase.firestore();

    db.collection('actions').add({
      label: newLifeActionLabel
    });
    alert('New Life Insurance Added');
    setNewLifeActionLabel('');
  };

  return (
    <Card style={{ padding: '15px' }}>
      <form onSubmit={onCreate}>
        <label>Name</label>
        <input
          value={newLifeActionLabel}
          onChange={e => {
            setNewLifeActionLabel(e.target.value);
          }}
          placeholder={'Name'}
        />

        <Button onClick={onCreate}>Create</Button>
      </form>
    </Card>
  );
};

Some React Hooks in there


问:
Security benchmarks for google cloud
Do we have any open source security benchmarks for Google cloud apart from CIS benchmarks?
Generally how pen-testing is done for Cloud infrastructure?</p>

答:
I don't know of any other open source benchmark, but according to security compliance doc the certifications and the compliance standards for GCP are ISO/IEC 27001, HIPAA, FedRAMP, SOC 1.

About the pen testing, according to this other doc, to do a pen test, you are not required to contact Google to begin testing. But it's needed to stick to the Acceptable Use Policy and the Terms of Service and only affect your own projects

In case its useful, there is also a white paper with more info

Title: Security benchmarks for google cloud


问:
Docker Jenkins fails to load plugins
I ran docker run jenkins and Jenkins starts correctly but almost all plugins failed to install.

In the log I got errors like this one:

```<code>SEVERE: Failed to install Folders
java.io.IOException: Failed to dynamically deploy this plugin
Caused by: java.io.IOException: Failed to install cloudbees-folder plugin
Caused by: java.io.IOException: Folders Plugin v6.11.1 failed to load.
 - You must update Jenkins from v2.60.3 to v2.138.4 or later to run this plugin.
</code>```

答: My bad, I was using the wrong image - it should be docker pull jenkins/jenkins instead of docker pull jenkins. I found the answer in https://github.com/jenkinsci/docker/issues/787 and https://jenkins.io/blog/2018/12/10/the-official-Docker-image/#official-jenkins-image-to-use-from-docker-hub.

Title: Docker Jenkins fails to load plugins

Body:
I ran docker run jenkins and Jenkins starts correctly but almost all plugins failed to install.

In the log I got errors like this one:

SEVERE: Failed to install Folders
java.io.IOException: Failed to dynamically deploy this plugin
Caused by: java.io.IOException: Failed to install cloudbees-folder plugin
Caused by: java.io.IOException: Folders Plugin v6.11.1 failed to load.
 - You must update Jenkins from v2.60.3 to v2.138.4 or later to run this plugin.


问:
VB delete last element in dynamic array
I need a way to delete the last element in an array when I don't know how big the array is.

Basically I need the VB version of php array_pop, but nothing relevant seems to be appearing in
search results.

答:
VB6:

```<code>redim preserve arr(lbound(arr) to ubound(arr) - 1)
</code>```

VB.NET:

```<code>redim preserve arr(arr.GetUpperBound(0) - 1)
</code>```

Title: VB delete last element in dynamic array

Body:
VB6:

redim preserve arr(lbound(arr) to ubound(arr) - 1)

VB.NET:

redim preserve arr(arr.GetUpperBound(0) - 1)


问:
Read-only monitoring
So im trying to make a read only filesystem monitoring for all my centos servers. At first it seemed easy but then i ran into a conflict. Basicly i made a script to check and zabbix to monitor the outcome but each server has 1 Read only mount that stops me from getting the correct data.

```<code>#!/bin/bash

if cat /proc/mounts | grep RO  | grep "\srw" > /dev/null
    then
            echo 1
    else
            echo 0

fi
</code>```

So this script will check for read only mounts perfectly but the outcome for "cat /proc/mounts" will allways result in "tmpfs /sys/fs/cgroup tmpfs ro,seclabel,nosuid,nodev,noexec,mode=755 0 0" meaning the monitoring will allways tell me i have an readonly mount. Does anyone know how to make script skip this or has even a better way to monitor readonly ?

答:
The cat is useless and you probably want to avoid stringing several greps in a pipeline.

```<code>if awk '/RO/ && !/tmpfs/ && /[ \t]rw/ { print 1; true=1; exit 0}
    END { if(!true) { print 0; exit 1 }}' /proc/mounts
</code>```

The \s escape is a Perl extension which is not generally portable; in Awk and portable grep you can use an explicit character class, or the POSIX symbolic class [[:space:]].

Title: Read-only monitoring

Body:
So im trying to make a read only filesystem monitoring for all my centos servers. At first it seemed easy but then i ran into a conflict. Basicly i made a script to check and zabbix to monitor the outcome but each server has 1 Read only mount that stops me from getting the correct data.

#!/bin/bash

if cat /proc/mounts | grep RO  | grep "\srw" > /dev/null
    then
            echo 1
    else
            echo 0

fi

So this script will check for read only mounts perfectly but the outcome for "cat /proc/mounts" will allways result in "tmpfs /sys/fs/cgroup tmpfs ro,seclabel,nosuid,nodev,noexec,mode=755 0 0" meaning the monitoring will allways tell me i have an readonly mount. Does anyone know how to make script skip this or has even a better way to monitor readonly ?

Body:
The cat is useless and you probably want to avoid stringing several greps in a pipeline.

if awk '/RO/ && !/tmpfs/ && /[ \t]rw/ { print 1; true=1; exit 0}
    END { if(!true) { print 0; exit 1 }}' /proc/mounts

The \s escape is a Perl extension which is not generally portable; in Awk and portable grep you can use an explicit character class, or the POSIX symbolic class [[:space:]].


问:
Access Kentico 12 Alternative URL value
I'm looking for a way to retrieve the alternative URL value for a page in kentico.

Having followed this example to enable Alternative Urls in Kentico 12 SP : https://docs.kentico.com/k12sp/developing-websites/configuring-page-urls-on-mvc-sites/enabling-alternative-urls-for-pages

I'm now stuck trying to access the value for the alternative URL programmatically. Any pointers towards how I may get the value would be greatly appreciated.

答:
```<code>var altLink = new DataQuery()
                .From("CMS_AlternativeURL")
                .Where("AlternativeUrlUrl = @URL", new QueryDataParameters { new
DataParameter("@URL", altURL) })
                .Execute()
                ?.Tables[0]
                ?.AsEnumerable();

            if (altLink != null)
            {
                var altLinkFirst = altLink
                    .ToList()
                    .FirstOrDefault();
                page = new TreeProvider()
                    .SelectSingleDocument(altLinkFirst.Field<int>("AlternativeUrlDocumentID"));
</code>```

So CMS_AlternativeURL is the table with the pairings of alturl and url. I then pass in a string as the alias path, try finding it the treeprovider and if I cannot find it I run this which links the alternative url (the given string) and it will return back pairing with documentId if it exists.

if you're instead trying to get the alternative urls from a treenode, run a dataquery where AlternativeUrlDocumentID = the treennode's documentid.

Title: Access Kentico 12 Alternative URL value

Body:
var altLink = new DataQuery()
                .From("CMS_AlternativeURL")
                .Where("AlternativeUrlUrl = @URL", new QueryDataParameters { new
DataParameter("@URL", altURL) })
                .Execute()
                ?.Tables[0]
                ?.AsEnumerable();

            if (altLink != null)
            {
                var altLinkFirst = altLink
                    .ToList()
                    .FirstOrDefault();
                page = new TreeProvider()
                    .SelectSingleDocument(altLinkFirst.Field<int>("AlternativeUrlDocumentID"));

So CMS_AlternativeURL is the table with the pairings of alturl and url. I then pass in a string as the alias path, try finding it the treeprovider and if I cannot find it I run this which links the alternative url (the given string) and it will return back pairing with documentId if it exists.

if you're instead trying to get the alternative urls from a treenode, run a dataquery where AlternativeUrlDocumentID = the treennode's documentid.


问:
Handling Inbox.items collection - VSTO Outlook Visual Basic
I couldn't find anything regarding a search by conversation ID in the Outlook.Items object collection (corresponding an outlook inbox)

Scenario:
we designed a website that requests an email to be searched in outlook client through a table insert

```<code>insert into Request(UserID,CID,emailDate,outlookAccount)
values ('myUserID','28603734D8EE4316A59257895B1B4A1A','2020-02-11','myOutlookAccount@outlook.com')
</code>```

From out VSTO add-in (visual basic) we are recurrently polling for an eventual request on the mentioned table (Request), once there is a request that belongs to the user, we trigger below's function

```<code>Private Sub SearchEmail(myConversationID As String, emailDate As String, outlookAccount As String)

        For Each account As Outlook.Account In myOutlookInstance.GetNamespace("MAPI").Accounts
            'i lower de displayname in order to match database information
            If (account.DisplayName.ToLower() = outlookAccount) Then
                Dim mailCollection As Outlook.Items = account.DeliveryStore.GetDefaultFolder(OlDefaultFolders.olFolderInbox).Items
                Dim filter As String = "[ConversationID] =" + "'" + myConversationID + "'"
                Dim matchedMail As Outlook.MailItem = mailCollection.Find(filter)
                matchedMail.Display()
                matchedMail.Save()
            End If
        Next
    End Sub
</code>```

However I can't make it work. I'm not quite sure but it might be a possibility that filtering by "ConversationID" field won't work. For that reason, I tried with this alternative (it doesn't work either)

```<code>    Private Sub SearchEmail(myConversationID As String, emailDate As String, outlookAccount As String)

        For Each account As Outlook.Account In myOutlookInstance.GetNamespace("MAPI").Accounts
            Dim mailCollection As Outlook.Items = account.DeliveryStore.GetDefaultFolder(OlDefaultFolders.olFolderInbox).Items
            Dim eval = False
            For Each item As Object In mailCollection
                If (TypeOf item Is Outlook.MailItem) Then
                    Dim mail As Outlook.MailItem = item
                    Dim myCID As String = mail.ConversationID
                    If (eval = False And (myConversationID = myCID)) Then
                        mail.Display()
                        mail.Save()
                        eval = True
                    End If
                End If
            Next
        Next

    End Sub
</code>```

Unfortunately (and avoiding the performance and readability issue), this last alternative raises below's issue:

System.InvalidCastException: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE) at Microsoft.Office.Interop.Outlook._MailItem.get_ConversationID()

Could any one help me with this issue?

答:
After, a while trying to figure out what that issue raised is about, i found that it is raised because i reach a non Outlook.Mailitem object and try to call a method that is not supported for that non Outlook.Mailitem (such as display or save)
However, i couldn't get a deffinitive answer regarding a search / filter by conversationID, my definitive guess is that i'm not allowed to. So the best chance i get is to filter as much as i can with the received Date and iterate comparing the Conversation ID property on each item that it hits with the loop

Find below my Work Around:

```<code>Private Function SearchEmail(myConversationID As String, emailDate As DateTime, outlookAccount As String)

        For Each account As Outlook.Account In myOutlookInstance.GetNamespace("MAPI").Accounts
            If (account.DisplayName.ToLower() = outlookAccount) Then

                Dim mailCollection As Outlook.Items = account.DeliveryStore.GetDefaultFolder(OlDefaultFolders.olFolderInbox).Items
                mailCollection.Sort("[ReceivedTime]", True)
                Dim myRestrictedMailCollection = mailCollection.Restrict("[ReceivedTime] >= " & "'" & emailDate.ToShortDateString() & "'" & " AND [ReceivedTime] <= " & "'" & emailDate.AddDays(1).ToShortDateString() & "'")
                Dim mail As Outlook.MailItem

                For Each item In myRestrictedMailCollection

                    If (TypeOf item Is Outlook.MailItem) Then

                        mail = item

                        If (myConversationID = mail.ConversationID) Then
                            mail.Display()
                            mail.Save()
                            Return True
                        End If

                    End If

                Next

            End If
        Next

        Return False

    End Function

</code>```

Body:
I couldn't find anything regarding a search by conversation ID in the Outlook.Items object collection (corresponding an outlook inbox)

Scenario:
we designed a website that requests an email to be searched in outlook client through a table insert

insert into Request(UserID,CID,emailDate,outlookAccount)
values ('myUserID','28603734D8EE4316A59257895B1B4A1A','2020-02-11','myOutlookAccount@outlook.com')

From out VSTO add-in (visual basic) we are recurrently polling for an eventual request on the mentioned table (Request), once there is a request that belongs to the user, we trigger below's function

Private Sub SearchEmail(myConversationID As String, emailDate As String, outlookAccount As String)

        For Each account As Outlook.Account In myOutlookInstance.GetNamespace("MAPI").Accounts
            'i lower de displayname in order to match database information
            If (account.DisplayName.ToLower() = outlookAccount) Then
                Dim mailCollection As Outlook.Items = account.DeliveryStore.GetDefaultFolder(OlDefaultFolders.olFolderInbox).Items
                Dim filter As String = "[ConversationID] =" + "'" + myConversationID + "'"
                Dim matchedMail As Outlook.MailItem = mailCollection.Find(filter)
                matchedMail.Display()
                matchedMail.Save()
            End If
        Next
    End Sub

However I can't make it work. I'm not quite sure but it might be a possibility that filtering by "ConversationID" field won't work. For that reason, I tried with this alternative (it doesn't work either)

    Private Sub SearchEmail(myConversationID As String, emailDate As String, outlookAccount As String)

        For Each account As Outlook.Account In myOutlookInstance.GetNamespace("MAPI").Accounts
            Dim mailCollection As Outlook.Items = account.DeliveryStore.GetDefaultFolder(OlDefaultFolders.olFolderInbox).Items
            Dim eval = False
            For Each item As Object In mailCollection
                If (TypeOf item Is Outlook.MailItem) Then
                    Dim mail As Outlook.MailItem = item
                    Dim myCID As String = mail.ConversationID
                    If (eval = False And (myConversationID = myCID)) Then
                        mail.Display()
                        mail.Save()
                        eval = True
                    End If
                End If
            Next
        Next

    End Sub

Unfortunately (and avoiding the performance and readability issue), this last alternative raises below's issue:

System.InvalidCastException: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE) at Microsoft.Office.Interop.Outlook._MailItem.get_ConversationID()

Could any one help me with this issue?

Body:
After, a while trying to figure out what that issue raised is about, i found that it is raised because i reach a non Outlook.Mailitem object and try to call a method that is not supported for that non Outlook.Mailitem (such as display or save)
However, i couldn't get a deffinitive answer regarding a search / filter by conversationID, my definitive guess is that i'm not allowed to. So the best chance i get is to filter as much as i can with the received Date and iterate comparing the Conversation ID property on each item that it hits with the loop

Find below my Work Around:

Private Function SearchEmail(myConversationID As String, emailDate As DateTime, outlookAccount As String)

        For Each account As Outlook.Account In myOutlookInstance.GetNamespace("MAPI").Accounts
            If (account.DisplayName.ToLower() = outlookAccount) Then

                Dim mailCollection As Outlook.Items = account.DeliveryStore.GetDefaultFolder(OlDefaultFolders.olFolderInbox).Items
                mailCollection.Sort("[ReceivedTime]", True)
                Dim myRestrictedMailCollection = mailCollection.Restrict("[ReceivedTime] >= " & "'" & emailDate.ToShortDateString() & "'" & " AND [ReceivedTime] <= " & "'" & emailDate.AddDays(1).ToShortDateString() & "'")
                Dim mail As Outlook.MailItem

                For Each item In myRestrictedMailCollection

                    If (TypeOf item Is Outlook.MailItem) Then

                        mail = item

                        If (myConversationID = mail.ConversationID) Then
                            mail.Display()
                            mail.Save()
                            Return True
                        End If

                    End If

                Next

            End If
        Next

        Return False

    End Function


问:
Kivy ScreenManager gives me a black screen
I have been trying to create a ping pong game using kivy. I followed the tutorial on their website and it worked perfectly! However I wanted to add a start screen. I looked on Google and saw that I should use Kivy's Screen Manager. I put it in my code but however when I press the start button it just does nothing and gives me a black screen. I have been trying to figure it out, but I do not see what is wrong! Probably becuase I do not have much experience with Kivy. Here is my code.

main.py

```<code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition

class PingPongPaddle(Widget):

    score = NumericProperty(0)

    def bounce_ball(self, ball):
        if self.collide_widget(ball):
            vx, vy = ball.velocity
            offset = (ball.center_y - self.center_y) / (self.height / 2)
            bounced = Vector(-1 * vx, vy)
            vel = bounced * 1.1
            ball.velocity = vel.x, vel.y + offset
class PingPongBall(Widget):
    #Velocity on x and y axis
    velocity_x = NumericProperty(0)
    velocity_y = NumericProperty(0)

    #So ball.velocity can be used
    velocity = ReferenceListProperty(velocity_x, velocity_y)

    #Moves the ball one step
    def move(self):
        self.pos = Vector(*self.velocity) + self.pos

class PingPongGame(Widget):
    ball = ObjectProperty(None)
    player1 = ObjectProperty(None)
    player2 = ObjectProperty(None)

    def serve_ball(self, vel=(8, 0)):
        self.ball.center = self.center
        self.ball.velocity = vel
    def update(self, dt):
        self.ball.move()
        #Bounce off the paddles
        self.player1.bounce_ball(self.ball)
        self.player2.bounce_ball(self.ball)
        #Bounce off top and bottom
        if (self.ball.y < 0) or (self.ball.top > self.height):
            self.ball.velocity_y *= -1

        #Went off the side
        if self.ball.x < self.x:
            self.player2.score += 1
            self.serve_ball(vel=(4, 0))
        if self.ball.x > self.width:
            self.player1.score += 1
            self.serve_ball(vel=(-4, 0))

    def on_touch_move(self, touch):
        #To sense if screen is touched
        if touch.x < self.width / 3:
            self.player1.center_y = touch.y
        if touch.x > self.width - self.width / 3:
            self.player2.center_y = touch.y

class GameScreen(Screen):
    def play(self):
        global game
        game = PingPongGame()
        game.serve_ball()
        #Runs every 60th of a second
        Clock.schedule_interval(game.update, 1.0/60.0)
        return game

class MainScreen(Screen):
    pass

class PingPongApp(App):
    def build(self):
        screen_manager = ScreenManager(transition=SlideTransition())

        screen_manager.add_widget(MainScreen(name="main"))
        screen_manager.add_widget(GameScreen(name="game"))
        return screen_manager

if __name__ == "__main__":
    PingPongApp().run()
</code>```

pingpong.kv

```<code>#:kivy 1.11.1

<MainScreen>:
    BoxLayout:
        Button:
            text: "Start!"
            on_press: root.manager.current = "game"
<GameScreen>:
    on_enter: self.play()

<PingPongBall>:
    size: 75, 75
    canvas:
        Ellipse:
            pos: self.pos
            size: self.size

<PingPongPaddle>:
    size: 50, 400
    canvas:
        Rectangle:
            pos:self.pos
            size:self.size

<PingPongGame>:
    ball: PingPong_ball
    player1: player_left
    player2: player_right

    canvas:
        Rectangle:
            pos: self.center_x - 5, 0
            size: 20, self.height

    Label:
        font_size: 140
        center_x: root.width / 4
        top: root.top - 50
        text: str(root.player1.score)

    Label:
        font_size: 140
        center_x: root.width * 3 / 4
        top: root.top - 50
        text: str(root.player2.score)

    Label:
        font_size: 35
        center_x: root.width * 6/7
        top: root.top - 500
        text: "by Me"

    PingPongBall:
        id: PingPong_ball
        center: self.parent.center

    PingPongPaddle:
        id: player_left
        x: root.x
        center_y: root.center_y

    PingPongPaddle:
        id: player_right
        x: root.width - self.width
        center_y: root.center_y

</code>```

Thanks in advance!

答:
I fixed it by including this line in the GameScreen's play function.</p>

```<code>self.add_widget(game)
</code>```

Body:
I have been trying to create a ping pong game using kivy. I followed the tutorial on their website and it worked perfectly! However I wanted to add a start screen. I looked on Google and saw that I should use Kivy's Screen Manager. I put it in my code but however when I press the start button it just does nothing and gives me a black screen. I have been trying to figure it out, but I do not see what is wrong! Probably becuase I do not have much experience with Kivy. Here is my code.

main.py

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition

class PingPongPaddle(Widget):

    score = NumericProperty(0)

    def bounce_ball(self, ball):
        if self.collide_widget(ball):
            vx, vy = ball.velocity
            offset = (ball.center_y - self.center_y) / (self.height / 2)
            bounced = Vector(-1 * vx, vy)
            vel = bounced * 1.1
            ball.velocity = vel.x, vel.y + offset
class PingPongBall(Widget):
    #Velocity on x and y axis
    velocity_x = NumericProperty(0)
    velocity_y = NumericProperty(0)

    #So ball.velocity can be used
    velocity = ReferenceListProperty(velocity_x, velocity_y)

    #Moves the ball one step
    def move(self):
        self.pos = Vector(*self.velocity) + self.pos

class PingPongGame(Widget):
    ball = ObjectProperty(None)
    player1 = ObjectProperty(None)
    player2 = ObjectProperty(None)

    def serve_ball(self, vel=(8, 0)):
        self.ball.center = self.center
        self.ball.velocity = vel
    def update(self, dt):
        self.ball.move()
        #Bounce off the paddles
        self.player1.bounce_ball(self.ball)
        self.player2.bounce_ball(self.ball)
        #Bounce off top and bottom
        if (self.ball.y < 0) or (self.ball.top > self.height):
            self.ball.velocity_y *= -1

        #Went off the side
        if self.ball.x < self.x:
            self.player2.score += 1
            self.serve_ball(vel=(4, 0))
        if self.ball.x > self.width:
            self.player1.score += 1
            self.serve_ball(vel=(-4, 0))

    def on_touch_move(self, touch):
        #To sense if screen is touched
        if touch.x < self.width / 3:
            self.player1.center_y = touch.y
        if touch.x > self.width - self.width / 3:
            self.player2.center_y = touch.y

class GameScreen(Screen):
    def play(self):
        global game
        game = PingPongGame()
        game.serve_ball()
        #Runs every 60th of a second
        Clock.schedule_interval(game.update, 1.0/60.0)
        return game

class MainScreen(Screen):
    pass

class PingPongApp(App):
    def build(self):
        screen_manager = ScreenManager(transition=SlideTransition())

        screen_manager.add_widget(MainScreen(name="main"))
        screen_manager.add_widget(GameScreen(name="game"))
        return screen_manager

if __name__ == "__main__":
    PingPongApp().run()

pingpong.kv

#:kivy 1.11.1

<MainScreen>:
    BoxLayout:
        Button:
            text: "Start!"
            on_press: root.manager.current = "game"
<GameScreen>:
    on_enter: self.play()

<PingPongBall>:
    size: 75, 75
    canvas:
        Ellipse:
            pos: self.pos
            size: self.size

<PingPongPaddle>:
    size: 50, 400
    canvas:
        Rectangle:
            pos:self.pos
            size:self.size

<PingPongGame>:
    ball: PingPong_ball
    player1: player_left
    player2: player_right

    canvas:
        Rectangle:
            pos: self.center_x - 5, 0
            size: 20, self.height

    Label:
        font_size: 140
        center_x: root.width / 4
        top: root.top - 50
        text: str(root.player1.score)

    Label:
        font_size: 140
        center_x: root.width * 3 / 4
        top: root.top - 50
        text: str(root.player2.score)

    Label:
        font_size: 35
        center_x: root.width * 6/7
        top: root.top - 500
        text: "by Me"

    PingPongBall:
        id: PingPong_ball
        center: self.parent.center

    PingPongPaddle:
        id: player_left
        x: root.x
        center_y: root.center_y

    PingPongPaddle:
        id: player_right
        x: root.width - self.width
        center_y: root.center_y

Thanks in advance!

Body:
I fixed it by including this line in the GameScreen's play function.

self.add_widget(game)


问:
powershell invoke-restmethod multipart/form-data
I'm currently trying to upload a file to a Webserver by using a REST API. And as mentioned I'm using PowerShell for this. With curl this is no problem. The call looks like this:

```<code>curl -H "Auth_token:"$AUTH_TOKEN -H "Content-Type:multipart/form-data" -X POST -F appInfo='{"name": "test","description": "test"}' -F uploadFile=@/test/test.test https://server/api/
</code>```

But I'm completely helpless when it comes to exporting this to powershell with a Invoke-Restmethod command. As far as I searched it is not possible to use the Invoke-Restmethod for this. https://www.snip2code.com/Snippet/396726/PowerShell-V3-Multipart-formdata-example
But even with that Snipped I'm not smart enough to get this working since I don´t want to upload two files but instead one file and some arguments.

I would be very thankful if someone could get me back on the track with this :o
Thanks!

答:
With PowerShell Core this should work out of the box with the new -Form parameter.

See: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-restmethod?view=powershell-7

```<code>$Uri = 'https://api.contoso.com/v2/profile'
$Form = @{
    firstName  = 'John'
    lastName   = 'Doe'
    email      = 'john.doe@contoso.com'
    avatar     = Get-Item -Path 'c:\Pictures\jdoe.png'
    birthday   = '1980-10-15'
    hobbies    = 'Hiking','Fishing','Jogging'
}
$Result = Invoke-RestMethod -Uri $Uri -Method Post -Form $Form
</code>```

Body:
I'm currently trying to upload a file to a Webserver by using a REST API. And as mentioned I'm using PowerShell for this. With curl this is no problem. The call looks like this:

curl -H "Auth_token:"$AUTH_TOKEN -H "Content-Type:multipart/form-data" -X POST -F appInfo='{"name": "test","description": "test"}' -F uploadFile=@/test/test.test https://server/api/

But I'm completely helpless when it comes to exporting this to powershell with a Invoke-Restmethod command. As far as I searched it is not possible to use the Invoke-Restmethod for this. https://www.snip2code.com/Snippet/396726/PowerShell-V3-Multipart-formdata-example
But even with that Snipped I'm not smart enough to get this working since I don´t want to upload two files but instead one file and some arguments.

I would be very thankful if someone could get me back on the track with this :o
Thanks!

Body:
With PowerShell Core this should work out of the box with the new -Form parameter.

See: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-restmethod?view=powershell-7

$Uri = 'https://api.contoso.com/v2/profile'
$Form = @{
    firstName  = 'John'
    lastName   = 'Doe'
    email      = 'john.doe@contoso.com'
    avatar     = Get-Item -Path 'c:\Pictures\jdoe.png'
    birthday   = '1980-10-15'
    hobbies    = 'Hiking','Fishing','Jogging'
}
$Result = Invoke-RestMethod -Uri $Uri -Method Post -Form $Form


问:
dplyr summarize with subtotals
One of the great things about pivot tables in excel is that they provide subtotals automatically.  First, I would like to know if there is anything already created within dplyr that can accomplish this.  If not, what is the easiest way to achieve it?

In the example below, I show the mean displacement by number of cylinders and carburetors.  For each group of cylinders (4,6,8), I'd like to see the mean displacement for the group (or total displacement, or any other summary statistic).

```<code>library(dplyr)
mtcars %>% group_by(cyl,carb) %>% summarize(mean(disp))

  cyl carb mean(disp)
1   4    1      91.38
2   4    2     116.60
3   6    1     241.50
4   6    4     163.80
5   6    6     145.00
6   8    2     345.50
7   8    3     275.80
8   8    4     405.50
9   8    8     301.00
</code>```

Title: dplyr summarize with subtotals

Body:
One of the great things about pivot tables in excel is that they provide subtotals automatically.  First, I would like to know if there is anything already created within dplyr that can accomplish this.  If not, what is the easiest way to achieve it?

In the example below, I show the mean displacement by number of cylinders and carburetors.  For each group of cylinders (4,6,8), I'd like to see the mean displacement for the group (or total displacement, or any other summary statistic).

library(dplyr)
mtcars %>% group_by(cyl,carb) %>% summarize(mean(disp))

  cyl carb mean(disp)
1   4    1      91.38
2   4    2     116.60
3   6    1     241.50
4   6    4     163.80
5   6    6     145.00
6   8    2     345.50
7   8    3     275.80
8   8    4     405.50
9   8    8     301.00

Body:
With data.table version above v1.11

library(data.table)

cubed <- cube(
  as.data.table(mtcars),
  .(`mean(disp)` = mean(disp)),
  by = c("cyl", "carb")
)
#>     cyl carb mean(disp)
#>  1:   6    4   163.8000
#>  2:   4    1    91.3800
#>  3:   6    1   241.5000
#>  4:   8    2   345.5000
#>  5:   8    4   405.5000
#>  6:   4    2   116.6000
#>  7:   8    3   275.8000
#>  8:   6    6   145.0000
#>  9:   8    8   301.0000
#> 10:   6   NA   183.3143
#> 11:   4   NA   105.1364
#> 12:   8   NA   353.1000
#> 13:  NA    4   308.8200
#> 14:  NA    1   134.2714
#> 15:  NA    2   208.1600
#> 16:  NA    3   275.8000
#> 17:  NA    6   145.0000
#> 18:  NA    8   301.0000
#> 19:  NA   NA   230.7219

res <- dcast(
  cubed,
  cyl ~ carb,
  value.var = "mean(disp)"
)
#>    cyl       NA        1      2     3      4   6   8
#> 1:  NA 230.7219 134.2714 208.16 275.8 308.82 145 301
#> 2:   4 105.1364  91.3800 116.60    NA     NA  NA  NA
#> 3:   6 183.3143 241.5000     NA    NA 163.80 145  NA
#> 4:   8 353.1000       NA 345.50 275.8 405.50  NA 301

Created on 2020-02-20 by the reprex package (v0.3.0)

Source: https://jozef.io/r912-datatable-grouping-sets/

library(kableExtra)

options(knitr.kable.NA = "")

res <- as.data.frame(res)
names(res)[2] <- "overall"
res[1, 1] <- "overall"
x <- kable(res, "html")
x <- kable_styling(x, "striped")
add_header_above(x, c(" " = 1, "carb" = ncol(res) - 1))


问:
How to show the full path for a file found using the find command and given to grep to match a string
I have a lot of config.php files in subdirectories below where I invoke the find command and I want to list the path names of only those for which a grep string match is found. Here is  what I've tried so far.

```<code>find `pwd -P` -name config.php -print -exec grep 'assetBasePath.*cloudfront' {} \;
</code>```

It partially does the job because find does list the paths for all the config.php files it found, and grep prints the matching line in the file if the pattern does indeed match one.

What I want to achieve is an output similar to the above, but where only the pathnames for the files that have a grep match are shown.

答:
Move the -print to the right-hand end so it is "gated" by the outcome of exec:

```<code>find `pwd -P` -name config.php -exec grep 'assetBasePath.*cloudfront' {} \; -print
</code>```

Body:
I have a lot of config.php files in subdirectories below where I invoke the find command and I want to list the path names of only those for which a grep string match is found. Here is  what I've tried so far.

find `pwd -P` -name config.php -print -exec grep 'assetBasePath.*cloudfront' {} \;

It partially does the job because find does list the paths for all the config.php files it found, and grep prints the matching line in the file if the pattern does indeed match one.

What I want to achieve is an output similar to the above, but where only the pathnames for the files that have a grep match are shown.

Body:
Move the -print to the right-hand end so it is "gated" by the outcome of exec:

find `pwd -P` -name config.php -exec grep 'assetBasePath.*cloudfront' {} \; -print


问:
Mysql INNER JOIN after a LEFT OUTER JOIN
I have below query;

```<code>SELECT * FROM product pr
LEFT OUTER JOIN product_field_value pfv ON pfv.product_id = pr.id AND pfv.product_field_id = 64
INNER JOIN product_colour pc ON pc.id = pfv.value
</code>```

Now, not every product has product_field_value corresponding to the :

```<code>ON pfv.product_id = pr.id AND pfv.product_field_id = 64
</code>```

But those that have corresponding rows in the product_field_value table, should inner join into product_colour also.

But as you imagine, INNER JOIN to product_colour table after a LEFT OUTER JOIN to product_field_value table, filters out those that DOESN'T HAVE product_field_value relation.

So I've come up with this solution;

```<code>SELECT * FROM product pr
LEFT OUTER JOIN (SELECT colourPfv.name as name,pfv.product_id as productId,pfv.product_field_id as productFieldId FROM product_field_value pfv
              INNER JOIN product_colour colourPfv on pfv.value = colourPfv.id) colourRel ON colourRel.productId = pr.id AND colourRel.productFieldId = 64
</code>```

And this query returns both those that DOESN'T HAVE corresponding product_field_value and those that HAVE.

But performance for latest query is too slow.

Is there a better way to do this ?

答:
What if you move the logic to the WHERE clause, is performance better?

```<code>SELECT * FROM product pr
LEFT JOIN product_field_value pfv
    ON pfv.product_id = pr.id AND pfv.product_field_id = 64
LEFT JOIN product_colour pc ON pc.id = pfv.value
WHERE pfv.product_id IS NULL OR (pfv.product_id IS NOT NULL AND pc.id IS NOT NULL)
</code>```

Body:
I have below query;

SELECT * FROM product pr
LEFT OUTER JOIN product_field_value pfv ON pfv.product_id = pr.id AND pfv.product_field_id = 64
INNER JOIN product_colour pc ON pc.id = pfv.value

Now, not every product has product_field_value corresponding to the :

ON pfv.product_id = pr.id AND pfv.product_field_id = 64

But those that have corresponding rows in the product_field_value table, should inner join into product_colour also.

But as you imagine, INNER JOIN to product_colour table after a LEFT OUTER JOIN to product_field_value table, filters out those that DOESN'T HAVE product_field_value relation.

So I've come up with this solution;

SELECT * FROM product pr
LEFT OUTER JOIN (SELECT colourPfv.name as name,pfv.product_id as productId,pfv.product_field_id as productFieldId FROM product_field_value pfv
              INNER JOIN product_colour colourPfv on pfv.value = colourPfv.id) colourRel ON colourRel.productId = pr.id AND colourRel.productFieldId = 64

And this query returns both those that DOESN'T HAVE corresponding product_field_value and those that HAVE.

But performance for latest query is too slow.

Is there a better way to do this ?

Body:
What if you move the logic to the WHERE clause, is performance better?

SELECT * FROM product pr
LEFT JOIN product_field_value pfv
    ON pfv.product_id = pr.id AND pfv.product_field_id = 64
LEFT JOIN product_colour pc ON pc.id = pfv.value
WHERE pfv.product_id IS NULL OR (pfv.product_id IS NOT NULL AND pc.id IS NOT NULL)


问:
How to execute mongo commands through shell scripts? (mine does not work)
I am trying to use scripts js in the mongo shell. I am reading a book on the topic. I have tried several options, such as opening the cmd at a specific place at my computer.
I found here the question "How to execute mongo commands through shell scripts?", but nothing seems to work for me. My mongo is working properly and I can enter mongo simply typing mongo at cmd. However, it cannot find the js files.
I am using Windows; anything has an idea what may be happening under the hood?

An example after:

```<code>mongo  demo.js

2020-02-20T11:03:33.098-0300 E  -        [main] file [demo.js] doesn't exist
2020-02-20T11:03:33.098-0300 F  -        [main] failed to load: demo.js
2020-02-20T11:03:33.098-0300 E  -        [main] exiting with code -3
</code>```

答:
Create your my_script.js file with this one command:

```<code>db.testColl.insertOne( { a: "hello" } )
</code>```

Place the script file in your current directory.

1. Run JS Script from OS Command-line:

From OS prompt do this:

```<code>> mongo localhost/testDB my_script.js
</code>```

Once the above command is run, you will see the output as follows (similar, depending upon your MongoDB version and the OS (Windows, in this case)):

```<code>MongoDB shell version v4.2.3
connecting to: mongodb://localhost:27017/testdb?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("456b350f-668f-4389-9901-7c456e2c50fe") }
MongoDB server version: 4.2.3
</code>```

Now, from the Mongo Shell (i.e., do mongo, and then from the mongo prompt):

```<code>mongo > use testDB
mongo > show collections
</code>```

You will see the testColl listed.

```<code>mongo > db.testColl.find()
{ "_id" : ObjectId("5e4ea0d05816162b300b0346"), "a" : "hello" }
</code>```

This is the document created in the testDB database and the collection testColl as per the command in the my_script.js.

2. Run JS Script from Mongo Shell:

Also, you can run the my_script.jsfrom within the Mongo Shell.

```<code>mongo > load("my_script.js")
true
mongo > db.test.find()
{ "_id" : ObjectId("5e4ea0d05816162b300b0346"), "a" : "hello" }
{ "_id" : ObjectId("5e4ea10f276cde8fc5fedec5"), "a" : "hello" }
</code>```

See there are two documents with different _id field values.

NOTE: I think you can run only some commands from the .js file.

3. Another Example:

Create a JS file named script2.js with the following content:

```<code>db.test.find().forEach(printjson)
</code>```

Note the printjson shell method prints a document to the shell output.

```<code>mongo > load("script2.js")
{ "_id" : ObjectId("5e4ea0d05816162b300b0346"), "a" : "hello" }
{ "_id" : ObjectId("5e4ea10f276cde8fc5fedec5"), "a" : "hello" }
</code>```

References:

load()

Print document value in
MongoShell

Body:
I am trying to use scripts js in the mongo shell. I am reading a book on the topic. I have tried several options, such as opening the cmd at a specific place at my computer.
I found here the question "How to execute mongo commands through shell scripts?", but nothing seems to work for me. My mongo is working properly and I can enter mongo simply typing mongo at cmd. However, it cannot find the js files.
I am using Windows; anything has an idea what may be happening under the hood?

An example after:

mongo  demo.js

2020-02-20T11:03:33.098-0300 E  -        [main] file [demo.js] doesn't exist
2020-02-20T11:03:33.098-0300 F  -        [main] failed to load: demo.js
2020-02-20T11:03:33.098-0300 E  -        [main] exiting with code -3

Body:
Create your my_script.js file with this one command:

db.testColl.insertOne( { a: "hello" } )

Place the script file in your current directory.

1. Run JS Script from OS Command-line:

From OS prompt do this:

> mongo localhost/testDB my_script.js

Once the above command is run, you will see the output as follows (similar, depending upon your MongoDB version and the OS (Windows, in this case)):

MongoDB shell version v4.2.3
connecting to: mongodb://localhost:27017/testdb?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("456b350f-668f-4389-9901-7c456e2c50fe") }
MongoDB server version: 4.2.3

Now, from the Mongo Shell (i.e., do mongo, and then from the mongo prompt):

mongo > use testDB
mongo > show collections

You will see the testColl listed.

mongo > db.testColl.find()
{ "_id" : ObjectId("5e4ea0d05816162b300b0346"), "a" : "hello" }

This is the document created in the testDB database and the collection testColl as per the command in the my_script.js.

2. Run JS Script from Mongo Shell:

Also, you can run the my_script.jsfrom within the Mongo Shell.

mongo > load("my_script.js")
true
mongo > db.test.find()
{ "_id" : ObjectId("5e4ea0d05816162b300b0346"), "a" : "hello" }
{ "_id" : ObjectId("5e4ea10f276cde8fc5fedec5"), "a" : "hello" }

See there are two documents with different _id field values.

NOTE: I think you can run only some commands from the .js file.

3. Another Example:

Create a JS file named script2.js with the following content:

db.test.find().forEach(printjson)

Note the printjson shell method prints a document to the shell output.

mongo > load("script2.js")
{ "_id" : ObjectId("5e4ea0d05816162b300b0346"), "a" : "hello" }
{ "_id" : ObjectId("5e4ea10f276cde8fc5fedec5"), "a" : "hello" }

References:

load()

Print document value in
MongoShell


问:
Static function leading to more static functions
I have a class that has a few functions that are useful on their own, which are static. Now these functions depend on other functions that are not useful on their own (but don't interact with class member variables) but are also static, so they are private. Now I have a class with many non-static functions, and couple of static public functions and a few static private functions.

Is this good practice? (should I be making this a community wiki?)

答:
Keep it simple. static function which has nothing to do with the class can be encapsulated either in an inner class or in a new namepsace. e.g

```<code>struct A
{
  struct Util  // can also be put outside in a namespace for others to use
  {
    static void Independent () { }
  };
  static void dependent ();
};
</code>```

Body:
Keep it simple. static function which has nothing to do with the class can be encapsulated either in an inner class or in a new namepsace. e.g

struct A
{
  struct Util  // can also be put outside in a namespace for others to use
  {
    static void Independent () { }
  };
  static void dependent ();
};


问:
excel, check if string contains a character a-z or A-Z
I have a column with unstructured data. I need to detect if the string has an alphabetical character meaning a-z or A-Z. I am not sure how to do this in excel with a formula or other. I am thinking this could be a long countif and sumproduct. Or maybe regex in excel. I will post an attempt try once I try this out more. But I am looking for some advice. While searching online, I could not find a formula to do this. Thanks for your help. Please see below screenshot for sample data.

答:
Using the fact that a to z is 99 to 122 in ASCII, you can use SEARCH, which is case-insensitive:

```<code>=IF(SUMPRODUCT(--ISNUMBER(SEARCH(CHAR(ROW($99:$122)),A2)))>0,"Yes","No")
</code>```

Note that inserting or deleting rows will change the $99:$122 so only use this approach if you can ensure that it remains unchanged.

Body:
Using the fact that a to z is 99 to 122 in ASCII, you can use SEARCH, which is case-insensitive:

=IF(SUMPRODUCT(--ISNUMBER(SEARCH(CHAR(ROW($99:$122)),A2)))>0,"Yes","No")

Note that inserting or deleting rows will change the $99:$122 so only use this approach if you can ensure that it remains unchanged.