问:
How do index.js files work in React component directories?
I just started a new React project and decided to use this pattern, which basically groups files according to their respective component:

```<code>├── actions
│   ├── LaneActions.js
│   └── NoteActions.js
├── components
│   ├── App
│   │   ├── App.jsx
│   │   ├── app.css
│   │   ├── app_test.jsx
│   │   └── index.js
│   ├── Editable
│   │   ├── Editable.jsx
│   │   ├── editable.css
│   │   ├── editable_test.jsx
│   │   └── index.js
...
│   └── index.js
├── constants
│   └── itemTypes.js
├── index.jsx
├── libs
│   ├── alt.js
│   ├── persist.js
│   └── storage.js
├── main.css
└── stores
    ├── LaneStore.js
    └── NoteStore.js
</code>```

What's confusing me is how index.js works in this case. As quoted:

The index.js files are there to provide easy entry points for
  components. Even though they add noise, they simplify imports.

What the article doesn't do is go in depth of what's inside these files. In the case of the Editable component, what would Editable.jsx and index.js ideally look like?

答:
If one is using this directory per component pattern looking for a clean way to organize and access your modules, then the example above with a default export won't work with multiple files, e.g; this structure with a reducer directory:

```<code>── reducers
│   ├── todoReducer.js
│   └── filterReducer.js
│   └── themeReducer.js
│   └── index.js
├── components
    ├── App.js
    ├── app.css
    └── index.js
</code>```

So reducers/index.js would look something like this:

```<code>// index.js
import filterReducer from './filterReducer';
import todoReducer from './todoReducer';
import theme from './themeReducer';

export { filterReducer, todoReducer, theme };
</code>```

...whether originally exported as default or named files in their original files, they are named exports now, and can be used cleanly in App.js as follows:

```<code>// App.js
import { filterReducer, todoReducer, theme } from '../reducers';
</code>```

So we can avoid all this noise:

```<code>import filterReducer from './reducers/filterReducer';
import todoReducer from './reducers/todoReducer';
import theme from './reducers/theme';
</code>```

Body:
I just started a new React project and decided to use this pattern, which basically groups files according to their respective component:

├── actions
│   ├── LaneActions.js
│   └── NoteActions.js
├── components
│   ├── App
│   │   ├── App.jsx
│   │   ├── app.css
│   │   ├── app_test.jsx
│   │   └── index.js
│   ├── Editable
│   │   ├── Editable.jsx
│   │   ├── editable.css
│   │   ├── editable_test.jsx
│   │   └── index.js
...
│   └── index.js
├── constants
│   └── itemTypes.js
├── index.jsx
├── libs
│   ├── alt.js
│   ├── persist.js
│   └── storage.js
├── main.css
└── stores
    ├── LaneStore.js
    └── NoteStore.js

What's confusing me is how index.js works in this case. As quoted:

The index.js files are there to provide easy entry points for
  components. Even though they add noise, they simplify imports.

What the article doesn't do is go in depth of what's inside these files. In the case of the Editable component, what would Editable.jsx and index.js ideally look like?

Body:
If one is using this directory per component pattern looking for a clean way to organize and access your modules, then the example above with a default export won't work with multiple files, e.g; this structure with a reducer directory:

── reducers
│   ├── todoReducer.js
│   └── filterReducer.js
│   └── themeReducer.js
│   └── index.js
├── components
    ├── App.js
    ├── app.css
    └── index.js

So reducers/index.js would look something like this:

// index.js
import filterReducer from './filterReducer';
import todoReducer from './todoReducer';
import theme from './themeReducer';

export { filterReducer, todoReducer, theme };

...whether originally exported as default or named files in their original files, they are named exports now, and can be used cleanly in App.js as follows:

// App.js
import { filterReducer, todoReducer, theme } from '../reducers';

So we can avoid all this noise:

import filterReducer from './reducers/filterReducer';
import todoReducer from './reducers/todoReducer';
import theme from './reducers/theme';


来源: stackexchange

问:
Encode text into WPARAM for win32api.SendMessage()
I'm trying to call win32api.SendMessage() via my Python application (i.e. the sending app).

The receiving app's API states that the format of the message is: ::SendMessage(<app_name>, <msg_name>, (WPARAM) <value>)

However, value is actually a string of between 3 to 4 characters (no spaces).

My Question

What is the correct way of using win32api.SendMessage, especially with regard to value?

Can I simply put the string, as in:
win32api.SendMessage(<app_name>, <msg_name>, "ABC")?

Or do I need to convert the string to WPARAM type (and if so, how do I do that)?

I've been developing in Linux Python and have very little experience with Windows and C++. Would appreciate any assistance.

Thanks in advance!

P.s. In response to comments, the receiving app is actually AmiBroker and the actual message format given in the API documentation is:
::SendMessage( g_hAmiBrokerWnd, WM_USER_STREAMING_UPDATE, (WPARAM) Ticker, (LPARAM) &recentInfoStructureForGivenTicker );
The 'string' I mentioned earlier is 'Ticker', which the author says is a string (char*). I didn't include that initially as I thought the actual message format is not important.

RESEARCH: I read from this that WPARAM is essentially an integer type, and this led me to win32api. Among the many articles I read; none of them helped to answer my questions above (or at least so I think).

答:
[Github]: mhammond/pywin32 - Python for Windows (pywin32) Extensions is a Python wrapper over WINAPIs, and therefore is designed to be Python friendly.

[ActiveState.Docs]: win32api.SendMessage (best doc I could find), is a wrapper over [MS.Docs]: SendMessage function.

The lParam (last) argument is a LONG_PTR, which means that it holds a memory address that can point to anything. Usually this is the one used to pass data like strings.

Since I don't know what message you want to send, I spent some time til I found [MS.Docs]: EM_REPLACESEL message.

code0.py:

#!/usr/bin/env python3

import sys
import win32api
import win32gui
import win32con

is_py2 = sys.version_info.major < 3

if is_py2:
    _input = input
    input = raw_input

def main():
    np_wnd = win32gui.FindWindow(None, "Untitled - Notepad")
    if not np_wnd:
        print("Cound not get Notepad window")
        return
    np_edit_wnd = win32gui.GetWindow(np_wnd, win32con.GW_CHILD)
    if not np_edit_wnd:
        print("Cound not get Notepad child window")
        return
    heading = "After pressing ENTER, "
    #'''
    input("{:s}all text in Notepad will be selected ... ".format(heading))
    # HERE's when the 1st screenshot was taken
    win32api.SendMessage(np_edit_wnd, win32con.EM_SETSEL, 0, -1)
    replaced_text0 = "Replaced\nmultiline text."
    input("{:s}Notepad text will be set (via EM_REPLACESEL) to: \n\"\"\"\n{:s}\n\"\"\" ... ".format(heading, replaced_text0))
    win32api.SendMessage(np_edit_wnd, win32con.EM_REPLACESEL, 0, replaced_text0)  # Regular string
    # HERE's when the 2nd screenshot was taken. It was at the end of the program (at that time), but some stuff was added
    replaced_text1 = "Other\nreplaced\n\nnmultiline text."
    input("\n{:s}Notepad text will be set (via WM_SETTEXT) to: \n\"\"\"\n{:s}\n\"\"\" ... ".format(heading, replaced_text1))
    win32api.SendMessage(np_edit_wnd, win32con.WM_SETTEXT, 0, replaced_text1)
    if not is_py2:
        return
    #'''
    print("\nFor Python 2, also get the text back from Notepad")
    buf_size = 255
    buf = win32gui.PyMakeBuffer(buf_size)
    text_len = win32api.SendMessage(np_edit_wnd, win32con.WM_GETTEXT, buf_size, buf)
    print("    Original text length: {:d}\n    Retrieved text length: {:d}\n    Text: \"\"\"\n{:s}\n    \"\"\"".format(len(replaced_text1), text_len, buf[:text_len]))

if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()
    print("\nDone.")
```

<p><strong>Outcome</strong>:</p>

<ul>
<li><p>Initial state:</p>

<p><img src="https://i.stack.imgur.com/EYal4.png" alt="Img0"></p></li>
<li><p>Final state:</p>

<p><img src="https://i.stack.imgur.com/J6FVE.png" alt="Img1"></p></li>
</ul>

<p><strong>Output</strong>:</p>

<blockquote>
<pre class="lang-bat prettyprint-override"><code>[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q056331657]> "e:\Work\Dev\VEnvs\py_064_02.07.15_test0\Scripts\python.exe" code0.py
Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] on win32

After pressing ENTER, all text in Notepad will be selected ...
After pressing ENTER, Notepad text will be set (via EM_REPLACESEL) to:
"""
Replaced
multiline text.
""" ...

After pressing ENTER, Notepad text will be set (via WM_SETTEXT) to:
"""
Other
replaced

nmultiline text.
""" ...

For Python 2, also get the text from Notepad
    Original text length: 32
    Retrieved text length: 32
    Text: """
Other
replaced

nmultiline text.
    """

Done.
</code>```

As seen, it works with a normal Python string.

Note: My Win user has "super" administrative privileges. For a normal user, some things might not work as expected.

You could also take a look at [SO]: Keyboard event not sent to window with pywin32 (@CristiFati's answer) for handling WM_CHAR like messages, and more important: how to handle child windows.

@EDIT0:

Added:

WM_SETTEXT

WM_GETTEXT (Python 2 only) - to show how to get strings back from SendMessage

But since WM_USER_STREAMING_UPDATE is beyond WM_USER (btw, I didn't see any documentation for it), things might / will not work (per @IInspectable's comment, and also SendMessage's documentation), so additional work (data marshaling) would be required.

@EDIT1:

I've already noticed that you're trying to work with AmiBroker (by Googleing WM_USER_STREAMING_UPDATE).
However, I couldn't find any (official) documentation for that message, that would reveal what the WPARAM and LPARAM arguments are supposed to contain (like: [MS.Docs]: WM_SETTEXT message).

Are you trying to write a plugin (meaning you're in the same process with AmiBroker), or you're simply trying to send messages to it (like I did in my example: Python -> Notepad)?

ContentLicense: CC BY-SA 4.0

Body:
[Github]: mhammond/pywin32 - Python for Windows (pywin32) Extensions is a Python wrapper over WINAPIs, and therefore is designed to be Python friendly.

[ActiveState.Docs]: win32api.SendMessage (best doc I could find), is a wrapper over [MS.Docs]: SendMessage function.

The lParam (last) argument is a LONG_PTR, which means that it holds a memory address that can point to anything. Usually this is the one used to pass data like strings.

Since I don't know what message you want to send, I spent some time til I found [MS.Docs]: EM_REPLACESEL message.

code0.py:

#!/usr/bin/env python3

import sys
import win32api
import win32gui
import win32con

is_py2 = sys.version_info.major < 3

if is_py2:
    _input = input
    input = raw_input

def main():
    np_wnd = win32gui.FindWindow(None, "Untitled - Notepad")
    if not np_wnd:
        print("Cound not get Notepad window")
        return
    np_edit_wnd = win32gui.GetWindow(np_wnd, win32con.GW_CHILD)
    if not np_edit_wnd:
        print("Cound not get Notepad child window")
        return
    heading = "After pressing ENTER, "
    #'''
    input("{:s}all text in Notepad will be selected ... ".format(heading))
    # HERE's when the 1st screenshot was taken
    win32api.SendMessage(np_edit_wnd, win32con.EM_SETSEL, 0, -1)
    replaced_text0 = "Replaced\nmultiline text."
    input("{:s}Notepad text will be set (via EM_REPLACESEL) to: \n\"\"\"\n{:s}\n\"\"\" ... ".format(heading, replaced_text0))
    win32api.SendMessage(np_edit_wnd, win32con.EM_REPLACESEL, 0, replaced_text0)  # Regular string
    # HERE's when the 2nd screenshot was taken. It was at the end of the program (at that time), but some stuff was added
    replaced_text1 = "Other\nreplaced\n\nnmultiline text."
    input("\n{:s}Notepad text will be set (via WM_SETTEXT) to: \n\"\"\"\n{:s}\n\"\"\" ... ".format(heading, replaced_text1))
    win32api.SendMessage(np_edit_wnd, win32con.WM_SETTEXT, 0, replaced_text1)
    if not is_py2:
        return
    #'''
    print("\nFor Python 2, also get the text back from Notepad")
    buf_size = 255
    buf = win32gui.PyMakeBuffer(buf_size)
    text_len = win32api.SendMessage(np_edit_wnd, win32con.WM_GETTEXT, buf_size, buf)
    print("    Original text length: {:d}\n    Retrieved text length: {:d}\n    Text: \"\"\"\n{:s}\n    \"\"\"".format(len(replaced_text1), text_len, buf[:text_len]))

if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()
    print("\nDone.")

Outcome:

Initial state:

Final state:

Output:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q056331657]> "e:\Work\Dev\VEnvs\py_064_02.07.15_test0\Scripts\python.exe" code0.py
Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] on win32

After pressing ENTER, all text in Notepad will be selected ...
After pressing ENTER, Notepad text will be set (via EM_REPLACESEL) to:
"""
Replaced
multiline text.
""" ...

After pressing ENTER, Notepad text will be set (via WM_SETTEXT) to:
"""
Other
replaced

nmultiline text.
""" ...

For Python 2, also get the text from Notepad
    Original text length: 32
    Retrieved text length: 32
    Text: """
Other
replaced

nmultiline text.
    """

Done.

As seen, it works with a normal Python string.

Note: My Win user has "super" administrative privileges. For a normal user, some things might not work as expected.

You could also take a look at [SO]: Keyboard event not sent to window with pywin32 (@CristiFati's answer) for handling WM_CHAR like messages, and more important: how to handle child windows.

@EDIT0:

Added:

WM_SETTEXT

WM_GETTEXT (Python 2 only) - to show how to get strings back from SendMessage

But since WM_USER_STREAMING_UPDATE is beyond WM_USER (btw, I didn't see any documentation for it), things might / will not work (per @IInspectable's comment, and also SendMessage's documentation), so additional work (data marshaling) would be required.

@EDIT1:

I've already noticed that you're trying to work with AmiBroker (by Googleing WM_USER_STREAMING_UPDATE).
However, I couldn't find any (official) documentation for that message, that would reveal what the WPARAM and LPARAM arguments are supposed to contain (like: [MS.Docs]: WM_SETTEXT message).

Are you trying to write a plugin (meaning you're in the same process with AmiBroker), or you're simply trying to send messages to it (like I did in my example: Python -> Notepad)?


问:
Why does the actionscript3.0 class heirachy fail (sometimes)?
All Objects in actionscript3.0 inherit from the Object class, but the actionscript3.0 compiler seems not to be smart enough to understand this.

take a look at the following code:

```<code>package{
   public class TestOne{
      public function TestOne(){
        var t2: TestTwo = new TestTwo();
        trace(t2.toString()); // COMPILE TIME ERROR
        trace((t2 as Object).toString(); // [object TestTwo]

        var t22 : * = new TestTwo();
        trace(t22.toString()); // [object TestTwo]
        trace((t22 as Object).toString(); // [object TestTwo]
      }
   }
}
class TestTwo{}
</code>```

t2.toString() gives a compile time error because the data type t2 does not include toString(). However, t2 does include toString() because it is an object as (t2 as Object).toString() shows. If we do not give the variable a datatype, like t22, then the problem is never encountered. Why cant the actionscript3.0 compiler relize that t2 is both TestTwo and Object?

答:
Class inheritance and prototype inheritance are two different things in AS3. Prototype inheritance is as far as I understand included for backwards compatibility with AS2/AS1, and it's prototype inheritance that's providing the toString() method on the variable that's cast to the Object class in your example. The Object prototype has the toString() method, not the Object class. Since the prototype is not present on your TestTwo class, it doesn't have a toString() method. If the toString() method was supplied via class inheritance instead, your example would compile.

So technically, your statement "All Objects in actionscript3.0 inherit from the Object class" is not entirely correct, because of the difference between prototype inheritance and class inheritance. Prototype inheritance is a somewhat esoteric OO concept found in script languages.

Does anyone know the reason why AS3 is designed like this?

OwnerDisplayName: ForYourOwnGood

ContentLicense: CC BY-SA 2.5

Body:
All Objects in actionscript3.0 inherit from the Object class, but the actionscript3.0 compiler seems not to be smart enough to understand this.

take a look at the following code:

package{
   public class TestOne{
      public function TestOne(){
        var t2: TestTwo = new TestTwo();
        trace(t2.toString()); // COMPILE TIME ERROR
        trace((t2 as Object).toString(); // [object TestTwo]

        var t22 : * = new TestTwo();
        trace(t22.toString()); // [object TestTwo]
        trace((t22 as Object).toString(); // [object TestTwo]
      }
   }
}
class TestTwo{}

t2.toString() gives a compile time error because the data type t2 does not include toString(). However, t2 does include toString() because it is an object as (t2 as Object).toString() shows. If we do not give the variable a datatype, like t22, then the problem is never encountered. Why cant the actionscript3.0 compiler relize that t2 is both TestTwo and Object?

LastEditorDisplayName: ForYourOwnGood

OwnerDisplayName: bzlm


问:
Memset In C Using Sizeof Operator :
Here is a struct :

```<code>typedef struct tag_device_sys
{
    char device[STRING_SIZE];
    int id;
    char category;
} device_sys;
</code>```

For memset, which one should be used from below ?

```<code>memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));
</code>```

or

```<code>memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(dev_sys));
</code>```

What are the differences ?

答: dev_sys is a pointer. sizeof(dev_sys) will just give you size of the pointer for your platform.

ContentLicense: CC BY-SA 3.0

Title: Memset In C Using Sizeof Operator :

Body:
Here is a struct :

typedef struct tag_device_sys
{
    char device[STRING_SIZE];
    int id;
    char category;
} device_sys;

For memset, which one should be used from below ?

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(device_sys));

or

memset(dev_sys, 0, (size_t)NUM_DEVICES * sizeof(dev_sys));

What are the differences ?


问:
How to plot entropart Diversity profiles in ggplot2
I got the diversity profiles of 6 altitudinal bands with DivProfile function of entropart package. Now I want to plot one of the components of the result object, $CommunityAlphaDiversities, using ggplot2

I tried this:

```<code>band.div1 <- as.data.frame(banddivs)
ggplot()+
  geom_line(data=band.div1, aes(x = Order, y = X1700))+
  geom_line(data=band.div1, aes(x = Order, y = X1900))+
  geom_line(data=band.div1, aes(x = Order, y = X2100))+
  geom_line(data=band.div1, aes(x = Order, y = X2300))+
  geom_line(data=band.div1, aes(x = Order, y = X2500))+
  geom_line(data=band.div1, aes(x = Order, y = X1700A))+
  theme(axis.title.x = element_text(size=18), # remove x-axis labels
        axis.title.y = element_text(size=18), # remove y-axis labels
        panel.grid.major = element_blank(),  #remove major-grid labels
        panel.grid.minor = element_blank())  #remove minor-grid labels)
</code>```

But I don't know how to set different colours for each line. My ggplot2 handling is very limited

答:
You need to reshape your data to a long format to have a variable for grouping (to avoid multiple geom_lines) and also use that variable for colour.

```<code>band.div1.long <- reshape(band.div1, direction='long',
        varying=c('X1700', 'X1700A', 'X1900', 'X2100', 'X2300', 'X2500'),
        timevar='var',
        times=c('X1700', 'X1700A', 'X1900', 'X2100', 'X2300', 'X2500'),
        v.names=c('X'),
        idvar='Order')

library(ggplot2)
ggplot()+
  geom_line(data=band.div1.long, aes(x = Order, y = X, group=var, colour=var))+
  theme(axis.title.x = element_text(size=18),
        axis.title.y = element_text(size=18),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank())
</code>```

You can specify the colour manually in each geom but it is not efficient. Look below:

```<code>ggplot()+
  geom_line(data=x, aes(x = Order, y = X1700 , colour="X1700" ))+
  geom_line(data=x, aes(x = Order, y = X1900 , colour="X1900" ))+
  geom_line(data=x, aes(x = Order, y = X2100 , colour="X2100" ))+
  geom_line(data=x, aes(x = Order, y = X2300 , colour="X2300" ))+
  geom_line(data=x, aes(x = Order, y = X2500 , colour="X2500" ))+
  geom_line(data=x, aes(x = Order, y = X1700A, colour="X1700A"))+
  theme(axis.title.x = element_text(size=18),
        axis.title.y = element_text(size=18),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank())
</code>```

Body:
I got the diversity profiles of 6 altitudinal bands with DivProfile function of entropart package. Now I want to plot one of the components of the result object, $CommunityAlphaDiversities, using ggplot2

I tried this:

band.div1 <- as.data.frame(banddivs)
ggplot()+
  geom_line(data=band.div1, aes(x = Order, y = X1700))+
  geom_line(data=band.div1, aes(x = Order, y = X1900))+
  geom_line(data=band.div1, aes(x = Order, y = X2100))+
  geom_line(data=band.div1, aes(x = Order, y = X2300))+
  geom_line(data=band.div1, aes(x = Order, y = X2500))+
  geom_line(data=band.div1, aes(x = Order, y = X1700A))+
  theme(axis.title.x = element_text(size=18), # remove x-axis labels
        axis.title.y = element_text(size=18), # remove y-axis labels
        panel.grid.major = element_blank(),  #remove major-grid labels
        panel.grid.minor = element_blank())  #remove minor-grid labels)

But I don't know how to set different colours for each line. My ggplot2 handling is very limited

Body:
You need to reshape your data to a long format to have a variable for grouping (to avoid multiple geom_lines) and also use that variable for colour.

band.div1.long <- reshape(band.div1, direction='long',
        varying=c('X1700', 'X1700A', 'X1900', 'X2100', 'X2300', 'X2500'),
        timevar='var',
        times=c('X1700', 'X1700A', 'X1900', 'X2100', 'X2300', 'X2500'),
        v.names=c('X'),
        idvar='Order')

library(ggplot2)
ggplot()+
  geom_line(data=band.div1.long, aes(x = Order, y = X, group=var, colour=var))+
  theme(axis.title.x = element_text(size=18),
        axis.title.y = element_text(size=18),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank())

You can specify the colour manually in each geom but it is not efficient. Look below:

ggplot()+
  geom_line(data=x, aes(x = Order, y = X1700 , colour="X1700" ))+
  geom_line(data=x, aes(x = Order, y = X1900 , colour="X1900" ))+
  geom_line(data=x, aes(x = Order, y = X2100 , colour="X2100" ))+
  geom_line(data=x, aes(x = Order, y = X2300 , colour="X2300" ))+
  geom_line(data=x, aes(x = Order, y = X2500 , colour="X2500" ))+
  geom_line(data=x, aes(x = Order, y = X1700A, colour="X1700A"))+
  theme(axis.title.x = element_text(size=18),
        axis.title.y = element_text(size=18),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank())


问:
Failed while installing tfjs-node using macOS and node-gyp rebuild failed
I'm trying to install tfjs-node via npm install @tensorflow/tfjs-node on my mac.

I'm getting following error while trying to installing it.

```<code>Error: node-gyp rebuild failed with: Error: Command failed: node-gyp rebuild
gyp ERR! configure error
gyp ERR! stack Error: Command failed: /Users/ReffasCode/anaconda3/bin/python -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                                ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:294:12)
gyp ERR! stack     at ChildProcess.emit (events.js:189:13)
gyp ERR! stack     at maybeClose (internal/child_process.js:970:16)
gyp ERR! stack     at Socket.stream.socket.on (internal/child_process.js:389:11)
gyp ERR! stack     at Socket.emit (events.js:189:13)
gyp ERR! stack     at Pipe._handle.close (net.js:597:12)
gyp ERR! System Darwin 18.2.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/ReffasCode/Desktop/ip2_ss19/Server/node_modules/@tensorflow/tfjs-node
gyp ERR! node -v v10.15.3
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
</code>```

答:
OK, getting more information from https://github.com/nodejs/node-gyp it seems like node-gyp is not supporting Python version 3.x.x is not supported.

So if you having the same error try to specify which Python version to use:

```<code>npm config set python /usr/bin/python
</code>```

Body:
I'm trying to install tfjs-node via npm install @tensorflow/tfjs-node on my mac.

I'm getting following error while trying to installing it.

Error: node-gyp rebuild failed with: Error: Command failed: node-gyp rebuild
gyp ERR! configure error
gyp ERR! stack Error: Command failed: /Users/ReffasCode/anaconda3/bin/python -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                                ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:294:12)
gyp ERR! stack     at ChildProcess.emit (events.js:189:13)
gyp ERR! stack     at maybeClose (internal/child_process.js:970:16)
gyp ERR! stack     at Socket.stream.socket.on (internal/child_process.js:389:11)
gyp ERR! stack     at Socket.emit (events.js:189:13)
gyp ERR! stack     at Pipe._handle.close (net.js:597:12)
gyp ERR! System Darwin 18.2.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/ReffasCode/Desktop/ip2_ss19/Server/node_modules/@tensorflow/tfjs-node
gyp ERR! node -v v10.15.3
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok

Body:
OK, getting more information from https://github.com/nodejs/node-gyp it seems like node-gyp is not supporting Python version 3.x.x is not supported.

So if you having the same error try to specify which Python version to use:

npm config set python /usr/bin/python


问:
How to update queryset value in django?
I have written a python script in my project. I want to update the value of a field.

Here are my modes

```<code>
class News_Channel(models.Model):
    name = models.TextField(blank=False)
    info = models.TextField(blank=False)
    image = models.FileField()
    website = models.TextField()
    total_star = models.PositiveIntegerField(default=0)
    total_user = models.IntegerField()

    class Meta:
        ordering = ["-id"]

    def __str__(self):
        return self.name

class Count(models.Model):
    userId = models.ForeignKey(User, on_delete=models.CASCADE)
    channelId = models.ForeignKey(News_Channel, on_delete=models.CASCADE)
    rate = models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.channelId.name

    class Meta:
        ordering = ["-id"]
</code>```

This is my python script:

```<code>from feed.models import Count, News_Channel

def run():
    for i in range(1, 11):
        news_channel = Count.objects.filter(channelId=i)
        total_rate = 0
        for rate in news_channel:
            total_rate += rate.rate
        print(total_rate)
        object = News_Channel.objects.filter(id=i)
        print(total_rate)
        print("before",object[0].total_star,total_rate)
        object[0].total_star = total_rate
        print("after", object[0].total_star)
        object.update()

</code>```

After counting the total_rate from the Count table I want to update the total star value in News_Channel table. I am failing to do so and get the data before the update and after the update as zero. Although total_rate has value.

答:
The problem

The reason why this fails is because here object is a QuerySet of News_Channels, yeah that QuerySet might contain exactly one News_Channel, but that is irrelevant.

If you then use object[0] you make a query to the database to fetch the first element and deserialize it into a News_Channel object. Then you set the total_star of that object, but you never save that object. You only call .update() on the entire queryset, resulting in another independent query.

You can fix this with:

```<code>objects = News_Channel.objects.filter(id=i)
<b>object = objects[0]</b>
object.total_star = total_rate
object<b>.save()</b></code>```

Or given you do not need any validation, you can boost performance with:

```<code>News_Channel.objects.filter(id=i).update(total_star=total_rate)</code>```

Updating all News_Channels

If you want to update all News_Channels, you actually better use a Subquery here:

```<code>from django.db.models import OuterRef, Sum, Subquery

subq = Subquery(
    Count.objects.filter(
        channelId=OuterRef('id')
    ).annotate(
        total_rate=Sum('rate')
    ).order_by('channelId').values('total_rate')[:1]
)

News_Channel.objects.update(total_star=subq)</code>```

Title: How to update queryset value in django?

Body:
I have written a python script in my project. I want to update the value of a field.

Here are my modes

class News_Channel(models.Model):
    name = models.TextField(blank=False)
    info = models.TextField(blank=False)
    image = models.FileField()
    website = models.TextField()
    total_star = models.PositiveIntegerField(default=0)
    total_user = models.IntegerField()

    class Meta:
        ordering = ["-id"]

    def __str__(self):
        return self.name

class Count(models.Model):
    userId = models.ForeignKey(User, on_delete=models.CASCADE)
    channelId = models.ForeignKey(News_Channel, on_delete=models.CASCADE)
    rate = models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.channelId.name

    class Meta:
        ordering = ["-id"]

This is my python script:

from feed.models import Count, News_Channel

def run():
    for i in range(1, 11):
        news_channel = Count.objects.filter(channelId=i)
        total_rate = 0
        for rate in news_channel:
            total_rate += rate.rate
        print(total_rate)
        object = News_Channel.objects.filter(id=i)
        print(total_rate)
        print("before",object[0].total_star,total_rate)
        object[0].total_star = total_rate
        print("after", object[0].total_star)
        object.update()

After counting the total_rate from the Count table I want to update the total star value in News_Channel table. I am failing to do so and get the data before the update and after the update as zero. Although total_rate has value.

Body:
The problem

The reason why this fails is because here object is a QuerySet of News_Channels, yeah that QuerySet might contain exactly one News_Channel, but that is irrelevant.

If you then use object[0] you make a query to the database to fetch the first element and deserialize it into a News_Channel object. Then you set the total_star of that object, but you never save that object. You only call .update() on the entire queryset, resulting in another independent query.

You can fix this with:

objects = News_Channel.objects.filter(id=i)
object = objects[0]
object.total_star = total_rate
object.save()

Or given you do not need any validation, you can boost performance with:

News_Channel.objects.filter(id=i).update(total_star=total_rate)

Updating all News_Channels

If you want to update all News_Channels, you actually better use a Subquery here:

from django.db.models import OuterRef, Sum, Subquery

subq = Subquery(
    Count.objects.filter(
        channelId=OuterRef('id')
    ).annotate(
        total_rate=Sum('rate')
    ).order_by('channelId').values('total_rate')[:1]
)

News_Channel.objects.update(total_star=subq)


问:
Java8 lambda for checking two conditions
I have the following code snippet which I would try to change to the lambda function.

```<code>if(catList != null && catList.size() > 0) {
    animalType = AnimalType.CAT;
    HttpEntity<List<?>> request = new HttpEntity<>(catList, headers);
    response = restTemplate.postForObject(apiUrl, request, String.class);
} else if(dogList != null && dogList.size() > 0) {
    animalType = AnimalType.DOG;
} else {
    return;
}
</code>```

Somehow I have written like as shown below, but don't know to incorporate the dogList checking the condition

```<code>Optional.of(catList)
    .map(catList -> {
        ....
    })
    .orElse(return); //<------ THIS IS NOT POSSIBLE
</code>```

Can anyone please help me with this

答:
It is not possible to exit a method using the Optional or any other class without either explicitly invoking return or throwing an exception. Usage of return inside a lambda expression is understood within the scope of the method implemented of the functional interface, hence there is no chance to do as your shown code.

There are basically two ways to achieve the desired behavior and keep Java language compliance.

Use return after obtaining a definitive result from Optional.

Here I might repeat an existing answer, but the best you can do is:

```<code>Optional<MyObject> optional = Optional.of(catList)
    .map(catList -> new HttpEntity<>(catList, headers))
    .map(httpEntity -> restTemplate.postForObject(apiUrl, request, String.class));

if (!optional.isPresent()) { return; }           // here the method execution is terminated
</code>```

Checking against null or an Null Object might be a way to go as well.

Throw an exception using the Optional::orElseThrow allows the method terminates the method and throws an Exception. Unfortunately, it obliges an upper layer with a need to handle it or rethrow).

```<code>MyObject myObject = Optional.of(catList)
    .map(catList -> new HttpEntity<>(catList, headers))
    .map(httpEntity -> restTemplate.postForObject(apiUrl, request, String.class))
    .orElseThrow(MyObjectException::new);        // here the method execution is terminated
</code>```

If the return parameter of the method is not void, the Optional might be used for the return type definition. The null check (or again a Null Object is a way) might be used there is the method called at:

```<code> return Optional.of(catList)
        .map(catList -> new HttpEntity<>(catList, headers))
        .map(httpEntity -> restTemplate.postForObject(apiUrl, request, String.class))
        .orElse(null);
</code>```

Body:
I have the following code snippet which I would try to change to the lambda function.

if(catList != null && catList.size() > 0) {
    animalType = AnimalType.CAT;
    HttpEntity<List<?>> request = new HttpEntity<>(catList, headers);
    response = restTemplate.postForObject(apiUrl, request, String.class);
} else if(dogList != null && dogList.size() > 0) {
    animalType = AnimalType.DOG;
} else {
    return;
}

Somehow I have written like as shown below, but don't know to incorporate the dogList checking the condition

Optional.of(catList)
    .map(catList -> {
        ....
    })
    .orElse(return); //<------ THIS IS NOT POSSIBLE

Can anyone please help me with this

Body:
It is not possible to exit a method using the Optional or any other class without either explicitly invoking return or throwing an exception. Usage of return inside a lambda expression is understood within the scope of the method implemented of the functional interface, hence there is no chance to do as your shown code.

There are basically two ways to achieve the desired behavior and keep Java language compliance.

Use return after obtaining a definitive result from Optional.

Here I might repeat an existing answer, but the best you can do is:

Optional<MyObject> optional = Optional.of(catList)
    .map(catList -> new HttpEntity<>(catList, headers))
    .map(httpEntity -> restTemplate.postForObject(apiUrl, request, String.class));

if (!optional.isPresent()) { return; }           // here the method execution is terminated

Checking against null or an Null Object might be a way to go as well.

Throw an exception using the Optional::orElseThrow allows the method terminates the method and throws an Exception. Unfortunately, it obliges an upper layer with a need to handle it or rethrow).

MyObject myObject = Optional.of(catList)
    .map(catList -> new HttpEntity<>(catList, headers))
    .map(httpEntity -> restTemplate.postForObject(apiUrl, request, String.class))
    .orElseThrow(MyObjectException::new);        // here the method execution is terminated

If the return parameter of the method is not void, the Optional might be used for the return type definition. The null check (or again a Null Object is a way) might be used there is the method called at:

 return Optional.of(catList)
        .map(catList -> new HttpEntity<>(catList, headers))
        .map(httpEntity -> restTemplate.postForObject(apiUrl, request, String.class))
        .orElse(null);


问:
Sorting a set of matrices
I have many images(about 10000). The my goal is make the binary research on a the set the matrixs bidimensional and researching  if there are images duplicate and delete this images. But exist the concept the matrix major another matrix? How i can solve? The alternative is make a research sequential, but is many innefficient.</p>

答:
@Miki's suggestion seemed like a fun exercise, so I created an implementation that you can use.

More on hashing here

```<code>import hashlib, os, cv2
# location of images
path = '.'
# create list that will hold the hashes
all_hashes = []

# get and iterate all image paths
all_files = os.listdir(path)
for f in all_files:
    # check image extension
    name, ext = os.path.splitext(f)
    if ext == '.jpg':
        # open image
        img = cv2.imread(f)
        # hash the image and get hex representation
        hash = hashlib.md5(img).hexdigest()
        # check if hash already exists, if not then add it to the list
        if hash in all_hashes:
            print('Already exists: ' + f)
        else:
            all_hashes.append(hash)
</code>```

Title: Sorting a set of matrices

Body:
@Miki's suggestion seemed like a fun exercise, so I created an implementation that you can use.

More on hashing here

import hashlib, os, cv2
# location of images
path = '.'
# create list that will hold the hashes
all_hashes = []

# get and iterate all image paths
all_files = os.listdir(path)
for f in all_files:
    # check image extension
    name, ext = os.path.splitext(f)
    if ext == '.jpg':
        # open image
        img = cv2.imread(f)
        # hash the image and get hex representation
        hash = hashlib.md5(img).hexdigest()
        # check if hash already exists, if not then add it to the list
        if hash in all_hashes:
            print('Already exists: ' + f)
        else:
            all_hashes.append(hash)


答:
News_Channel.total_star can be calculated by using aggregation

```<code>news_channel_obj.count_set.aggregate(total_star=Sum('rate'))['total_star']
</code>```

You can then either use this in your script:

```<code>object.total_star = object.count_set.aggregate(total_star=Sum('rate'))['total_star']
</code>```

Or if you do not need to cache this value because performance is not an issue, you can remove the total_star field and add it as a property on the News_Channel model

```<code>@property
def total_star(self):
    return self.count_set.aggregate(total_star=Sum('rate'))['total_star']
</code>```

Title: How to update queryset value in django?

Body:
News_Channel.total_star can be calculated by using aggregation

news_channel_obj.count_set.aggregate(total_star=Sum('rate'))['total_star']

You can then either use this in your script:

object.total_star = object.count_set.aggregate(total_star=Sum('rate'))['total_star']

Or if you do not need to cache this value because performance is not an issue, you can remove the total_star field and add it as a property on the News_Channel model

@property
def total_star(self):
    return self.count_set.aggregate(total_star=Sum('rate'))['total_star']


问:
stack translator in formal languages
Can someone explain how a stack translator works ? I think it is mainly used for lexical analysis (i could be very much wrong) . Any additional material or links are welcome ! Thanks ! </p>

答:
I don't think your question is well formed; lexers don't have much need for stacks.  Perhaps you could clarify the context in which the phrase you are using came up, and why you care.

The closest guess I have is "syntax-directed translation", which generally means a translator driven directly by the recognition of syntax phrases (e.g., text generation procedurally attached to grammar rule matches).

Title: stack translator in formal languages


问:
Is it possible to use "WHERE" clause to select all records in SQL Statement?
Good Evening, I am curious if it is possible to make a WHERE-clause in a SQL statement which can show all records?

Below some explanation:

Random SQL Statement (Java)-(JSP example), Normal Situation

```<code>String SqlStatement = "SELECT * FROM table_example WHERE First_Col = '<%=passVar%>' ";
db.query(SqlStatement );
//........
//........
</code>```

What if the passVar is 'ALL', and we need to prompt all the records out when passVar = All? I know I can do it with if-else and check if the passVar is "ALL" then query the without-WHERE statement to make it work..

```<code>**without-WHERE statement (Java)-(JSP example)**
</code>```

```<code>if(<%=passVar%> == "ALL") {
   SqlStatement = "SELECT * FROM table_example";
} else {

   SqlStatement = "SELECT * FROM table_example WHERE First_Col = '<%=passVar%>' ";
}
</code>```

but can I just code one SQL statement to make all the records prompt? Something like below:

(Java)-(JSP example)

```<code>String ShowAll = "";
if(<%=passVar%> == "ALL") {
    ShowAll = *;

} else {
    ShowAll = <%=passVar%>;
}
SqlStatement = "SELECT * FROM table_example WHERE First_Col = ShowAll ";
</code>```

答:
On sqlserver you can make proc:

```<code>create proc select_all_on_null
@a int = null
as
begin
  select * from Records where (@a is null or Record_id=@a )
end
</code>```

When you select be your program:

```<code>make @a in null will select all
</code>```

if i is number there will select row with this id

Body:
Good Evening, I am curious if it is possible to make a WHERE-clause in a SQL statement which can show all records?

Below some explanation:

Random SQL Statement (Java)-(JSP example), Normal Situation

String SqlStatement = "SELECT * FROM table_example WHERE First_Col = '<%=passVar%>' ";
db.query(SqlStatement );
//........
//........

What if the passVar is 'ALL', and we need to prompt all the records out when passVar = All? I know I can do it with if-else and check if the passVar is "ALL" then query the without-WHERE statement to make it work..

**without-WHERE statement (Java)-(JSP example)**

if(<%=passVar%> == "ALL") {
   SqlStatement = "SELECT * FROM table_example";
} else {

   SqlStatement = "SELECT * FROM table_example WHERE First_Col = '<%=passVar%>' ";
}

but can I just code one SQL statement to make all the records prompt? Something like below:

(Java)-(JSP example)

String ShowAll = "";
if(<%=passVar%> == "ALL") {
    ShowAll = *;

} else {
    ShowAll = <%=passVar%>;
}
SqlStatement = "SELECT * FROM table_example WHERE First_Col = ShowAll ";

Body:
On sqlserver you can make proc:

create proc select_all_on_null
@a int = null
as
begin
  select * from Records where (@a is null or Record_id=@a )
end

When you select be your program:

make @a in null will select all

if i is number there will select row with this id


问:
How do I display Google reCAPTCHA v2 in a Chrome Extension browser action?
I'm building a Chrome Extension that interacts with an API that I wish to protect using Google recatcha, as I'm intending for it to be used beyond just the Chrome Extension. The API side is working, correctly verifying a recaptcha response with Google, however, displaying the recatcha widget inside the extension's browser action window is resulting in the following javascript error:

```<code>Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('chrome-extension://pjhcgfibbbmibojnlkgjejaojpokgldl:80') does not match the recipient window's origin ('chrome-extension://pjhcgfibbbmibojnlkgjejaojpokgldl').
</code>```

which is generated in recaptcha_en.js at the line:

```<code>(a.window || ne(a.Tg)).postMessage(JSON.stringify({
        message: c || null ,
        messageType: b
    }), Zj(a.path));
</code>```

The problem seems to be that the value of a.path is chrome-extension://pjhcgfibbbmibojnlkgjejaojpokgldl:80 but I don't know how I can affect this value.

The result of this error is that the recaptcha widget displays a message saying:

Please upgrade to a supported browser to get a reCAPTCHA challenge.

I'm displaying the widget via the auto render method, but have also tried the explicit method which results in the same error. For info, I'm using the following content_security_policy:

```<code>script-src 'self' https://*.google.com https://*.gstatic.com; object-src 'self'
</code>```

Is there any way I can get this to work in my extension? And if not, what is the best alternative method for integrating recaptcha?

答:
In recaptcha v3

manifest.json
"content_security_policy": "script-src 'self' https://.google.com https://.gstatic.com; object-src 'self'"

ADD CHROME EXTENCION ID TO ALLOWED DOMAINS IN RECAPTCHA ADMIN CONSOLE

chrome-extension://aailnablglhloogfnpkgddnjjfimhhhg

so you just put "aailnablglhloogfnpkgddnjjfimhhhg" without chrome-extension://

Body:
I'm building a Chrome Extension that interacts with an API that I wish to protect using Google recatcha, as I'm intending for it to be used beyond just the Chrome Extension. The API side is working, correctly verifying a recaptcha response with Google, however, displaying the recatcha widget inside the extension's browser action window is resulting in the following javascript error:

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('chrome-extension://pjhcgfibbbmibojnlkgjejaojpokgldl:80') does not match the recipient window's origin ('chrome-extension://pjhcgfibbbmibojnlkgjejaojpokgldl').

which is generated in recaptcha_en.js at the line:

(a.window || ne(a.Tg)).postMessage(JSON.stringify({
        message: c || null ,
        messageType: b
    }), Zj(a.path));

The problem seems to be that the value of a.path is chrome-extension://pjhcgfibbbmibojnlkgjejaojpokgldl:80 but I don't know how I can affect this value.

The result of this error is that the recaptcha widget displays a message saying:

Please upgrade to a supported browser to get a reCAPTCHA challenge.

I'm displaying the widget via the auto render method, but have also tried the explicit method which results in the same error. For info, I'm using the following content_security_policy:

script-src 'self' https://*.google.com https://*.gstatic.com; object-src 'self'

Is there any way I can get this to work in my extension? And if not, what is the best alternative method for integrating recaptcha?


问:
How to subscribe to an Observable that emits in some other part of the code?
I'm sort of a beginner on RxJava. I have the following issue.
I have a Presenter and a Fragment. I'm creating the Presenter inside onCreate of the Fragment.
I want to subscribe to an Observable in the Presenter's constructor. And this Observable should emit when the Fragment's onViewCreated fires (which calls some method in the Presenter - i.e. onViewReady).
The issue I'm running into is that when I create the Observable (in the Presenter's constructor), I also have to pass the emitter then. How can I subscribe to the observable in the constructor and emit later inside onViewReady?

I tried searching bunch of StackOverflow and Medium links. All of them seem to always pass the emitter during Observable creation.

Fragment

```<code>@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    // create presenter
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    // call presenter.onViewReady
}
</code>```

Presenter

```<code>Presenter() {
    // create and subscribe to observable
}

public void onViewReady() {
    // emit observable
}
</code>```

答:
Here is an example of how you could achieve that:</p>

```<code>private final Observable<MyClass> myObservable;

Presenter() {
    // create observable
    myObservable = Observable.create(new Action1<Emitter<MyClass>>() {
        @Override
        public void call(Emitter<MyClass> emitter) {
            // Emit here
            emitter.onNext(...);
            emitter.onNext(...);

            emitter.onCompleted();
        }
    });
}

public void onViewReady() {
    // subscribe to the observable
    myObservable.subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers::mainThread)
                .subscribe(
                        new Action1<MyClass>() {
                            @Override
                            public void call(MyClass mc) {
                                // TODO implement
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                // TODO implement
                            }
                        }
                );
}
</code>```

Body:
I'm sort of a beginner on RxJava. I have the following issue.
I have a Presenter and a Fragment. I'm creating the Presenter inside onCreate of the Fragment.
I want to subscribe to an Observable in the Presenter's constructor. And this Observable should emit when the Fragment's onViewCreated fires (which calls some method in the Presenter - i.e. onViewReady).
The issue I'm running into is that when I create the Observable (in the Presenter's constructor), I also have to pass the emitter then. How can I subscribe to the observable in the constructor and emit later inside onViewReady?

I tried searching bunch of StackOverflow and Medium links. All of them seem to always pass the emitter during Observable creation.

Fragment

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    // create presenter
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    // call presenter.onViewReady
}

Presenter

Presenter() {
    // create and subscribe to observable
}

public void onViewReady() {
    // emit observable
}

Body:
Here is an example of how you could achieve that:

private final Observable<MyClass> myObservable;

Presenter() {
    // create observable
    myObservable = Observable.create(new Action1<Emitter<MyClass>>() {
        @Override
        public void call(Emitter<MyClass> emitter) {
            // Emit here
            emitter.onNext(...);
            emitter.onNext(...);

            emitter.onCompleted();
        }
    });
}

public void onViewReady() {
    // subscribe to the observable
    myObservable.subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers::mainThread)
                .subscribe(
                        new Action1<MyClass>() {
                            @Override
                            public void call(MyClass mc) {
                                // TODO implement
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                // TODO implement
                            }
                        }
                );
}


问:
What javascript would I need to open two web pages at the same time and close the previous tab?
I'm working on an exam project where students will click on an option which would open two tabs with different case studies and close the previous tab but I don't have experience with Javascript and I'm unsure how to approach the problem.

It's built on Wordpress and I've tried using various plugins but all of them have failed. I have managed to get links to open in new tab (no different to  but not close the previous one or open two tabs with individual webpages.

We're using anchor tags currently in HTML and putting the javascript inline but I think we might need to tackle it differently, potentially through calling a javascript file.

We want to use Javascript as it'll allow us to add code to track users when they click on the link.

The page layout is very basic with one link on it (it has a pageview conversion tracking code to track the number of students taking the exam) so there's very little chance the script will conflict with anything else, this is why the previous tab should close automatically to avoid distraction

```<code><a href="http://www.example.com" onclick="window.open('https://www.example.com');return false">Example</a>
</code>```

It opens the webpage in a new tab but I'm unsure how to make it open two new tabs (different URLs) and close the previous tab.

(I noticed there are similar questions asked but none address closing the previous tab)

答:
If you want to perform all 3 of those actions at the same time then you may want to create a function that does all three, and then call that function with the onclick event.

href="http://www.example.com" onclick="myFunction()">```
</div>
</div>
</p>

<p>Then you will define the function in a JS file and link it to your html. Something like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="myscripts.js"></script></code>```

The JS file (in this example) would be named myscripts.js and would look something like this:

function myFunction(){
  window.open('url1.com');
  window.open('url2.com');
  window.close()
}```

Unfortunately, you are unable to close windows using Window.close() if that window was not opened by a script, so that is another issue. Without more information on how the user gets to this page in the first place, I can't really suggest a workaround.

Body:
I'm working on an exam project where students will click on an option which would open two tabs with different case studies and close the previous tab but I don't have experience with Javascript and I'm unsure how to approach the problem.

It's built on Wordpress and I've tried using various plugins but all of them have failed. I have managed to get links to open in new tab (no different to  but not close the previous one or open two tabs with individual webpages.

We're using anchor tags currently in HTML and putting the javascript inline but I think we might need to tackle it differently, potentially through calling a javascript file.

We want to use Javascript as it'll allow us to add code to track users when they click on the link.

The page layout is very basic with one link on it (it has a pageview conversion tracking code to track the number of students taking the exam) so there's very little chance the script will conflict with anything else, this is why the previous tab should close automatically to avoid distraction

Example

It opens the webpage in a new tab but I'm unsure how to make it open two new tabs (different URLs) and close the previous tab.

(I noticed there are similar questions asked but none address closing the previous tab)

Body:
If you want to perform all 3 of those actions at the same time then you may want to create a function that does all three, and then call that function with the onclick event.

<a href="http://www.example.com" onclick="myFunction()">

Then you will define the function in a JS file and link it to your html. Something like this:

<script src="myscripts.js"></script>

The JS file (in this example) would be named myscripts.js and would look something like this:

function myFunction(){
  window.open('url1.com');
  window.open('url2.com');
  window.close()
}

Unfortunately, you are unable to close windows using Window.close() if that window was not opened by a script, so that is another issue. Without more information on how the user gets to this page in the first place, I can't really suggest a workaround.


问:
Search a value from another tab/sheet in google sheets based on cell reference
I'm trying to create a search page in google sheets where the user enters a value in one cell(s) and then other cells auto-populate with values from another tab/sheet based on the value entered in the search cell(s).

I'm trying to use VLOOKUP up in an array but it gives either error or N/A.

I have 'sheet1' with data from a google forms (columns from A to BN) and I'm trying to make a search page in 'Sheet2' where on top the user can write for example the ID-number, and I want to grab the value of a column from 'sheet1' that matches the ID-number written on the same row for 'sheet1'.

I've already checked:

VLOOKUP to the left from another sheet in Google Sheets

How to get value depending on list selection in spreadsheet?

Google sheets - VLOOKUP inside ARRAYFORMULA

There are others but I'm not looking for any scripts.

In simple form the formula would be:

```<code>=VLOOKUP(B3,'sheet1'!A:BN,40,False)
</code>```

But because I have too many columns and I'll be needing to grab other values too I'm using:

```<code>=ArrayFormula(IF(LEN(B3),VLOOKUP(B3,{'sheet1'!A:BN},{iferror(match("ID-number",'sheet1'!A1:BN1,0),"No match")},FALSE),""))
</code>```

Explanation:

B3 is the cell where the user inputs the id number value

Then ...:

```<code>{'sheet1'!A:BN},{iferror(match("ID-number",'sheet1'!A1:BN1,0),"No match")}
</code>```

is where I'm looking for the number of the column of the title of value I'm looking for, in this case, it is AN, which would be the column 40 but it could be any other.

And then the ArrayFormula is because sheet1 is data from a Google form that is on use and increasing rows constantly.

It gives me an error of #N/A because it doesn't find the value (input in B3 in sheet 2) in the range (tab sheet1 in all the columns from A to BN that have values)

Example sheet with working answer is [here]:
 (https://docs.google.com/spreadsheets/d/1qLcJdCn4EdV7lPOAfZ_CMak1LBkve45FL5SXyqBV3L8/edit?usp=sharing)

NOTE: The values to search/return are on the same row in sheet 1 and when a new search is entered then only the row changes.

答:
You cannot use match inside arrayformula.
I suggst you to use something like

```<code>=ArrayFormula(IF(LEN(B3),VLOOKUP(B3,{'sheet1'!AN:AN,'sheet1'!A:BN},column('sheet1'!X:X)-column('sheet1'!A:A)+1,FALSE),""))
</code>```

where X is the resulting column (change that to your needs).

Body:
I'm trying to create a search page in google sheets where the user enters a value in one cell(s) and then other cells auto-populate with values from another tab/sheet based on the value entered in the search cell(s).

I'm trying to use VLOOKUP up in an array but it gives either error or N/A.

I have 'sheet1' with data from a google forms (columns from A to BN) and I'm trying to make a search page in 'Sheet2' where on top the user can write for example the ID-number, and I want to grab the value of a column from 'sheet1' that matches the ID-number written on the same row for 'sheet1'.

I've already checked:

VLOOKUP to the left from another sheet in Google Sheets

How to get value depending on list selection in spreadsheet?

Google sheets - VLOOKUP inside ARRAYFORMULA

There are others but I'm not looking for any scripts.

In simple form the formula would be:

=VLOOKUP(B3,'sheet1'!A:BN,40,False)

But because I have too many columns and I'll be needing to grab other values too I'm using:

=ArrayFormula(IF(LEN(B3),VLOOKUP(B3,{'sheet1'!A:BN},{iferror(match("ID-number",'sheet1'!A1:BN1,0),"No match")},FALSE),""))

Explanation:

B3 is the cell where the user inputs the id number value

Then ...:

{'sheet1'!A:BN},{iferror(match("ID-number",'sheet1'!A1:BN1,0),"No match")}

is where I'm looking for the number of the column of the title of value I'm looking for, in this case, it is AN, which would be the column 40 but it could be any other.

And then the ArrayFormula is because sheet1 is data from a Google form that is on use and increasing rows constantly.

It gives me an error of #N/A because it doesn't find the value (input in B3 in sheet 2) in the range (tab sheet1 in all the columns from A to BN that have values)

Example sheet with working answer is [here]:
 (https://docs.google.com/spreadsheets/d/1qLcJdCn4EdV7lPOAfZ_CMak1LBkve45FL5SXyqBV3L8/edit?usp=sharing)

NOTE: The values to search/return are on the same row in sheet 1 and when a new search is entered then only the row changes.

Body:
You cannot use match inside arrayformula.
I suggst you to use something like

=ArrayFormula(IF(LEN(B3),VLOOKUP(B3,{'sheet1'!AN:AN,'sheet1'!A:BN},column('sheet1'!X:X)-column('sheet1'!A:A)+1,FALSE),""))

where X is the resulting column (change that to your needs).


问:
DKIM on multiple lines
I have now used 4(!) days trying to get this DKIM TXT record to get recognized, so I really hope that someone is able to help me out now..

The DKIM I have from my server is output on three lines like this:

```<code>default._domainkey IN TXT "v=DKIM1; k=rsa;

p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ7AMIIBCgKCAQEAvbBZcUcajRf+nP+BSvhsa8roEcor2rf9oLs98u8HrqjZgpHQJ4frbA2C8OuRlPGN9JzZOpTmeeJg2eITeJXlQsc88xX0hqZCogDUeUcTLghDhw2Vd7q5AWG6mDcc3F2HJ0q5GwkYTS7d6D9nXCGcCE/M/F2pgwBe5MI5S9h60cr+XhHrK3uDCW3QNMj6jRDIW"

    3o5WquA5/MmQJJ38BwMzn/7HJwcL5aJ5EnA3KlLi413kK820f4h2E+u4dAT5Kmua7x8Lx1ny7oEZH/MBQoEMq0s7XuDD+d0gR/0VCHvQ6PhZf4wOwzGIO6jn/Fb/pywAgQqZRglRGZLbcoHHQCIgQIDAQAB\;
</code>```

I have tried to add it in numerous different ways, but every time I get some kind of error. Also, it seems like my DNS is changing the order of the entries I make. Could this be the error?

Any kind of help is really, really appreciated.. Please. Thanks!

答:
I wanted to comment on Ryan Young answer but I don't have enough reputation for that.

This answer is correct except that the second line of the DKIM key needs to also be in the p value in the DNS TXT entry like that:

```<code>v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ7AMIIBCgKCAQEAvbBZcUcajRf+nP+BSvhsa8roEcor2rf9oLs98u8HrqjZgpHQJ4frbA2C8OuRlPGN9JzZOpTmeeJg2eITeJXlQsc88xX0hqZCogDUeUcTLghDhw2Vd7q5AWG6mDcc3F2HJ0q5GwkYTS7d6D9nXCGcCE/M/F2pgwBe5MI5S9h60cr+XhHrK3uDCW3QNMj6jRDIW3o5WquA5/MmQJJ38BwMzn/7HJwcL5aJ5EnA3KlLi413kK820f4h2E+u4dAT5Kmua7x8Lx1ny7oEZH/MBQoEMq0s7XuDD+d0gR/0VCHvQ6PhZf4wOwzGIO6jn/Fb/pywAgQqZRglRGZLbcoHHQCIgQIDAQAB
</code>```

All the DKIM p entries for my domains typically start with "MI" and end with "IDAQAB". You may need to remove from them the spaces/tabs, line feeds/returns and double/single quotes if they are on several lines.

Edit:
I found out that using the long 2048 DKIM key lead to the following in the original email on gmail:

```<code>dkim=neutral (invalid public key) header.i=...
</code>```

This was probably because the key was being truncated anyway.
What I had to do to get a normal situation was to reduce the size of the DKIM key when generating the key:

```<code>opendkim-genkey -b 1024 -s mail -d example.com
</code>```

My emails then viewed as original in gmail contain this instead of the invalid key mention:

```<code>dkim=pass header.i=...
</code>```

Title: DKIM on multiple lines

Body:
I have now used 4(!) days trying to get this DKIM TXT record to get recognized, so I really hope that someone is able to help me out now..

The DKIM I have from my server is output on three lines like this:

default._domainkey IN TXT "v=DKIM1; k=rsa;

p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ7AMIIBCgKCAQEAvbBZcUcajRf+nP+BSvhsa8roEcor2rf9oLs98u8HrqjZgpHQJ4frbA2C8OuRlPGN9JzZOpTmeeJg2eITeJXlQsc88xX0hqZCogDUeUcTLghDhw2Vd7q5AWG6mDcc3F2HJ0q5GwkYTS7d6D9nXCGcCE/M/F2pgwBe5MI5S9h60cr+XhHrK3uDCW3QNMj6jRDIW"

    3o5WquA5/MmQJJ38BwMzn/7HJwcL5aJ5EnA3KlLi413kK820f4h2E+u4dAT5Kmua7x8Lx1ny7oEZH/MBQoEMq0s7XuDD+d0gR/0VCHvQ6PhZf4wOwzGIO6jn/Fb/pywAgQqZRglRGZLbcoHHQCIgQIDAQAB\;

I have tried to add it in numerous different ways, but every time I get some kind of error. Also, it seems like my DNS is changing the order of the entries I make. Could this be the error?

Any kind of help is really, really appreciated.. Please. Thanks!

Body:
I wanted to comment on Ryan Young answer but I don't have enough reputation for that.

This answer is correct except that the second line of the DKIM key needs to also be in the p value in the DNS TXT entry like that:

v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ7AMIIBCgKCAQEAvbBZcUcajRf+nP+BSvhsa8roEcor2rf9oLs98u8HrqjZgpHQJ4frbA2C8OuRlPGN9JzZOpTmeeJg2eITeJXlQsc88xX0hqZCogDUeUcTLghDhw2Vd7q5AWG6mDcc3F2HJ0q5GwkYTS7d6D9nXCGcCE/M/F2pgwBe5MI5S9h60cr+XhHrK3uDCW3QNMj6jRDIW3o5WquA5/MmQJJ38BwMzn/7HJwcL5aJ5EnA3KlLi413kK820f4h2E+u4dAT5Kmua7x8Lx1ny7oEZH/MBQoEMq0s7XuDD+d0gR/0VCHvQ6PhZf4wOwzGIO6jn/Fb/pywAgQqZRglRGZLbcoHHQCIgQIDAQAB

All the DKIM p entries for my domains typically start with "MI" and end with "IDAQAB". You may need to remove from them the spaces/tabs, line feeds/returns and double/single quotes if they are on several lines.

Edit:
I found out that using the long 2048 DKIM key lead to the following in the original email on gmail:

dkim=neutral (invalid public key) header.i=...

This was probably because the key was being truncated anyway.
What I had to do to get a normal situation was to reduce the size of the DKIM key when generating the key:

opendkim-genkey -b 1024 -s mail -d example.com

My emails then viewed as original in gmail contain this instead of the invalid key mention:

dkim=pass header.i=...


问:
Machine Learning model generalisation
I'm new to Machine Learning, and I'd like to make a question regarding the model generalization. In my case, I'm going to produce some mechanical parts, and I'm interested in the control of the input parameters to obtain certain properties on the final part.

More particularly, I'm interested in 8 parameters (say, P1, P2, ..., P8). In which to optimize the number of required pieces produced to maximize the combinations of parameters explored, I've divided the problem into 2 sets. For the first set of pieces, I'll vary the first 4 parameters (P1 ... P4), while the others will be held constant. In the second case, I'll do the opposite (variables P5 ... P8 and constants P1 ... P4).

So I'd like to know if it's possible to make a single model that has the eight parameters as inputs to predict the properties of the final part. I ask because as I'm not varying all the 8 variables at once, I thought that maybe I would have to do 1 model for each set of parameters, and the predictions of the 2 different models couldn't be related one to the other.

Thanks in advance.

答:
In most cases having two different models will have a better accuracy then one big model. The reason is that in local models, the model will only look at 4 features and will be able to identify patterns among them to make prediction.

But this particular approach will most certainly fail to scale. Right now you only have two sets of data but what if it increases and you have 20 sets of data. It will not be possible for you to create and maintain 20 ML models in production.

What works best for your case will need some experimentation. Take a random sample from data and train ML models. Take one big model and two local models and evaluate their performance. Not just accuracy, but also their F1 score, AUC-PR and ROC curve too to find out what works best for you. If you do not see a major performance drop, then one big model for the entire dataset will be a better option. If you know that your data will always be divided into these two sets and you dont care about scalability, then go with two local models.

Title: Machine Learning model generalisation


问:
Count word frequency of all words in a file
I have a text file, from which I have removed symbols and stop words.

I have also tokenized it (broken it into a list of all words) in case operations are easier with a list.

I would like to create a .csv file with frequencies of all words (long format) in descending order. How could I go about it?

I have thought about looping through the list thus:

```<code>longData = pandas.DataFrame([], index=[], columns=['Frequency'])
for word in tokenizedFile:
    if word in longData.index:
         longData.loc[word]=longData.loc[word]+1
    else:
         wordFrame = pandas.DataFrame([1], index=[word])
         longData.append(wordFrame)
</code>```

but that seems pretty inefficient and wasteful.

答:
You can use Series.str.extractall() and Series.value_counts(). Assume file.txt is the file-path with texts removed symbols and stop words:

```<code># read file into one column dataframe, the default column name is '0'
df = pd.read_csv('file.txt', sep='\n', header=None)

# extract words into rows and then do value_counts()
words_count = df[0].str.extractall(r'(\w+)')[0].value_counts()
</code>```

The above result words_count is a Series which you can convert to dataframe by:

```<code>df_new = words_count.to_frame('words_count')
</code>```

Body:
I have a text file, from which I have removed symbols and stop words.

I have also tokenized it (broken it into a list of all words) in case operations are easier with a list.

I would like to create a .csv file with frequencies of all words (long format) in descending order. How could I go about it?

I have thought about looping through the list thus:

longData = pandas.DataFrame([], index=[], columns=['Frequency'])
for word in tokenizedFile:
    if word in longData.index:
         longData.loc[word]=longData.loc[word]+1
    else:
         wordFrame = pandas.DataFrame([1], index=[word])
         longData.append(wordFrame)

but that seems pretty inefficient and wasteful.

Body:
You can use Series.str.extractall() and Series.value_counts(). Assume file.txt is the file-path with texts removed symbols and stop words:

# read file into one column dataframe, the default column name is '0'
df = pd.read_csv('file.txt', sep='\n', header=None)

# extract words into rows and then do value_counts()
words_count = df[0].str.extractall(r'(\w+)')[0].value_counts()

The above result words_count is a Series which you can convert to dataframe by:

df_new = words_count.to_frame('words_count')


问:
Revisiting Gauss sum with Isabelle
I'm interested in a variation of the argument that stablishes:

```<code>"(∑ i=1..k . i) = k*(k+1) div 2"
</code>```

We know this follows from a simple induction but the intution is a bit different. A way to see this formula is that if you sum the extremes of the sequence of numbers 1..k you get

1+k = 2 + (k-1) = ...

and then you just multiply the right number of times to get the complete sum.

I would like to reproduce this argument to show the following inequality:

```<code>"(∑n = 1..k - 1. cmod (f (int n))) ≤ 2 * (∑n ≤ k div 2. cmod (f (int n)))"
</code>```

Here I know that cmod (f (int k - n)) = cmod (cnj (f n)) for every n.

Do you see an elegant way of proving this in Isabelle?

答:
The trick to do this proof in an elegant way is to realise that ∑i=1..k. i is the same as ∑i=1..k. k + 1 - i and then adding that to the original sum so that the i cancels. This is a simple re-indexing argument:

```<code>lemma "(∑i=1..k. i :: nat) = k * (k + 1) div 2"
proof -
  have "(∑i=1..k. i) = (∑i=1..k. k + 1 - i)"
    by (rule sum.reindex_bij_witness[of _ "λi. k + 1 - i" "λi. k + 1 - i"]) auto
  hence "2 * (∑i=1..k. i) = (∑i=1..k. i) + (∑i=1..k. k + 1 - i)"
    by simp
  also have "… = k * (k + 1)"
    by (simp add: sum.distrib [symmetric])
  finally show ?thesis by simp
qed
</code>```

For the other thing you mentioned, I think that the best way to do this is to first split the sum into the elements less that k div 2 and the rest. Then you can reindex the second sum similarly to the one above. Then the inequality part comes in because you might have one extra leftover element ‘in the middle’ if k is odd and you have to throw that away.

Brief sketch of the important part of the proof:

```<code>lemma
  assumes "⋀i. f i ≥ 0"
  shows   "(∑i=1..<k. f (i::nat) :: real) = T"
proof -
  (* Separate summation domain into two disjoint parts *)
  have "(∑i=1..<k. f i) = (∑i∈{1..k div 2}∪{k div 2<..<k}. f i)"
    by (intro sum.cong) auto
  (* Pull sum apart *)
  also have "… = (∑i∈{1..k div 2}. f i) + (∑i∈{k div 2<..<k}. f i)"
    by (subst sum.union_disjoint) auto
  (* Reindex the second sum *)
  also have "(∑i∈{k div 2<..<k}. f i) = (∑i∈{1..<k - k div 2}. f (k - i))"
    by (rule sum.reindex_bij_witness[of _ "λi. k - i" "λi. k - i"]) auto
  (* Throw away the element in the middle if k is odd *)
  also have "… ≤ (∑i∈{1..k div 2}. f (k - i))"
    using assms by (intro sum_mono2) auto
  finally have "(∑i=1..<k. f i) ≤ (∑i=1..k div 2. f i + f (k - i))"
    by (simp add: sum.distrib)
</code>```

Figuring out how to do these sum manipulations idiomatically in Isabelle takes some experience. sum.reindex_bij_witness is a very useful rule (as you can see). Things like sum.mono_neutral_left/right can also help a lot.

Title: Revisiting Gauss sum with Isabelle

Body:
I'm interested in a variation of the argument that stablishes:

"(∑ i=1..k . i) = k*(k+1) div 2"

We know this follows from a simple induction but the intution is a bit different. A way to see this formula is that if you sum the extremes of the sequence of numbers 1..k you get

1+k = 2 + (k-1) = ...

and then you just multiply the right number of times to get the complete sum.

I would like to reproduce this argument to show the following inequality:

"(∑n = 1..k - 1. cmod (f (int n))) ≤ 2 * (∑n ≤ k div 2. cmod (f (int n)))"

Here I know that cmod (f (int k - n)) = cmod (cnj (f n)) for every n.

Do you see an elegant way of proving this in Isabelle?

Body:
The trick to do this proof in an elegant way is to realise that ∑i=1..k. i is the same as ∑i=1..k. k + 1 - i and then adding that to the original sum so that the i cancels. This is a simple re-indexing argument:

lemma "(∑i=1..k. i :: nat) = k * (k + 1) div 2"
proof -
  have "(∑i=1..k. i) = (∑i=1..k. k + 1 - i)"
    by (rule sum.reindex_bij_witness[of _ "λi. k + 1 - i" "λi. k + 1 - i"]) auto
  hence "2 * (∑i=1..k. i) = (∑i=1..k. i) + (∑i=1..k. k + 1 - i)"
    by simp
  also have "… = k * (k + 1)"
    by (simp add: sum.distrib [symmetric])
  finally show ?thesis by simp
qed

For the other thing you mentioned, I think that the best way to do this is to first split the sum into the elements less that k div 2 and the rest. Then you can reindex the second sum similarly to the one above. Then the inequality part comes in because you might have one extra leftover element ‘in the middle’ if k is odd and you have to throw that away.

Brief sketch of the important part of the proof:

lemma
  assumes "⋀i. f i ≥ 0"
  shows   "(∑i=1..<k. f (i::nat) :: real) = T"
proof -
  (* Separate summation domain into two disjoint parts *)
  have "(∑i=1..<k. f i) = (∑i∈{1..k div 2}∪{k div 2<..<k}. f i)"
    by (intro sum.cong) auto
  (* Pull sum apart *)
  also have "… = (∑i∈{1..k div 2}. f i) + (∑i∈{k div 2<..<k}. f i)"
    by (subst sum.union_disjoint) auto
  (* Reindex the second sum *)
  also have "(∑i∈{k div 2<..<k}. f i) = (∑i∈{1..<k - k div 2}. f (k - i))"
    by (rule sum.reindex_bij_witness[of _ "λi. k - i" "λi. k - i"]) auto
  (* Throw away the element in the middle if k is odd *)
  also have "… ≤ (∑i∈{1..k div 2}. f (k - i))"
    using assms by (intro sum_mono2) auto
  finally have "(∑i=1..<k. f i) ≤ (∑i=1..k div 2. f i + f (k - i))"
    by (simp add: sum.distrib)

Figuring out how to do these sum manipulations idiomatically in Isabelle takes some experience. sum.reindex_bij_witness is a very useful rule (as you can see). Things like sum.mono_neutral_left/right can also help a lot.


问:
LINQ: failed because the materialized value is null
I'm trying to use sum in code below but I get the error:

The cast to value type 'System.Int32' failed because the materialized
  value is null. Either the result type's generic parameter or the query
  must use a nullable type.

```<code>Product_Order:
    ---------------- ----------- ---------
    |   ProductId   | OrderId   | Quantity |
    ---------------- ----------- ---------
</code>```

I get the error at "let quantity"

```<code>  var fullInfo = (from product in allProdcts
                 let quantity = db.Product_Order.Where(x=> x.ProductId == product.ID).Sum(x => x.Quantity)
                select new ReportVm
                    {
                        ProductId = product.ID,
                        ProductName = product.Name,
                        AmountProduct = quantity,
                        TotPrice = (quantity)*(product.Price)
                    }).ToList();
</code>```

This is my Product_Order table(M-M relation):

```<code>Product_Order:
    ---------------- ----------- ---------
    |   ProductId   | OrderId   | Quantity |
    ---------------- ----------- ---------
</code>```

Any idea how to solve this?

答:
Another solution...</p>

```<code>let quantity = db.Product_Order.Where(x=> x.ProductId == product.ID).Sum(x => x.Quantity == null ? 0 : x.Quantity)
</code>```

Body:
I'm trying to use sum in code below but I get the error:

The cast to value type 'System.Int32' failed because the materialized
  value is null. Either the result type's generic parameter or the query
  must use a nullable type.

Product_Order:
    ---------------- ----------- ---------
    |   ProductId   | OrderId   | Quantity |
    ---------------- ----------- ---------

I get the error at "let quantity"

  var fullInfo = (from product in allProdcts
                 let quantity = db.Product_Order.Where(x=> x.ProductId == product.ID).Sum(x => x.Quantity)
                select new ReportVm
                    {
                        ProductId = product.ID,
                        ProductName = product.Name,
                        AmountProduct = quantity,
                        TotPrice = (quantity)*(product.Price)
                    }).ToList();

This is my Product_Order table(M-M relation):

Product_Order:
    ---------------- ----------- ---------
    |   ProductId   | OrderId   | Quantity |
    ---------------- ----------- ---------

Any idea how to solve this?

Body:
Another solution...

let quantity = db.Product_Order.Where(x=> x.ProductId == product.ID).Sum(x => x.Quantity == null ? 0 : x.Quantity)


问:
Permission denied when running NPM module that sets environment variables in Nodejs on Kubuntu 18.04
I am trying to set environment variables on process.env in nodejs using the npm module env-cmd. My system is running Kubuntu 18.04.

I consistently get "permission denied" even when using sudo.

My node and npm versions are the ones from the Ubuntu package manager. So not the latest, but the latest "approved" ones.

I would like to get past this permission denied thing.

I have tried updating env-cmd to the latest package and using the -f switch with the exact same results. I have verified my file path is correct and double checked my code. Which leads me to think this is a "linux thing"

from package.json

```<code>"scripts": {
    "start": "node src/index.js",
    "dev": "env-cmd ./config/dev.env nodemon src/index.js"
  },
"devDependencies": {
    "env-cmd": "^8.0.2",
    "nodemon": "^1.18.9"
  }
</code>```

from dev.env

PORT=3000

from index.js

const port = process.env.PORT;

The expected result is that node runs and variables get set on process.env

Terminal output is

```<code>hoo@BadWolf:~/storage/node-task-api v3$ npm run dev

> node-task-manager@1.0.0 dev /home/hoo/storage/node-task-api v3
> sudo env-cmd ./config/dev.env nodemon src/index.js

[sudo] password for hoo:
sudo: env-cmd: command not found

npm ERR! Linux 4.15.0-50-generic
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "run" "dev"
npm ERR! node v8.10.0
npm ERR! npm  v3.5.2
npm ERR! code ELIFECYCLE
npm ERR! node-task-manager@1.0.0 dev: `sudo env-cmd ./config/dev.env nodemon src/index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-task-manager@1.0.0 dev script 'sudo env-cmd ./config/dev.env nodemon src/index.js'.
....(details on how to report an issue)
npm ERR!     /home/hoo/storage/node-task-api v3/npm-debug.log
</code>```

debug.log:

```<code>0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'run', 'dev' ]
2 info using npm@3.5.2
3 info using node@v8.10.0
4 verbose run-script [ 'predev', 'dev', 'postdev' ]
5 info lifecycle node-task-manager@1.0.0~predev: node-task-manager@1.0.0
6 silly lifecycle node-task-manager@1.0.0~predev: no script for predev, continuing
7 info lifecycle node-task-manager@1.0.0~dev: node-task-manager@1.0.0
8 verbose lifecycle node-task-manager@1.0.0~dev: unsafe-perm in lifecycle true
9 verbose lifecycle node-task-manager@1.0.0~dev: PATH: /usr/share/npm/bin/node-gyp-bin:/home/hoo/storage/node-task-api v3/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
10 verbose lifecycle node-task-manager@1.0.0~dev: CWD: /home/hoo/storage/node-task-api v3
11 silly lifecycle node-task-manager@1.0.0~dev: Args: [ '-c', 'env-cmd ./config/dev.env nodemon src/index.js' ]
12 silly lifecycle node-task-manager@1.0.0~dev: Returned: code: 126  signal: null
13 info lifecycle node-task-manager@1.0.0~dev: Failed to exec dev script
14 verbose stack Error: node-task-manager@1.0.0 dev: `env-cmd ./config/dev.env nodemon src/index.js`
14 verbose stack Exit status 126
14 verbose stack     at EventEmitter.<anonymous> (/usr/share/npm/lib/utils/lifecycle.js:232:16)
14 verbose stack     at emitTwo (events.js:126:13)
14 verbose stack     at EventEmitter.emit (events.js:214:7)
14 verbose stack     at ChildProcess.<anonymous> (/usr/share/npm/lib/utils/spawn.js:24:14)
14 verbose stack     at emitTwo (events.js:126:13)
14 verbose stack     at ChildProcess.emit (events.js:214:7)
14 verbose stack     at maybeClose (internal/child_process.js:925:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
15 verbose pkgid node-task-manager@1.0.0
16 verbose cwd /home/hoo/storage/node-task-api v3
17 error Linux 4.15.0-50-generic
18 error argv "/usr/bin/node" "/usr/bin/npm" "run" "dev"
19 error node v8.10.0
20 error npm  v3.5.2
21 error code ELIFECYCLE
22 error node-task-manager@1.0.0 dev: `env-cmd ./config/dev.env nodemon src/index.js`
22 error Exit status 126
23 error Failed at the node-task-manager@1.0.0 dev script 'env-cmd ./config/dev.env nodemon src/index.js'.
23 error Make sure you have the latest version of node.js and npm installed.
23 error If you do, this is most likely a problem with the node-task-manager package,
23 error not with npm itself.
23 error Tell the author that this fails on your system:
23 error     env-cmd ./config/dev.env nodemon src/index.js
....(details on how to report an issue)
24 verbose exit [ 1, true ]
</code>```

答:
Solved this with some help from Adam Hartleb, a Course Assistant at Udemy. He suggested running it with npx, which worked, after some finagling.

For anyone else having this problem, here is what I did:

I solved this by inspecting the source code for env-cmd, then re-reading the docs.

The problem  is that, in Ubuntu 18.04 at least, env-cmd doesn't play well with non-default file locations.

To get it to run, you must have a version of Node that supports npx. If you are in Ubuntu then you have to use a version of node that is not supported by Canonical. The way I solved that was to install NVM and Node 10.15.3

how to install NVM and Node LTS

You will need to use the default file location for your .env file:

```<code> ./.env
</code>```

You will need to remove any references to non-default file locations,as their presence will only anger env-cmd. It will have a literal hangup. (it will actually spawn an error called "hangup"). It will also use the word "spawn". I only tell you what I saw.

I changed my "dev" script to

```<code>"dev" : "npx env-cmd nodemon src/index.js"
</code>```

It should work now. May the .env-gods be merciful upon your app.

BACKSTORY: How I got there

Adam's suggestion of "npx env-cmd ./config/dev.env nodemon src/index.js" resulted in:

```<code>hoo@BadWolf:~/storage/node-task-api v3$ npx env-cmd ./config/dev.env nodemon src/index.js
(node:19209) UnhandledPromiseRejectionWarning: Error: Unable to locate env file at default location (./.env)
    at /home/hoo/storage/node-task-api v3/node_modules/env-cmd/dist/get-env-vars.js:47:19
    at Generator.throw (<anonymous>)
    at rejected (/home/hoo/storage/node-task-api v3/node_modules/env-cmd/dist/get-env-vars.js:5:65)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:757:11)
    at findNodeScript.then.existing (/home/hoo/.nvm/versions/node/v10.15.3/lib/node_modules/npm/node_modules/libnpx/index.js:268:14)
(node:19209) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:19209) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

I traced the problem back to a few undefined variables in the module code, which I logged to terminal.

```<code>hoo@BadWolf:~/storage/node-task-api v3$ npx env-cmd ./config/dev.env nodemon src/index.js
Russ logging from get-env-vars.js 27:  getEnvFile({ filePath, fallback }): filePath = undefined
Russ logging from get-env-vars.js 27: getEnvFile({ filePath, fallback }): fallback = undefined
</code>```

Creating a .env file at ./.env and running the same npx script (with the non-default file argument)

```<code>hoo@BadWolf:~/storage/node-task-api v3$ npx env-cmd ./config/dev.env nodemon src/index.js
spawn ./config/dev.env EACCES
Hangup
</code>```

With the non-default file location removed, to spin up the server with env-cmd run:

```<code>npx env-cmd  nodemon src/index.js
</code>```

Body:
I am trying to set environment variables on process.env in nodejs using the npm module env-cmd. My system is running Kubuntu 18.04.

I consistently get "permission denied" even when using sudo.

My node and npm versions are the ones from the Ubuntu package manager. So not the latest, but the latest "approved" ones.

I would like to get past this permission denied thing.

I have tried updating env-cmd to the latest package and using the -f switch with the exact same results. I have verified my file path is correct and double checked my code. Which leads me to think this is a "linux thing"

from package.json

"scripts": {
    "start": "node src/index.js",
    "dev": "env-cmd ./config/dev.env nodemon src/index.js"
  },
"devDependencies": {
    "env-cmd": "^8.0.2",
    "nodemon": "^1.18.9"
  }

from dev.env

PORT=3000

from index.js

const port = process.env.PORT;

The expected result is that node runs and variables get set on process.env

Terminal output is

hoo@BadWolf:~/storage/node-task-api v3$ npm run dev

> node-task-manager@1.0.0 dev /home/hoo/storage/node-task-api v3
> sudo env-cmd ./config/dev.env nodemon src/index.js

[sudo] password for hoo:
sudo: env-cmd: command not found

npm ERR! Linux 4.15.0-50-generic
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "run" "dev"
npm ERR! node v8.10.0
npm ERR! npm  v3.5.2
npm ERR! code ELIFECYCLE
npm ERR! node-task-manager@1.0.0 dev: `sudo env-cmd ./config/dev.env nodemon src/index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-task-manager@1.0.0 dev script 'sudo env-cmd ./config/dev.env nodemon src/index.js'.
....(details on how to report an issue)
npm ERR!     /home/hoo/storage/node-task-api v3/npm-debug.log

debug.log:

0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'run', 'dev' ]
2 info using npm@3.5.2
3 info using node@v8.10.0
4 verbose run-script [ 'predev', 'dev', 'postdev' ]
5 info lifecycle node-task-manager@1.0.0~predev: node-task-manager@1.0.0
6 silly lifecycle node-task-manager@1.0.0~predev: no script for predev, continuing
7 info lifecycle node-task-manager@1.0.0~dev: node-task-manager@1.0.0
8 verbose lifecycle node-task-manager@1.0.0~dev: unsafe-perm in lifecycle true
9 verbose lifecycle node-task-manager@1.0.0~dev: PATH: /usr/share/npm/bin/node-gyp-bin:/home/hoo/storage/node-task-api v3/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
10 verbose lifecycle node-task-manager@1.0.0~dev: CWD: /home/hoo/storage/node-task-api v3
11 silly lifecycle node-task-manager@1.0.0~dev: Args: [ '-c', 'env-cmd ./config/dev.env nodemon src/index.js' ]
12 silly lifecycle node-task-manager@1.0.0~dev: Returned: code: 126  signal: null
13 info lifecycle node-task-manager@1.0.0~dev: Failed to exec dev script
14 verbose stack Error: node-task-manager@1.0.0 dev: `env-cmd ./config/dev.env nodemon src/index.js`
14 verbose stack Exit status 126
14 verbose stack     at EventEmitter.<anonymous> (/usr/share/npm/lib/utils/lifecycle.js:232:16)
14 verbose stack     at emitTwo (events.js:126:13)
14 verbose stack     at EventEmitter.emit (events.js:214:7)
14 verbose stack     at ChildProcess.<anonymous> (/usr/share/npm/lib/utils/spawn.js:24:14)
14 verbose stack     at emitTwo (events.js:126:13)
14 verbose stack     at ChildProcess.emit (events.js:214:7)
14 verbose stack     at maybeClose (internal/child_process.js:925:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
15 verbose pkgid node-task-manager@1.0.0
16 verbose cwd /home/hoo/storage/node-task-api v3
17 error Linux 4.15.0-50-generic
18 error argv "/usr/bin/node" "/usr/bin/npm" "run" "dev"
19 error node v8.10.0
20 error npm  v3.5.2
21 error code ELIFECYCLE
22 error node-task-manager@1.0.0 dev: `env-cmd ./config/dev.env nodemon src/index.js`
22 error Exit status 126
23 error Failed at the node-task-manager@1.0.0 dev script 'env-cmd ./config/dev.env nodemon src/index.js'.
23 error Make sure you have the latest version of node.js and npm installed.
23 error If you do, this is most likely a problem with the node-task-manager package,
23 error not with npm itself.
23 error Tell the author that this fails on your system:
23 error     env-cmd ./config/dev.env nodemon src/index.js
....(details on how to report an issue)
24 verbose exit [ 1, true ]

Body:
Solved this with some help from Adam Hartleb, a Course Assistant at Udemy. He suggested running it with npx, which worked, after some finagling.

For anyone else having this problem, here is what I did:

I solved this by inspecting the source code for env-cmd, then re-reading the docs.

The problem  is that, in Ubuntu 18.04 at least, env-cmd doesn't play well with non-default file locations.

To get it to run, you must have a version of Node that supports npx. If you are in Ubuntu then you have to use a version of node that is not supported by Canonical. The way I solved that was to install NVM and Node 10.15.3

how to install NVM and Node LTS

You will need to use the default file location for your .env file:

 ./.env

You will need to remove any references to non-default file locations,as their presence will only anger env-cmd. It will have a literal hangup. (it will actually spawn an error called "hangup"). It will also use the word "spawn". I only tell you what I saw.

I changed my "dev" script to

"dev" : "npx env-cmd nodemon src/index.js"

It should work now. May the .env-gods be merciful upon your app.

BACKSTORY: How I got there

Adam's suggestion of "npx env-cmd ./config/dev.env nodemon src/index.js" resulted in:

hoo@BadWolf:~/storage/node-task-api v3$ npx env-cmd ./config/dev.env nodemon src/index.js
(node:19209) UnhandledPromiseRejectionWarning: Error: Unable to locate env file at default location (./.env)
    at /home/hoo/storage/node-task-api v3/node_modules/env-cmd/dist/get-env-vars.js:47:19
    at Generator.throw (<anonymous>)
    at rejected (/home/hoo/storage/node-task-api v3/node_modules/env-cmd/dist/get-env-vars.js:5:65)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:757:11)
    at findNodeScript.then.existing (/home/hoo/.nvm/versions/node/v10.15.3/lib/node_modules/npm/node_modules/libnpx/index.js:268:14)
(node:19209) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:19209) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I traced the problem back to a few undefined variables in the module code, which I logged to terminal.

hoo@BadWolf:~/storage/node-task-api v3$ npx env-cmd ./config/dev.env nodemon src/index.js
Russ logging from get-env-vars.js 27:  getEnvFile({ filePath, fallback }): filePath = undefined
Russ logging from get-env-vars.js 27: getEnvFile({ filePath, fallback }): fallback = undefined

Creating a .env file at ./.env and running the same npx script (with the non-default file argument)

hoo@BadWolf:~/storage/node-task-api v3$ npx env-cmd ./config/dev.env nodemon src/index.js
spawn ./config/dev.env EACCES
Hangup

With the non-default file location removed, to spin up the server with env-cmd run:

npx env-cmd  nodemon src/index.js


问:
Loop through array of arrays containing objects
This is my first time posting and I'm also very new to AngularJs and somewhat new to JavaScript in general. I hope I am providing enough info. I have an array containing arrays of objects [[{},{},{}],[{},{},{}],[{},{},{}]]. Is there a way to loop through this using AngularJs and output something similar to the following?

Group Title 1

01 Item title 1: item description

02 Item title 2: item description

Group Title 2

03 Item title 1: item description

04 Item title 2: item description

==============

```<code>$scope.groups_array = [
    [
        {
            "id": "01 ",
            "": [
                "Item Title 1",
                "Item description"
            ],
            "group_id": "A",
            "title": "Group Title 1"
        },
        {
            "id": "02 ",
            "": [
                "Item Title 2",
                "Item description"
            ],
            "group_id": "A",
            "title": "Group Title 1"
        }
    ],
    [
        {
            "id": "03 ",
            "": [
                "Item Title 1",
                "Item description"
            ],
            "group_id": "B",
            "title": "Group Title 2"
        },
        {
            "id": "04 ",
            "": [
                "Item Title 2",
                "Item description"
            ],
            "group_id": "B",
            "title": "Group Title 2"
        }
    ]
]

$scope.group_title = ["Group Title 1", "Group Title 2"];
</code>```

```<code><div>
    <div ng-repeat="title in group_title">
        <h1>{{title}}</h1>
        <ul>
            <li ng-repeat="item in groups_array">
              {{item.id + ' ' + item[''][0]}}: {{item[''][1]}}
            </li>
        </ul>
    </div>
</div>
</code>```

The output I'm getting instead is simply a list of the :'s with no errors in the console.

The arrays of objects themselves come from a master array containing all the objects, and I tried to group them into arrays by group title. I'm not sure if this is the best solution.

答:
The nested ng-repeat needs to select the correct group to iterate:

```<code><div>
    <div ng-repeat="title in group_title">
        <h1>{{title}}</h1>
        <ul>
            ̶<̶l̶i̶ ̶n̶g̶-̶r̶e̶p̶e̶a̶t̶=̶"̶i̶t̶e̶m̶ ̶i̶n̶ ̶g̶r̶o̶u̶p̶s̶_̶a̶r̶r̶a̶y̶"̶>̶
            <li ng-repeat="item in groups_array[$index]">
              {{item.id + ' ' + item[''][0]}}: {{item[''][1]}}
            </li>
        </ul>
    </div>
</div>
</code>```

This assumes that the order of the titles in the group_title array matches the order of the groups in the groups_array.

Body:
This is my first time posting and I'm also very new to AngularJs and somewhat new to JavaScript in general. I hope I am providing enough info. I have an array containing arrays of objects [[{},{},{}],[{},{},{}],[{},{},{}]]. Is there a way to loop through this using AngularJs and output something similar to the following?

Group Title 1

01 Item title 1: item description

02 Item title 2: item description

Group Title 2

03 Item title 1: item description

04 Item title 2: item description

==============

$scope.groups_array = [
    [
        {
            "id": "01 ",
            "": [
                "Item Title 1",
                "Item description"
            ],
            "group_id": "A",
            "title": "Group Title 1"
        },
        {
            "id": "02 ",
            "": [
                "Item Title 2",
                "Item description"
            ],
            "group_id": "A",
            "title": "Group Title 1"
        }
    ],
    [
        {
            "id": "03 ",
            "": [
                "Item Title 1",
                "Item description"
            ],
            "group_id": "B",
            "title": "Group Title 2"
        },
        {
            "id": "04 ",
            "": [
                "Item Title 2",
                "Item description"
            ],
            "group_id": "B",
            "title": "Group Title 2"
        }
    ]
]

$scope.group_title = ["Group Title 1", "Group Title 2"];

{{title}}

              {{item.id + ' ' + item[''][0]}}: {{item[''][1]}}

The output I'm getting instead is simply a list of the :'s with no errors in the console.

The arrays of objects themselves come from a master array containing all the objects, and I tried to group them into arrays by group title. I'm not sure if this is the best solution.

Body:
The nested ng-repeat needs to select the correct group to iterate:

<div>
    <div ng-repeat="title in group_title">
        <h1>{{title}}</h1>
        <ul>
            ̶<̶l̶i̶ ̶n̶g̶-̶r̶e̶p̶e̶a̶t̶=̶"̶i̶t̶e̶m̶ ̶i̶n̶ ̶g̶r̶o̶u̶p̶s̶_̶a̶r̶r̶a̶y̶"̶>̶
            <li ng-repeat="item in groups_array[$index]">
              {{item.id + ' ' + item[''][0]}}: {{item[''][1]}}
            </li>
        </ul>
    </div>
</div>

This assumes that the order of the titles in the group_title array matches the order of the groups in the groups_array.