问:
Assistance in understanding sqr logic

Hello, I am new to learning how to develop sqr programs within PeopleSoft. I've been going through some programs we are utilizing and wanted to see if someone could help provide clarification with what the below snippet of code is doing in this While loop.

```<code> if $path != ''
   let $Archive_File = $path || 'ARCHIVE\' || $filename || $Curr_Date || '.dat'
   open $Out_File  as 1  for-reading record=450:vary status=#fileread
   open $Archive_File as 2  for-writing record=450:vary status=#filewrite
   While 1
     if #END-FILE
        break
     else
        read 1 into $Current_Line:999
        write 2 from $Current_Line
    end-if
 End-While
 close 1
 close 2
end-if
</code>```

I'm trying to understand if the WHILE statement is evaluating the "$Out_File as 1" as the logical expression, or is 1 being evaluated as the value of the variable #END-FILE (As I understand this variable is set to either 0 or 1).

答:
In addition to the file name, the open command takes a number as a parameter which it uses as a handler for the file. In your example, two files are being opened.

The WHILE 1 statement doesn't have anything to do with file 1. Here 1 means true, instead of 0 for false. So 1 is always true, creating an endless loop unless something within the loop breaks out if it, which in this case is the BREAK command.

The #END-FILE variable contains FALSE when the file cursor is not at EOF, and a TRUE when the the file cursor is at EOF.

An alternative, which uses less lines of code and is easier to understand might look like this:

```<code>if $path != ''
  let $Archive_File = $path || 'ARCHIVE\' || $filename || $Curr_Date || '.dat'
  open $Out_File  as 1  for-reading record=450:vary status=#fileread
  open $Archive_File as 2  for-writing record=450:vary status=#filewrite
  While Not #END-FILE
    read 1 into $Current_Line:999
    write 2 from $Current_Line
  End-While
  close 1
  close 2
end-if
</code>```

Title: Assistance in understanding sqr logic

Body:
Hello, I am new to learning how to develop sqr programs within PeopleSoft. I've been going through some programs we are utilizing and wanted to see if someone could help provide clarification with what the below snippet of code is doing in this While loop.

 if $path != ''
   let $Archive_File = $path || 'ARCHIVE\' || $filename || $Curr_Date || '.dat'
   open $Out_File  as 1  for-reading record=450:vary status=#fileread
   open $Archive_File as 2  for-writing record=450:vary status=#filewrite
   While 1
     if #END-FILE
        break
     else
        read 1 into $Current_Line:999
        write 2 from $Current_Line
    end-if
 End-While
 close 1
 close 2
end-if

I'm trying to understand if the WHILE statement is evaluating the "$Out_File as 1" as the logical expression, or is 1 being evaluated as the value of the variable #END-FILE (As I understand this variable is set to either 0 or 1).

Body:
In addition to the file name, the open command takes a number as a parameter which it uses as a handler for the file. In your example, two files are being opened.

The WHILE 1 statement doesn't have anything to do with file 1. Here 1 means true, instead of 0 for false. So 1 is always true, creating an endless loop unless something within the loop breaks out if it, which in this case is the BREAK command.

The #END-FILE variable contains FALSE when the file cursor is not at EOF, and a TRUE when the the file cursor is at EOF.

An alternative, which uses less lines of code and is easier to understand might look like this:

if $path != ''
  let $Archive_File = $path || 'ARCHIVE\' || $filename || $Curr_Date || '.dat'
  open $Out_File  as 1  for-reading record=450:vary status=#fileread
  open $Archive_File as 2  for-writing record=450:vary status=#filewrite
  While Not #END-FILE
    read 1 into $Current_Line:999
    write 2 from $Current_Line
  End-While
  close 1
  close 2
end-if


来源: stackexchange

问:
Unable to disable `<li>` elements by setting `disable` property to `true`
I'm trying to make the rest of my chat room app disabled while a modal is open. I've been using element.disable = true to disable the buttons and this has worked. I have a ul where each li is the name of a chat room that is clickable and opens up its respective chat room in another container. I'm trying to disable the lis using the same disable.true method. I'm using a for loop to iterate through the array of lis, but it isn't working.

I used console.log to view the variable with the array stored in it (var lis) as well as the console.log(lis.length). The console shows that the array has a length of 5 but returns lis.length as 0.

Would be much appreciated if someone could tell me what I'm doing incorrectly.

HTML:

```<code><div class"home-template" id="home">
  <div class="rooms-container">
    <h1 class="app-title">Bloc Chat</h1>
    <ul id="rooms-list">
      <li class="room-item" id="room-item" ng-repeat="chat in home.chatRooms">
        <a href="#" class="room-link" id="{{ chat.$value }}" data-ng-click="home.getRoomName(chat.$id)">{{ chat.$value }}</a>
      </li>
    </ul>
    <button class="btn btn-warning" id="new-room-button" type="button" ng-click="home.open()">New room</button>
    <button class="btn btn-warning" id="delete-cookies-button" type="button" ng-click="home.deleteCookies()">Delete Cookie for testing</button>
  </div>
  <div class="messages-container">
    <h1 class="current-room" ng-bind="home.activeRoom"></h1>
    <ul class="messages-list">
      <li class="message-bubble" ng-repeat="message in home.messages">
        <div class="username">{{ message.username }}</div>
        <div class="sentAt">{{ message.sentAt }}</div>
        <div class="content">{{ message.content }}</div>
      </li>
    </ul>
  </div>
</div>
</code>```

JavaScript in a home controller:

```<code>home.cookieDisplay = $cookies.get('blocChatCurrentUser');
var modals = document.getElementsByClassName('modal');
var lis = document.getElementsByClassName('room-item');
var newButton = document.getElementById('new-room-button');
var delButton = document.getElementById('delete-cookies-button');
if (modals.length === 0) {
  newButton.disabled = false;
  delButton.disabled = false;
  for (var i = 0; i < lis.length; i++) {
    lis[i].disabled.false;
  }
} else if (modals.length !== 0) {
    newButton.disabled = true;
    delButton.disabled = true;
    for (var i = 0; i < lis.length; i++) {
      // lis[i].setAttribute('display', 'none');
      lis[i].disabled.true;
    }
  }
</code>```

Here's what my console looks like:

答:
You can't disable the li itself.

You can either disable the anchor tag (a) in it for example like this (refernece):

```<code>document.getElementById("tab_c").childNodes[0].onclick = function() {return false;};
</code>```

Or you can set pointer-events:noneas it has been done using CSS (reference):

```<code>.disabled {
    pointer-events:none; //This makes it not clickable
    opacity:0.6;         //This grays it out to look disabled
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to make the rest of my chat room app disabled while a modal is open. I've been using element.disable = true to disable the buttons and this has worked. I have a ul where each li is the name of a chat room that is clickable and opens up its respective chat room in another container. I'm trying to disable the lis using the same disable.true method. I'm using a for loop to iterate through the array of lis, but it isn't working.

I used console.log to view the variable with the array stored in it (var lis) as well as the console.log(lis.length). The console shows that the array has a length of 5 but returns lis.length as 0.

Would be much appreciated if someone could tell me what I'm doing incorrectly.

HTML:

Bloc Chat

        {{ chat.$value }}

    <button class="btn btn-warning" id="new-room-button" type="button" ng-click="home.open()">New room</button>
    <button class="btn btn-warning" id="delete-cookies-button" type="button" ng-click="home.deleteCookies()">Delete Cookie for testing</button>

{{ message.username }}

{{ message.sentAt }}

{{ message.content }}

JavaScript in a home controller:

home.cookieDisplay = $cookies.get('blocChatCurrentUser');
var modals = document.getElementsByClassName('modal');
var lis = document.getElementsByClassName('room-item');
var newButton = document.getElementById('new-room-button');
var delButton = document.getElementById('delete-cookies-button');
if (modals.length === 0) {
  newButton.disabled = false;
  delButton.disabled = false;
  for (var i = 0; i < lis.length; i++) {
    lis[i].disabled.false;
  }
} else if (modals.length !== 0) {
    newButton.disabled = true;
    delButton.disabled = true;
    for (var i = 0; i < lis.length; i++) {
      // lis[i].setAttribute('display', 'none');
      lis[i].disabled.true;
    }
  }

Here's what my console looks like:

Body:
You can't disable the li itself.

You can either disable the anchor tag (a) in it for example like this (refernece):

document.getElementById("tab_c").childNodes[0].onclick = function() {return false;};

Or you can set pointer-events:noneas it has been done using CSS (reference):

.disabled {
    pointer-events:none; //This makes it not clickable
    opacity:0.6;         //This grays it out to look disabled
}


问:
Send request to CMake server from the Linux command line
I would like to play around with the CMake server mode from the Linux command line. The documentation tells me to start CMake like the following:

```<code>cmake -E server (--debug|--pipe <NAMED_PIPE>)
</code>```

But for me it works only this way:

```<code>cmake -E server --experimental --debug

[== "CMake Server" ==[
{"supportedProtocolVersions":[{"isExperimental":true,"major":1,"minor":0}],"type":"hello"}
]== "CMake Server" ==]
</code>```

I tried to send a request to the server, but I get only the hello response:

```<code>cat request.txt | cmake -E server --experimental --debug
[== "CMake Server" ==[
{"supportedProtocolVersions":[{"isExperimental":true,"major":1,"minor":0}],"type":"hello"}
]== "CMake Server" ==]
</code>```

How can I send requests to the CMake server?

答:
The CMake server will be expecting messages of either --debug or --pipe mode in the following format:

```<code>[== "CMake Server" ==[
</code>```

...your message...

```<code> ]== "CMake Server" ==]
</code>```

The CMake server help page has more examples, but here is something that will help you get started.

For the following examples, I used CMake 3.10, if you are using an older version you may have to modify the "protocolVersion":{"major":1} to {"major":0}.

You'll also need to have a CMake project and know the source directory where the CMakeLists.txt file is and a build folder where the out of tree files will be placed by cmake.

If you want to try the --debug --experimental flags, the server will be expecting to get input from standard input. So right after you run cmake -E server --debug --experimental, input the following:

```<code>[== "CMake Server" ==[

{"cookie":"yummy","type":"handshake","protocolVersion":{"major":1},
    "sourceDirectory":"/path/to/CMakeList.txt","buildDirectory":"/path/to/build/folder",

"generator":"Unix Makefiles"}

]== "CMake Server" ==]
</code>```

It should respond with a bunch of information and the build folder should containt some files now.

If you want to use a named pipe instead, you'll have to use something like netcat. Using your command as an example, after running the cmake -E server --pipe=pipe --experimental in the background, you can use the following command:

```<code>nc -U pipe
</code>```

At this point, nc will be expecting input in the standard input as well, so you will be able to input the same json messages as before and get the same response.

ContentLicense: CC BY-SA 4.0

Body:
I would like to play around with the CMake server mode from the Linux command line. The documentation tells me to start CMake like the following:

cmake -E server (--debug|--pipe <NAMED_PIPE>)

But for me it works only this way:

cmake -E server --experimental --debug

[== "CMake Server" ==[
{"supportedProtocolVersions":[{"isExperimental":true,"major":1,"minor":0}],"type":"hello"}
]== "CMake Server" ==]

I tried to send a request to the server, but I get only the hello response:

cat request.txt | cmake -E server --experimental --debug
[== "CMake Server" ==[
{"supportedProtocolVersions":[{"isExperimental":true,"major":1,"minor":0}],"type":"hello"}
]== "CMake Server" ==]

How can I send requests to the CMake server?

Body:
The CMake server will be expecting messages of either --debug or --pipe mode in the following format:

[== "CMake Server" ==[

...your message...

 ]== "CMake Server" ==]

The CMake server help page has more examples, but here is something that will help you get started.

For the following examples, I used CMake 3.10, if you are using an older version you may have to modify the "protocolVersion":{"major":1} to {"major":0}.

You'll also need to have a CMake project and know the source directory where the CMakeLists.txt file is and a build folder where the out of tree files will be placed by cmake.

If you want to try the --debug --experimental flags, the server will be expecting to get input from standard input. So right after you run cmake -E server --debug --experimental, input the following:

[== "CMake Server" ==[

{"cookie":"yummy","type":"handshake","protocolVersion":{"major":1},
    "sourceDirectory":"/path/to/CMakeList.txt","buildDirectory":"/path/to/build/folder",

"generator":"Unix Makefiles"}

]== "CMake Server" ==]

It should respond with a bunch of information and the build folder should containt some files now.

If you want to use a named pipe instead, you'll have to use something like netcat. Using your command as an example, after running the cmake -E server --pipe=pipe --experimental in the background, you can use the following command:

nc -U pipe

At this point, nc will be expecting input in the standard input as well, so you will be able to input the same json messages as before and get the same response.


问:
Removing Similar Elements in Matrix
I'm trying to figure out how to remove an element of a matrix in MATLAB if it differs from any of the other elements by 0.01. I'm supposed to be using all of the unique elements of the matrix as thresholding values for a ROC curve that I'm creating but I need a way to remove values when they are within 0.01 of each other (since we are assuming they are basically equal if this is true).

And help would be greatly appreciated!

Thanks!

答: Before you use a threshold or tolerance to keep values that all close enough, you can use matlab inbuilt unique() to reduce the run. Usually, matlab tries to accelerate their inbuilts, so try to use as many inbuilts as possible.</p>

ContentLicense: CC BY-SA 2.5

Title: Removing Similar Elements in Matrix


问:
i am not able to load array from session storage in java script
I am not able to restore a created array in html and reuse it again.
I have used Json but do not work with me.
in the below code. I'm trying to reload items which is an array created in another page. when i try to load it, it did not work. how can i fix this?
does json need header file?
Thank you.</p>

```<code>$( document ).ready(function() {
    var count=sessionStorage.getItem('items');
)};
</code>```

答:
You have to convert your array to a string before setting and back again when your get the item</p>

```<code>var letters = ['a', 'b', 'c'];
sessionStorage.setItem("letters", JSON.stringify(letters));
var storedLetters = JSON.parse(sessionStorage.getItem("letters"));

console.log(storedLetters);
</code>```

Body:
I am not able to restore a created array in html and reuse it again.
I have used Json but do not work with me.
in the below code. I'm trying to reload items which is an array created in another page. when i try to load it, it did not work. how can i fix this?
does json need header file?
Thank you.

$( document ).ready(function() {
    var count=sessionStorage.getItem('items');
)};

Body:
You have to convert your array to a string before setting and back again when your get the item

var letters = ['a', 'b', 'c'];
sessionStorage.setItem("letters", JSON.stringify(letters));
var storedLetters = JSON.parse(sessionStorage.getItem("letters"));

console.log(storedLetters);


问:
Unable to compile: unrecognized relocation
I'm unable to compile anything in my linux pc. I have no idea why, probably I've installed some package and made a mess. I've uninstalled and reinstalled gcc and other packages, but no good news.. still this problem.

This is the message:

```<code>/usr/lib64/gcc/x86_64-suse-linux/4.8/../../../../x86_64-suse-
linux/bin/ld: /usr/lib64/gcc/x86_64-suse-linux/4.8/../../../../lib64/crt1.o: unrecognized relocation (0x29) in section `.text'
</code>```

Any idea of what does it mean and how to fix this problem?

cheers

答:
For anyone else that encounters this issue: I think @gabib44's problem was using a older version of ld to link a library that had been built with a newer version.

"unrecognized relocation" occurs when the relocation type is greater than the greatest known relocation type in your version of ld. 0x2a (R_X86_64_REX_GOTPCRELX) is presently the relocation type with the greatest value; I guess @gabib44's ld was old enough to not know about the relocation type before that one (0x29, R_X86_64_GOTPCRELX).

I had this problem myself when I was building a library with binutils v2.26 (which knew about relocation 0x2a) but then incorporating that library on a build machine using binutils v2.24

The fix is either to build the library that you want to link with a older version of the binutils suite, or to upgrade ld on the machine that wants to link that library.

Body:
I'm unable to compile anything in my linux pc. I have no idea why, probably I've installed some package and made a mess. I've uninstalled and reinstalled gcc and other packages, but no good news.. still this problem.

This is the message:

/usr/lib64/gcc/x86_64-suse-linux/4.8/../../../../x86_64-suse-
linux/bin/ld: /usr/lib64/gcc/x86_64-suse-linux/4.8/../../../../lib64/crt1.o: unrecognized relocation (0x29) in section `.text'

Any idea of what does it mean and how to fix this problem?

cheers


问:
How to capture old value and new value in INotifyPropertyChanged implementation of PropertyChanged event in C#
I need to capture old value, new value and property name in PropertyChanged event handler. The default implementation of INotifyPropertyChanged provides only name of the property. So after searching on internet, I found similar question here with Extended implementation of property changed.

Below is the link to that Q and interface declaration:

NotifyPropertyChanged event where event args contain the old value

```<code>public interface INotifyPropertyChangedExtended<T>
{
    event PropertyChangedExtendedEventHandler<T> PropertyChanged;
}
</code>```

public delegate void PropertyChangedExtendedEventHandler(object sender, PropertyChangedExtendedEventArgs e);

Above interface will solve my problem, however I am not understanding how to implement generic interface on my Entity class because T will change depending on data type of property.

Can anyone help me in understanding, will it be possible to implement this interface with T parameter. Sample implementation of this will be really helpful.

Thanks in advance for help.

Umesh

EDIT #1:
Based on the reply from Peter, posting updated code that may be useful for someone who wants to capture old and new values in PropertyChanged event.

```<code>    public class PropertyChangedExtendedEventArgs : PropertyChangedEventArgs
{
    public string OldValue { get; set; }

    public string NewValue { get; set; }

    public PropertyChangedExtendedEventArgs(string propertyName, string oldValue, string newValue) : base(propertyName)
    {
        OldValue = oldValue;
        NewValue = newValue;
    }
}

    //
// Summary:
//     Notifies clients that a property value has changed.
public interface INotifyPropertyChangedEnhanced
{
    //
    // Summary:
    //     Occurs when a property value changes.
    event PropertyChangedEventHandlerEnhanced PropertyChanged;
}

public delegate void PropertyChangedEventHandlerEnhanced(object sender, PropertyChangedExtendedEventArgs e);

public abstract class BindableBase : INotifyPropertyChangedEnhanced
{
    public event PropertyChangedEventHandlerEnhanced PropertyChanged;

    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName]
    string propertyName = null)
    {
        if (Equals(storage, value))
        {
            return false;
        }

        var oldValue = storage;
        storage = value;
        this.OnPropertyChanged(oldValue, value, propertyName);
        return true;
    }
    protected void OnPropertyChanged<T>(T oldValue, T newValue, [CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedExtendedEventArgs(propertyName, oldValue?.ToString(), newValue?.ToString()));
    }
}
</code>```

答:
I am not understanding how to implement generic interface on my Entity class because T will change depending on data type of property

That's correct. The answer you're looking at isn't actually all that good an answer, because it contains code that doesn't compile or make sense.

The basic idea of raising the non-generic PropertyChanged event by passing the generic args class that inherits the non-generic PropertyChangedEventArgs class is by itself okay. It should work fine in your case.

But! You're not going to be able to implement the generic interface that answer proposes, because (as you already note) the interface doesn't work when the properties have different types. In fact, the answer you're looking at wouldn't even compile with that interface, because their event-raising method is itself generic, and raises the non-generic PropertyChanged event (the method would be incompatible with the generic interface), and they don't bother to actually implement their generic interface (if they'd tried, they'd have noticed that the generic method doesn't work with the generic interface…the method's type parameter T is different from the interface's type parameter T).

It's unfortunate that highly up-voted answer was written that way. It has some useful ideas in it, but it also has completely unworkable ideas, and is going to just confuse exactly the people who are looking for an answer like that (i.e. the very people who most want to read and use the answer).

Body:
I need to capture old value, new value and property name in PropertyChanged event handler. The default implementation of INotifyPropertyChanged provides only name of the property. So after searching on internet, I found similar question here with Extended implementation of property changed.

Below is the link to that Q and interface declaration:

NotifyPropertyChanged event where event args contain the old value

public interface INotifyPropertyChangedExtended<T>
{
    event PropertyChangedExtendedEventHandler<T> PropertyChanged;
}

public delegate void PropertyChangedExtendedEventHandler(object sender, PropertyChangedExtendedEventArgs e);

Above interface will solve my problem, however I am not understanding how to implement generic interface on my Entity class because T will change depending on data type of property.

Can anyone help me in understanding, will it be possible to implement this interface with T parameter. Sample implementation of this will be really helpful.

Thanks in advance for help.

Umesh

EDIT #1:
Based on the reply from Peter, posting updated code that may be useful for someone who wants to capture old and new values in PropertyChanged event.

    public class PropertyChangedExtendedEventArgs : PropertyChangedEventArgs
{
    public string OldValue { get; set; }

    public string NewValue { get; set; }

    public PropertyChangedExtendedEventArgs(string propertyName, string oldValue, string newValue) : base(propertyName)
    {
        OldValue = oldValue;
        NewValue = newValue;
    }
}

    //
// Summary:
//     Notifies clients that a property value has changed.
public interface INotifyPropertyChangedEnhanced
{
    //
    // Summary:
    //     Occurs when a property value changes.
    event PropertyChangedEventHandlerEnhanced PropertyChanged;
}

public delegate void PropertyChangedEventHandlerEnhanced(object sender, PropertyChangedExtendedEventArgs e);

public abstract class BindableBase : INotifyPropertyChangedEnhanced
{
    public event PropertyChangedEventHandlerEnhanced PropertyChanged;

    protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName]
    string propertyName = null)
    {
        if (Equals(storage, value))
        {
            return false;
        }

        var oldValue = storage;
        storage = value;
        this.OnPropertyChanged(oldValue, value, propertyName);
        return true;
    }
    protected void OnPropertyChanged<T>(T oldValue, T newValue, [CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedExtendedEventArgs(propertyName, oldValue?.ToString(), newValue?.ToString()));
    }
}


问:
How to change the order of DataFrame columns?
I have the following DataFrame (df):

```<code>import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10, 5))
</code>```

I add more column(s) by assignment:

```<code>df['mean'] = df.mean(1)
</code>```

How can I move the column mean to the front, i.e. set it as first column leaving the order of the other columns untouched?

答:
I liked Shoresh's answer to use set functionality to remove columns when you don't know the location, however this didn't work for my purpose as I need to keep the original column order (which has arbitrary column labels).

I got this to work though by using IndexedSet from the boltons package.

I also needed to re-add multiple column labels, so for a more general case I used the following code:

```<code>from boltons.setutils import IndexedSet
cols = list(IndexedSet(df.columns.tolist()) - set(['mean', 'std']))
cols[0:0] =['mean', 'std']
df = df[cols]
</code>```

Hope this is useful to anyone searching this thread for a general solution.

Body:
I have the following DataFrame (df):

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10, 5))

I add more column(s) by assignment:

df['mean'] = df.mean(1)

How can I move the column mean to the front, i.e. set it as first column leaving the order of the other columns untouched?

Body:
I liked Shoresh's answer to use set functionality to remove columns when you don't know the location, however this didn't work for my purpose as I need to keep the original column order (which has arbitrary column labels).

I got this to work though by using IndexedSet from the boltons package.

I also needed to re-add multiple column labels, so for a more general case I used the following code:

from boltons.setutils import IndexedSet
cols = list(IndexedSet(df.columns.tolist()) - set(['mean', 'std']))
cols[0:0] =['mean', 'std']
df = df[cols]

Hope this is useful to anyone searching this thread for a general solution.


问:
Best way to compare std::strings
What is the best way to compare std::strings? The obvious way would be with if/else:

```<code>std::string input;
std::cin >> input;

if ( input == "blahblahblah" )
{
    // do something.
}

else if ( input == "blahblah" )
{
    // do something else.
}

else if ( input == "blah" )
{
    // do something else yet.
}

// etc. etc. etc.
</code>```

Another possibility is to use an std::map and a switch/case. What is the best way when doing lots (like 8, 10, 12+) of these comparisons?

答:
Here's an example using std::map.

```<code>#include <map>
#include <string>
#include <iostream>
#include <utility>

void first()
{
  std::cout << "first\n";
}

void second()
{
  std::cout << "second\n";
}

void third()
{
  std::cout << "third\n";
}

int main()
{
  typedef void(*StringFunc)();
  std::map<std::string, StringFunc> stringToFuncMap;

  stringToFuncMap.insert(std::make_pair("blah", &first));
  stringToFuncMap.insert(std::make_pair("blahblah", &second));
  stringToFuncMap.insert(std::make_pair("blahblahblah", &third));

  stringToFuncMap["blahblah"]();
  stringToFuncMap["blahblahblah"]();
  stringToFuncMap["blah"]();
}
</code>```

Output is:

```<code>second
third
first
</code>```

The benefits of this approach are:

It's easily extensible.

It forces you to break out the string-handling routines into separate functions (programming by intention).

Function lookup is O(log n), whereas your example is O(n)

Look into using boost::function to make the syntax a bit nicer, especially with class member functions.

Title: Best way to compare std::strings

Body:
What is the best way to compare std::strings? The obvious way would be with if/else:

std::string input;
std::cin >> input;

if ( input == "blahblahblah" )
{
    // do something.
}

else if ( input == "blahblah" )
{
    // do something else.
}

else if ( input == "blah" )
{
    // do something else yet.
}

// etc. etc. etc.

Another possibility is to use an std::map and a switch/case. What is the best way when doing lots (like 8, 10, 12+) of these comparisons?

Body:
Here's an example using std::map.

#include <map>
#include <string>
#include <iostream>
#include <utility>

void first()
{
  std::cout << "first\n";
}

void second()
{
  std::cout << "second\n";
}

void third()
{
  std::cout << "third\n";
}

int main()
{
  typedef void(*StringFunc)();
  std::map<std::string, StringFunc> stringToFuncMap;

  stringToFuncMap.insert(std::make_pair("blah", &first));
  stringToFuncMap.insert(std::make_pair("blahblah", &second));
  stringToFuncMap.insert(std::make_pair("blahblahblah", &third));

  stringToFuncMap["blahblah"]();
  stringToFuncMap["blahblahblah"]();
  stringToFuncMap["blah"]();
}

Output is:

second
third
first

The benefits of this approach are:

It's easily extensible.

It forces you to break out the string-handling routines into separate functions (programming by intention).

Function lookup is O(log n), whereas your example is O(n)

Look into using boost::function to make the syntax a bit nicer, especially with class member functions.


问:
How do I check if array contains at least one empty value?
Here is my array ouput

```<code>Array
(
    [1] => 1
    [2] => 2
    [3] =>
)
</code>```

How do I know the [3] => is empty?

```<code>foreach ($array as $key => $value) {
    if (empty($value))
        echo "$key empty <br/>";
    else
        echo "$key not empty <br/>";
}
</code>```

My out put showing all is not empty. What is correct way to check is empty?

答:
For a different task, when you need to tell if ALL array values are empty, you can use the following:</p>
```<code>if (array_filter($array)) {
    echo 'OK';
} else {
    echo 'EMPTY ARRAY';
}
</code>```

Body:
Here is my array ouput

Array
(
    [1] => 1
    [2] => 2
    [3] =>
)

How do I know the [3] => is empty?

foreach ($array as $key => $value) {
    if (empty($value))
        echo "$key empty
";
    else
        echo "$key not empty
";
}

My out put showing all is not empty. What is correct way to check is empty?

Body:
For a different task, when you need to tell if ALL array values are empty, you can use the following:

if (array_filter($array)) {
    echo 'OK';
} else {
    echo 'EMPTY ARRAY';
}


答:
The sessionStorageproperty allows you to access a session Storage object for the current origin.It is two way process first of all stringifyobject before storing to session and second  parseto getting back .

```<code>     var user = {'name':'John'};
     sessionStorage['user'] = JSON.stringify(user);
     console.log(sessionStorage['user']);
     var obj = JSON.parse(sessionStorage['user']);
     console.log(Object.keys(obj).length);
</code>```

Here is fiddle.Opening a page in a new tab or window will cause a new session to be initiated.
More About session storage.

Title: i am not able to load array from session storage in java script

Body:
The sessionStorageproperty allows you to access a session Storage object for the current origin.It is two way process first of all stringifyobject before storing to session and second  parseto getting back .

     var user = {'name':'John'};
     sessionStorage['user'] = JSON.stringify(user);
     console.log(sessionStorage['user']);
     var obj = JSON.parse(sessionStorage['user']);
     console.log(Object.keys(obj).length);

Here is fiddle.Opening a page in a new tab or window will cause a new session to be initiated.
More About session storage.


问:
Android Device Monitor not found JDK Path
I'm using Arch Linux with Gnome.

I open Android Studio by the desktop item. The code editor works fine, the device manager starts correctly and the app run like a charm, but when I try to open the Device Monitor, I get this error:

A Java Runtime Environment (JRE) or Java Development Kit (JDK)
  must be available in order to run Monitor. No Java virtual machine
  was found after searching the following locations:
  /home/grams/Android/Sdk/tools/lib/monitor-x86_64/jre/bin/java
  java in your current PATH
  When i run the android studion from command line, the Device Monitor works.

Here is the .desktop content

```<code>#!/usr/bin/env xdg-open
[Desktop Entry]
Version=1.0
Type=Application
Terminal=false
Icon[en_US]=/home/grams/android-studio/bin/studio.png
Name[en_US]=Android Studio
Exec=/home/grams/android-studio/bin/studio.sh
Comment[en_US]=Android Studio IDE
Name=Android Studio
Comment=Android Studio IDE
Icon=/home/grams/android-studio/bin/studio.png
</code>```

My JRE and JDK variables are being added on /etc/profile.
When i run Android Studio on the command line, this error not occurs. Maybe it is a problem with Gnome launcher ?

答:
Newest Android Studio Bundle comes with its own JRE (under <ANDROID_STUDIO>/jre and this is the recommended JRE to work with (look at File / Project Structure / SDK Location).

Likewise, a simple option is to create a symbolic link under the monitor tools to keep JRE in line with Android Studio even getting an update.

For MAC or Linux:

```<code>#ln -s <ANDROID_STUDIO>/jre <SDK>/tools/lib/monitor-x86_64/jre
</code>```

32 bits:

```<code>#ln -s <ANDROID_STUDIO>/jre <SDK>/tools/lib/monitor-x86/jre
</code>```

Then the ddms monitor works for both ways:  from Studio IDE (Tools / Android / ADM) or command line  (<SDK>tools/./monitor)

Body:
I'm using Arch Linux with Gnome.

I open Android Studio by the desktop item. The code editor works fine, the device manager starts correctly and the app run like a charm, but when I try to open the Device Monitor, I get this error:

A Java Runtime Environment (JRE) or Java Development Kit (JDK)
  must be available in order to run Monitor. No Java virtual machine
  was found after searching the following locations:
  /home/grams/Android/Sdk/tools/lib/monitor-x86_64/jre/bin/java
  java in your current PATH
  When i run the android studion from command line, the Device Monitor works.

Here is the .desktop content

#!/usr/bin/env xdg-open
[Desktop Entry]
Version=1.0
Type=Application
Terminal=false
Icon[en_US]=/home/grams/android-studio/bin/studio.png
Name[en_US]=Android Studio
Exec=/home/grams/android-studio/bin/studio.sh
Comment[en_US]=Android Studio IDE
Name=Android Studio
Comment=Android Studio IDE
Icon=/home/grams/android-studio/bin/studio.png

My JRE and JDK variables are being added on /etc/profile.
When i run Android Studio on the command line, this error not occurs. Maybe it is a problem with Gnome launcher ?

Body:
Newest Android Studio Bundle comes with its own JRE (under <ANDROID_STUDIO>/jre and this is the recommended JRE to work with (look at File / Project Structure / SDK Location).

Likewise, a simple option is to create a symbolic link under the monitor tools to keep JRE in line with Android Studio even getting an update.

For MAC or Linux:

#ln -s <ANDROID_STUDIO>/jre <SDK>/tools/lib/monitor-x86_64/jre

32 bits:

#ln -s <ANDROID_STUDIO>/jre <SDK>/tools/lib/monitor-x86/jre

Then the ddms monitor works for both ways:  from Studio IDE (Tools / Android / ADM) or command line  (<SDK>tools/./monitor)


问:
html pattern to parse in php
i have a following pattern, inside the html file, that i would like to parse in php to get a link but for now i dont see a solution as i am trying to use QueryPath and my case is simply not a common dom element:

```<code><script>
to.addVariable("site_name","http://www.sitename.com");
</script>
</code>```

I just would like to return a link part of that pattern in order to print it.

Hope someone could recommend how to.
Thank you.

UPDATE: I would like to get http://www.sitename.com as a value from the code above using php, maybe with phpQuery or QueryPath.

答:
Try this regular exp:

```<code>$regex = '#to\.addVariable\("(.+?)", "(.+?)"\)#';
</code>```

Then, use preg_match_all to get the matches. If you want to check that the URL is an actual URL, the get any regular expression to match URLs and place it in the second .+?, these patterns will match anything between "", so you should check that you have what you need unless you trust the source.

NOTE: I'm not so sure that " doesn't needs to be escaped in regex, so check it out

Hope I can help!
If you don't understand something drop a comment!

Title: html pattern to parse in php

Body:
i have a following pattern, inside the html file, that i would like to parse in php to get a link but for now i dont see a solution as i am trying to use QueryPath and my case is simply not a common dom element:

I just would like to return a link part of that pattern in order to print it.

Hope someone could recommend how to.
Thank you.

UPDATE: I would like to get http://www.sitename.com as a value from the code above using php, maybe with phpQuery or QueryPath.

Body:
Try this regular exp:

$regex = '#to\.addVariable\("(.+?)", "(.+?)"\)#';

Then, use preg_match_all to get the matches. If you want to check that the URL is an actual URL, the get any regular expression to match URLs and place it in the second .+?, these patterns will match anything between "", so you should check that you have what you need unless you trust the source.

NOTE: I'm not so sure that " doesn't needs to be escaped in regex, so check it out

Hope I can help!
If you don't understand something drop a comment!


问:
Root directory in package.json
My question concerns an existing library that I wish to publish as an NPM module. The library is already in use, and currently required via the local file system.

How can I specify the root directory of my module's files?

If I have a structure like:

```<code>.
├── package.json
├── src
|   ├── js
|   └────── lib
|   └───────── my
|   └───────────── thing.js
|   └───────────── that.js
</code>```

How do I specify that the root of my module, and accessible files is src/js/lib/my/?

I would like to use as follows from an outside project:

```<code>var thing = require('my/thing'),
    that = require('my/that');
</code>```

I saw the "files" property in package.json, is this the right way to go?

答:
In webpack, you can specify resolve.alias like this:

```<code>{
  resolve: {
    alias: {
      'my': 'my/src'
    }
  }
}
</code>```

or you can specify directions option in package.json

```<code>{
  directions: {
    'lib': 'src/lib'
  }
}
</code>```

Title: Root directory in package.json

Body:
My question concerns an existing library that I wish to publish as an NPM module. The library is already in use, and currently required via the local file system.

How can I specify the root directory of my module's files?

If I have a structure like:

.
├── package.json
├── src
|   ├── js
|   └────── lib
|   └───────── my
|   └───────────── thing.js
|   └───────────── that.js

How do I specify that the root of my module, and accessible files is src/js/lib/my/?

I would like to use as follows from an outside project:

var thing = require('my/thing'),
    that = require('my/that');

I saw the "files" property in package.json, is this the right way to go?

Body:
In webpack, you can specify resolve.alias like this:

{
  resolve: {
    alias: {
      'my': 'my/src'
    }
  }
}

or you can specify directions option in package.json

{
  directions: {
    'lib': 'src/lib'
  }
}


问:
Maximum execution time of 0 seconds in Collection reduce method
In the past week, I started to receive the following message in the Laravel log, but there is nothing else on my stacktrace to give me any clue of what is going on. Any idea of what this could happen?

```<code>[2017-11-30 19:40:05] production.ERROR: Maximum execution time of 0 seconds exceeded {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalErrorException(code: 1): Maximum execution time of 0 seconds exceeded at /var/www/html/app/vendor/laravel/framework/src/Illuminate/Support/Collection.php:1201)
    [stacktrace]
    #0 {main}
    "}
</code>```

I'm currently using Laravel 5.5 and PHP 7.1.

答: I managed to solve the issue. I checked Apache error logs, and it showed me the URL where the error was and from that point, I was able to review what happened. And it was bug in our implementation that was causing a weird iteration that took a lot of time. Now, it's solved.</p>

Body:
In the past week, I started to receive the following message in the Laravel log, but there is nothing else on my stacktrace to give me any clue of what is going on. Any idea of what this could happen?

[2017-11-30 19:40:05] production.ERROR: Maximum execution time of 0 seconds exceeded {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalErrorException(code: 1): Maximum execution time of 0 seconds exceeded at /var/www/html/app/vendor/laravel/framework/src/Illuminate/Support/Collection.php:1201)
    [stacktrace]
    #0 {main}
    "}

I'm currently using Laravel 5.5 and PHP 7.1.


问:
builtins.ImportError: cannot import name 'choices'

I am trying to import choices from the random library in python but I get an error.

```<code>from tkinter import *
from itertools import accumulate
from random import choices
from string import ascii_lowercase
</code>```

I get the error that says
    File "c:\Users\coope\Downloads\hw3.py", line 26, in
    from random import choices
builtins.ImportError: cannot import name 'choices'

答:
Upgrade your python version. The random.choices() function was introduced in Python 3.6.

Quoting from the Library Documentation

random.choices(population, weights=None, *, cum_weights=None, k=1)

Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.

Compared to random.choice, the function random.choices returns not a single element but a k-sized list.

Body:
I am trying to import choices from the random library in python but I get an error.

from tkinter import *
from itertools import accumulate
from random import choices
from string import ascii_lowercase

I get the error that says
    File "c:\Users\coope\Downloads\hw3.py", line 26, in
    from random import choices
builtins.ImportError: cannot import name 'choices'


问:
How to pause or continue Foreach php
This is my code,

```<code>        <?php $i=1; foreach($xls as $xls): ?>
        <tr>
            <td><?php echo $i; ?></td>
            <td><?php echo $xls->jenis; ?></td>
            <td><?php echo $xls->user; ?></td>
            <td><?php echo $xls->nama; ?></td>
            <td><?php echo $xls->unit; ?></td>
            <?php if (is_array($jawab) || is_object($jawab)){ ?>
        <?php if(isset($jawab)) {?>
        <?php $limit=0;?>
        <?php foreach($jawab as $row): ?>
            <td><?php echo $row['ket_jawaban']; ?></td>
        <?php $limit++;  if($limit==2) break;  endforeach; }} ?>

        </tr>
        <?php $i++; endforeach; ?>
</tbody>
</code>```

How do I  make each print 2 lines from foreach 2nd move to the bottom line (tr)

OK, with explanation:

The above code prints like this:

But I want to print like this:

答:
It's simple. Change the name of one of your $jawab variables in the foreach loop.

```<code><?php foreach($jawab as $jawab): ?>
</code>```

And NEVER repeat a variable name in a loop.

UPDATE:

Try to change your loop:

```<code><?php $limit=0;?>
<?php foreach($jawab as $row): ?>
    <td><?php echo $row['ket_jawaban']; ?></td>
<?php $limit++;  if($limit==2) break;  endforeach; }} ?>
</code>```

to:

```<code><td><?php echo $jawab[i*2]['ket_jawaban']; ?></td>
<td><?php echo $jawab[i*2-1]['ket_jawaban']; ?></td>
</code>```

Title: How to pause or continue Foreach php

Body:
This is my code,

        <?php $i=1; foreach($xls as $xls): ?>

            <?php echo $i; ?>
            <?php echo $xls->jenis; ?>
            <?php echo $xls->user; ?>
            <?php echo $xls->nama; ?>
            <?php echo $xls->unit; ?>
            <?php if (is_array($jawab) || is_object($jawab)){ ?>
        <?php if(isset($jawab)) {?>
        <?php $limit=0;?>
        <?php foreach($jawab as $row): ?>
            <?php echo $row['ket_jawaban']; ?>
        <?php $limit++;  if($limit==2) break;  endforeach; }} ?>

        <?php $i++; endforeach; ?>

How do I  make each print 2 lines from foreach 2nd move to the bottom line (tr)

OK, with explanation:

The above code prints like this:

But I want to print like this:

Body:
It's simple. Change the name of one of your $jawab variables in the foreach loop.

<?php foreach($jawab as $jawab): ?>

And NEVER repeat a variable name in a loop.

UPDATE:

Try to change your loop:

<?php $limit=0;?>
<?php foreach($jawab as $row): ?>
    <td><?php echo $row['ket_jawaban']; ?></td>
<?php $limit++;  if($limit==2) break;  endforeach; }} ?>

to:

<td><?php echo $jawab[i*2]['ket_jawaban']; ?></td>
<td><?php echo $jawab[i*2-1]['ket_jawaban']; ?></td>


问:
How to repeat a "block" in a django template
I want to use the same {% block %} twice in the same django template. I want this block to appear more than once in my base template:

```<code># base.html
<html>
    <head>
        <title>{% block title %}My Cool Website{% endblock %}</title>
    </head>
    <body>
        <h1>{% block title %}My Cool Website{% endblock %}</h1>
    </body>
</html>
</code>```

And then extend it:

```<code># blog.html
{% extends 'base.html' %}
{% block title %}My Blog{% endblock %}

# pictures.html
{% extends 'base.html' %}
{% block title %}My Pictures{% endblock %}

# cats.html
{% extends 'base.html' %}
{% block title %}My Cats{% endblock %}
</code>```

I will get an exception, as Django wants the block to appear only once:

TemplateSyntaxError at /

'block' tag with name 'title' appears
  more than once

A quick and dirty solution would be duplicating the block title into title1 and title2:

```<code># blog.html
{% extends 'base.html' %}
{% block title1 %}My Blog{% endblock %}
{% block title2 %}My Blog{% endblock %}
</code>```

But this is a violation of the DRY principle. It would be very difficult as I have a lot of inheriting templates, and also because I don't wanna go to hell ;-)

Is there any trick or work-around to this problem? How can I repeat the same block in my template, without duplicating all the code?

答:
There are some discussion here:
http://code.djangoproject.com/ticket/4529
Obviously django core team reject this ticket because they think this is not a common used scenario, however I disagree.

repeat block is simple and clean implementation for this:
https://github.com/SmileyChris/django-repeatblock

template macros is another one, however the author mentioned it's not carefully tested:
http://www.djangosnippets.org/snippets/363/

I used repeatblock.

OwnerDisplayName: DZPM

Body:
I want to use the same {% block %} twice in the same django template. I want this block to appear more than once in my base template:

# base.html

        <title>{% block title %}My Cool Website{% endblock %}</title>

{% block title %}My Cool Website{% endblock %}

And then extend it:

# blog.html
{% extends 'base.html' %}
{% block title %}My Blog{% endblock %}

# pictures.html
{% extends 'base.html' %}
{% block title %}My Pictures{% endblock %}

# cats.html
{% extends 'base.html' %}
{% block title %}My Cats{% endblock %}

I will get an exception, as Django wants the block to appear only once:

TemplateSyntaxError at /

'block' tag with name 'title' appears
  more than once

A quick and dirty solution would be duplicating the block title into title1 and title2:

# blog.html
{% extends 'base.html' %}
{% block title1 %}My Blog{% endblock %}
{% block title2 %}My Blog{% endblock %}

But this is a violation of the DRY principle. It would be very difficult as I have a lot of inheriting templates, and also because I don't wanna go to hell ;-)

Is there any trick or work-around to this problem? How can I repeat the same block in my template, without duplicating all the code?


答:
choices is available only on python3 and not in python2. So if you want to use choices, make sure you run your code in Python 3.x.

Here's a way to check if choices is present in python (2 or 3):

```<code>>>> import random
>>> dir(random)
</code>```

Edit: As pointed out by Dmitri, it is only available in python3.6!

Title: builtins.ImportError: cannot import name 'choices'

Body:
choices is available only on python3 and not in python2. So if you want to use choices, make sure you run your code in Python 3.x.

Here's a way to check if choices is present in python (2 or 3):

>>> import random
>>> dir(random)

Edit: As pointed out by Dmitri, it is only available in python3.6!


问:
Get the records using left join
I try to get the records from opportunity that created manually, so it means it’s not created via Converted from Leads or other module.

I’m trying to do is to get the opportunity record that is not converted from leads.

Below, you will see my query using left join the leads to opportunity using
 opportunity id from leads table and the opportunity id from Opportunity table.

But whenever I try to run this query it doesn’t show the records that created manually in the opportunity,
 I just want to get the records that are not converted and created manually in the opportunities. May I know why it is not showing? Thanks guys.

```<code>$strQuery = " SELECT
                *
             FROM
                leads l
            LEFT JOIN
                opportunities O
            ON
                l.opportunity_id = O.id
            WHERE
                l.deleted = '0'
            AND
                O.deleted = '0'
            AND
                l.converted = '0'
            AND
                DATE_FORMAT(O.date_created, '%y-%m-%d') = CURDATE()";
//
$hQuery = $db->query($strQuery);
//
while ( $arRow = $db->fetchByAssoc($hQuery) ){

// My logic
}
</code>```

答:
I just want to get the records that are not converted and created manually in the opportunities

You may need to reverse the table relationships, e.g.

```<code>SELECT *
FROM opportunities O
LEFT JOIN leads l ON O.id = l.opportunity_id
WHERE l.opportunity_id IS NULL
AND O.deleted = '0'
AND DATE_FORMAT(O.date_created, '%y-%m-%d') = CURDATE()
</code>```

here there is no assocated "lead", just an "opportunity".

Title: Get the records using left join

Body:
I try to get the records from opportunity that created manually, so it means it’s not created via Converted from Leads or other module.

I’m trying to do is to get the opportunity record that is not converted from leads.

Below, you will see my query using left join the leads to opportunity using
 opportunity id from leads table and the opportunity id from Opportunity table.

But whenever I try to run this query it doesn’t show the records that created manually in the opportunity,
 I just want to get the records that are not converted and created manually in the opportunities. May I know why it is not showing? Thanks guys.

$strQuery = " SELECT
                *
             FROM
                leads l
            LEFT JOIN
                opportunities O
            ON
                l.opportunity_id = O.id
            WHERE
                l.deleted = '0'
            AND
                O.deleted = '0'
            AND
                l.converted = '0'
            AND
                DATE_FORMAT(O.date_created, '%y-%m-%d') = CURDATE()";
//
$hQuery = $db->query($strQuery);
//
while ( $arRow = $db->fetchByAssoc($hQuery) ){

// My logic
}

Body:
I just want to get the records that are not converted and created manually in the opportunities

You may need to reverse the table relationships, e.g.

SELECT *
FROM opportunities O
LEFT JOIN leads l ON O.id = l.opportunity_id
WHERE l.opportunity_id IS NULL
AND O.deleted = '0'
AND DATE_FORMAT(O.date_created, '%y-%m-%d') = CURDATE()

here there is no assocated "lead", just an "opportunity".


问:
console log if checkbox has been checked?
Im having trouble getting the console to log when the checkbox has been selected or not.

HTML:

```<code><label class="container">
   <input type="checkbox" class="checkbox1">
      <span class="checkmark"></span>
</label>
</code>```

JS:

```<code>function carDealer () {

        if (document.getElementsByClassName('checkbox1').checked == true) {
            console.log('true');

            } else {
                console.log('false');
            }
    }
    carDealer();
</code>```

答:
getElementsByClassName returns array like object, so please replace

```<code>document.getElementsByClassName('checkbox1').checked == true
</code>```

to

```<code>document.getElementsByClassName('checkbox1')[0].checked == true
</code>```

Body:
Im having trouble getting the console to log when the checkbox has been selected or not.

HTML:

   <input type="checkbox" class="checkbox1">

JS:

function carDealer () {

        if (document.getElementsByClassName('checkbox1').checked == true) {
            console.log('true');

            } else {
                console.log('false');
            }
    }
    carDealer();

Body:
getElementsByClassName returns array like object, so please replace

document.getElementsByClassName('checkbox1').checked == true

to

document.getElementsByClassName('checkbox1')[0].checked == true


问:
How to start Spyder IDE on Windows
I downloaded spyder using the

pip install spyder

in my windows 10 32-bit operating system, but i dont see any desktop icons or exe files to start running the IDE. I downloaded spyder 3, any my python is 3.6.
I even tried creating a shortcut of spyder.exe from the Python3.6/Scripts folder, but it won't open.

答:
Try the command spyder3
If you check the scripts folder you'll find spyder3.exe

Title: How to start Spyder IDE on Windows


问:
ORACLE - After trigger is not passing the value to the procedure
I have a problem with a "after insert" trigger which won't pass the value to a stored procedure that i'm calling inside the trigger.
It works ok for update and also i should mention that i am querying the table in the procedure that i am calling.
It goes something like:

```<code>create or replace trigger test_trg
after insert or update on table1
for each row
begin
    test_procedure(:new.value1);
end;
</code>```

The procedure looks inside table1 and inserts in table2 hints about what should be added in table1 based on the current inserted/updated row.

Thanks in advance!!

答:
A trigger transaction is depend on its statement transaction. Therefore you can not read uncommitted records. So you should transfer "test_procedure" codes into your trigger and  use :New record values to insert data into table2.
Your code should look like this:</p>

```<code>create or replace trigger test_trg
after insert or update on table1
for each row
begin
    if inserting then
      insert into table2(ID, F1, F2, ...)
      values (NEW_ID_VALUE, :NEW.F1_VALUE, :NEW.F2_VALUE, ...);
    elsif updating then
      update table2
      set  F1 = :NEW.F1_VALUE
         , F2 = :NEW.F2_VALUE
      where TABLE1_ID_FK = :NEW.ID;
    end if;
end;
</code>```

Body:
I have a problem with a "after insert" trigger which won't pass the value to a stored procedure that i'm calling inside the trigger.
It works ok for update and also i should mention that i am querying the table in the procedure that i am calling.
It goes something like:

create or replace trigger test_trg
after insert or update on table1
for each row
begin
    test_procedure(:new.value1);
end;

The procedure looks inside table1 and inserts in table2 hints about what should be added in table1 based on the current inserted/updated row.

Thanks in advance!!

Body:
A trigger transaction is depend on its statement transaction. Therefore you can not read uncommitted records. So you should transfer "test_procedure" codes into your trigger and  use :New record values to insert data into table2.
Your code should look like this:

create or replace trigger test_trg
after insert or update on table1
for each row
begin
    if inserting then
      insert into table2(ID, F1, F2, ...)
      values (NEW_ID_VALUE, :NEW.F1_VALUE, :NEW.F2_VALUE, ...);
    elsif updating then
      update table2
      set  F1 = :NEW.F1_VALUE
         , F2 = :NEW.F2_VALUE
      where TABLE1_ID_FK = :NEW.ID;
    end if;
end;


问:
C# Error while getting data from a web page
Receiving this error: System.Net.WebException: 'The remote server returned an error: (400) Bad Request.' Yet I can still access the data in a web browser.

WebClient client = new WebClient();
            String downloadedString = client.DownloadString("https://api.gdax.com/products/LTC-USD/book/");

答:
Your path is wrong. It must  be with file name at the end. See below:</p>

```<code>https://api.gdax.com/products/LTC-USD/book/index.html or default.aspx
</code>```

Body:
Your path is wrong. It must  be with file name at the end. See below:

https://api.gdax.com/products/LTC-USD/book/index.html or default.aspx


问:
AppleScript to open named terminal window
I have two windows/tabs set up to run in Terminal.app, "syd" and "mel".  i.e. in Shell | New Window, "syd" and "mel" are listed.  How can I open these terminal configurations with AppleScript?</p>

答:
A few weeks ago, I migrated a new Snow Leopard (10.6) machine from a Tiger (10.4) machine. Tiger’s Terminal stored its settings in “.term“ files (usually in ~/Library/Application Support/Terminal/, but they could be saved/moved anywhere); Snow Leopard’s Terminal centralized its settings into its preference file.

Prior to migrating to Snow Leopard a part of one of my normal workflows was using Finder to double click on a saved “.term” file to open a Terminal window with a preset size and initial command. Today, I noticed that each time I did this Terminal was creating a duplicate “settings set”. So, I started looking for a way to start a saved setting that did not involve opening a “.term” file (so that the duplicate settings would not pile up); AppleScript was my first stop since I have had a bit of experience with it before.

In short, there seems to be no direct way to start a new window/tab with a particular “settings set” via Terminal’s AppleScript commands. The usual approach would be to do something involving make new window (or make new tab), but I could not find a variation that Terminal would accept. I came up with three alternate solutions (the last is the best, in my opinion).

Create a Window, Then Change Settings

If your settings do not involve an initial command or a different size from your default settings (e.g. only color/keyboard/behavioral settings are different from the default), you could use Terminal’s do script command (without a “text“ parameter) to create a new new window and then change its settings set to the one you wanted.

```<code>tell application "Terminal"
    set newTab to do script -- create a new window with no initial command
    set current settings of newTab to settings set "Grass"
end tell
</code>```

This might work for you, but it was not appropriate for my needs, so I continued my search.

Terminal’s default settings

Next, I looked to the default settings property. I thought it would be possible to temporarily change which setting is the default, create a new window, then reset the default setting. This approach was eventually successful, but it turned out to be quite ugly (besides the ugliness of the temporary change to the defaults).

I used System Events’ keystroke command to send a ⌘N to Terminal to create the new window. It turns out that Terminal is sometimes a bit slow to create the new window and my script would end up reseting the default before Terminal had a chance to use the temporary value the earlier part of the script had arranged. do script would have been synchronous, but it would also nullify any initial command saved as a part of the settings. I ended up resorting to counting the number of windows before the ⌘N and waiting for the number of windows to increase. If the launched command results in a very quick opening and closing of a window, there is a chance that this loop could get stuck. I could limited the iterations, but by this point I was quite disappointed with the overall flavor of the code (though I did go ahead and extend it to allow for new tabs instead of just windows).

```<code>to newTerminal(settingSetName, asTab)
    tell application "Terminal"
        if asTab is true then
            set countRef to a reference to tabs of first window
            set newKey to "t"
        else
            set countRef to a reference to windows
            set newKey to "n"
        end if
        set originalDefault to name of default settings
        set default settings to settings set settingSetName
    end tell
    try
        set initialCount to count of countRef
        tell application "System Events"
            -- keystrokes always go to the frontmost application
            set frontmost of application process "Terminal" to true
            keystroke newKey using command down
        end tell
        repeat until (count of countRef) > initialCount
            beep
            delay 0.1
        end repeat

        tell application "Terminal" to set default settings to settings set originalDefault
    on error m number n
        try
            tell application "Terminal" to set default settings to settings set originalDefault
        end try
        error m number n
    end try
end newTerminal

newTerminal("Grass", false)
</code>```

Click a Menu Item via System Events

With System Events, there is a way to directly activate the menu items Shell > New Tab and Shell > New Window. This requires that “access for assistive devices” is enabled (near the bottom of the Universal Access preference pane; I usually have it enabled because the GUI scripting that can then be done via System Events is often the only (good) way to accomplish some automation tasks). Although the prior variation also uses System Events, its very limited use does not require “access for assistive devices”.

```<code>(* makeNewTerminal(settingsSetName, asTab)

    Bring Terminal.app to the front and
        click the menu item named <settingsSetName>.
        If <asTab> is true, then use the menu item under Shell > New Tab,
            otherwise use the menu item under Shell > New Window
*)
to makeNewTerminal(settingsSetName, asTab)
    tell application "Terminal" to launch
    if asTab is true then
        set submenuName to "New Tab"
    else
        set submenuName to "New Window"
    end if
    tell application "System Events"
        set terminal to application process "Terminal"
        set frontmost of terminal to true
        click menu item settingsSetName of ¬
            first menu of menu item submenuName of ¬
            first menu of menu bar item "Shell" of ¬
            first menu bar of terminal
    end tell
end makeNewTerminal

makeNewTerminal("Grass", true)
</code>```

This approach literally automates the selection and activation of one of the menu items from the Shell menu. It does require “access for assistive devices”, but the code is much simpler and has fewer problematic areas (the major issue with this code is localization).

Body:
A few weeks ago, I migrated a new Snow Leopard (10.6) machine from a Tiger (10.4) machine. Tiger’s Terminal stored its settings in “.term“ files (usually in ~/Library/Application Support/Terminal/, but they could be saved/moved anywhere); Snow Leopard’s Terminal centralized its settings into its preference file.

Prior to migrating to Snow Leopard a part of one of my normal workflows was using Finder to double click on a saved “.term” file to open a Terminal window with a preset size and initial command. Today, I noticed that each time I did this Terminal was creating a duplicate “settings set”. So, I started looking for a way to start a saved setting that did not involve opening a “.term” file (so that the duplicate settings would not pile up); AppleScript was my first stop since I have had a bit of experience with it before.

In short, there seems to be no direct way to start a new window/tab with a particular “settings set” via Terminal’s AppleScript commands. The usual approach would be to do something involving make new window (or make new tab), but I could not find a variation that Terminal would accept. I came up with three alternate solutions (the last is the best, in my opinion).

Create a Window, Then Change Settings

If your settings do not involve an initial command or a different size from your default settings (e.g. only color/keyboard/behavioral settings are different from the default), you could use Terminal’s do script command (without a “text“ parameter) to create a new new window and then change its settings set to the one you wanted.

tell application "Terminal"
    set newTab to do script -- create a new window with no initial command
    set current settings of newTab to settings set "Grass"
end tell

This might work for you, but it was not appropriate for my needs, so I continued my search.

Terminal’s default settings

Next, I looked to the default settings property. I thought it would be possible to temporarily change which setting is the default, create a new window, then reset the default setting. This approach was eventually successful, but it turned out to be quite ugly (besides the ugliness of the temporary change to the defaults).

I used System Events’ keystroke command to send a ⌘N to Terminal to create the new window. It turns out that Terminal is sometimes a bit slow to create the new window and my script would end up reseting the default before Terminal had a chance to use the temporary value the earlier part of the script had arranged. do script would have been synchronous, but it would also nullify any initial command saved as a part of the settings. I ended up resorting to counting the number of windows before the ⌘N and waiting for the number of windows to increase. If the launched command results in a very quick opening and closing of a window, there is a chance that this loop could get stuck. I could limited the iterations, but by this point I was quite disappointed with the overall flavor of the code (though I did go ahead and extend it to allow for new tabs instead of just windows).

to newTerminal(settingSetName, asTab)
    tell application "Terminal"
        if asTab is true then
            set countRef to a reference to tabs of first window
            set newKey to "t"
        else
            set countRef to a reference to windows
            set newKey to "n"
        end if
        set originalDefault to name of default settings
        set default settings to settings set settingSetName
    end tell
    try
        set initialCount to count of countRef
        tell application "System Events"
            -- keystrokes always go to the frontmost application
            set frontmost of application process "Terminal" to true
            keystroke newKey using command down
        end tell
        repeat until (count of countRef) > initialCount
            beep
            delay 0.1
        end repeat

        tell application "Terminal" to set default settings to settings set originalDefault
    on error m number n
        try
            tell application "Terminal" to set default settings to settings set originalDefault
        end try
        error m number n
    end try
end newTerminal

newTerminal("Grass", false)

Click a Menu Item via System Events

With System Events, there is a way to directly activate the menu items Shell > New Tab and Shell > New Window. This requires that “access for assistive devices” is enabled (near the bottom of the Universal Access preference pane; I usually have it enabled because the GUI scripting that can then be done via System Events is often the only (good) way to accomplish some automation tasks). Although the prior variation also uses System Events, its very limited use does not require “access for assistive devices”.

(* makeNewTerminal(settingsSetName, asTab)

    Bring Terminal.app to the front and
        click the menu item named <settingsSetName>.
        If <asTab> is true, then use the menu item under Shell > New Tab,
            otherwise use the menu item under Shell > New Window
*)
to makeNewTerminal(settingsSetName, asTab)
    tell application "Terminal" to launch
    if asTab is true then
        set submenuName to "New Tab"
    else
        set submenuName to "New Window"
    end if
    tell application "System Events"
        set terminal to application process "Terminal"
        set frontmost of terminal to true
        click menu item settingsSetName of ¬
            first menu of menu item submenuName of ¬
            first menu of menu bar item "Shell" of ¬
            first menu bar of terminal
    end tell
end makeNewTerminal

makeNewTerminal("Grass", true)

This approach literally automates the selection and activation of one of the menu items from the Shell menu. It does require “access for assistive devices”, but the code is much simpler and has fewer problematic areas (the major issue with this code is localization).


问:
how to calculate binomial coefficents with non-integer numbers
I know how to calculate binomial coefficients for choose(5,2), but now I want to know if there is a function that I can calculate choose(5,2.1) in python or R programming language?</p>

答:
Use the gamma function from scipy and the extended definition of the binomial coefficient.</p>

```<code>>>> from scipy.special import gamma
>>> def choose(x,y):
...     return gamma(x+1)/(gamma(y+1)*gamma(x-y+1))
...
>>> choose(5,2.1)
10.304042688575837
</code>```

Body:
Use the gamma function from scipy and the extended definition of the binomial coefficient.

>>> from scipy.special import gamma
>>> def choose(x,y):
...     return gamma(x+1)/(gamma(y+1)*gamma(x-y+1))
...
>>> choose(5,2.1)
10.304042688575837


问:
Chrome.storage.sync.get() seems to be duplicating keys?
I am saving some settings using the following sequence

```<code>var getSettings = async function() {

    var settings;
    try {
        settings = await authenticatedGET(server_url + SETTINGS_ENDPOINT);
        return settings;
    } catch (error) {
        console.log("Settings Fetch Failed: " + error);
        throw new Error(error);
    }
}

const setLocalSettings = function(settings) {
    chrome.storage.sync.set({ 'LML_Settings': JSON.parse(settings) }, function() {
        console.log("Settings saved locally");
    });
}
</code>```

At the line right after the setLocalSettings function definition, the 'settings' object logs out as
{"email_format":"individual","close_tab":true,"frequency":"DAILY"} (correctly as intended).  When I go to fetch the settings using this sequence:

```<code>chrome.storage.sync.get('LML_Settings', function(LMLSettingsContainer) {
                console.log(LMLSettingsContainer);
                if (LMLSettingsContainer.LML_settings.close_tab == "true") {
                    closeCurrentTab();
                }
            })
</code>```

LMLSettingsContainer logs out as

```<code>{
  "LML_Settings": {
    "close_tab": true,
    "email_format": "individual",
    "frequency": "DAILY"
  }
}
</code>```

accessing my settings with LMLSettingsContainer.LML_Settings["<setting>"] is a bit annoying (and its the whole reason I named the top variable LMLSettingsContainer).

Does anyone know if there's a way to have chrome save/get these values unwrapped?

答: chrome.storage.sync.get('LML_Settings', ({LML_settings}) => { ... }) works, per @wOxxOm</p>

Body:
I am saving some settings using the following sequence

var getSettings = async function() {

    var settings;
    try {
        settings = await authenticatedGET(server_url + SETTINGS_ENDPOINT);
        return settings;
    } catch (error) {
        console.log("Settings Fetch Failed: " + error);
        throw new Error(error);
    }
}

const setLocalSettings = function(settings) {
    chrome.storage.sync.set({ 'LML_Settings': JSON.parse(settings) }, function() {
        console.log("Settings saved locally");
    });
}

At the line right after the setLocalSettings function definition, the 'settings' object logs out as
{"email_format":"individual","close_tab":true,"frequency":"DAILY"} (correctly as intended).  When I go to fetch the settings using this sequence:

chrome.storage.sync.get('LML_Settings', function(LMLSettingsContainer) {
                console.log(LMLSettingsContainer);
                if (LMLSettingsContainer.LML_settings.close_tab == "true") {
                    closeCurrentTab();
                }
            })

LMLSettingsContainer logs out as

{
  "LML_Settings": {
    "close_tab": true,
    "email_format": "individual",
    "frequency": "DAILY"
  }
}

accessing my settings with LMLSettingsContainer.LML_Settings["<setting>"] is a bit annoying (and its the whole reason I named the top variable LMLSettingsContainer).

Does anyone know if there's a way to have chrome save/get these values unwrapped?


问:
Javascript - returning a subset of array members based on the existance of a value using Map or filter
I have had a look for this around SO  and whilst there is a lot of info on these concepts I am having trouble understanding how to bring all these ideas together to satisfy my problem.

I have an array:

```<code>[
  {
    route: ["", "scheduler"],
    name: "scheduler",
    settings: {
      icon: "user",
      auth: true,
      roles: ["Employee", "Admin"],
      pos: "left"
    },
    moduleId: PLATFORM.moduleName("../components/scheduler/scheduler"),
    nav: true,
    title: "scheduler"
  },
  {
    route: "jobs",
    name: "jobs",
    moduleId: PLATFORM.moduleName("../components/jobs/jobsList"),
    settings: {
      icon: "list",
      auth: true,
      roles: ["Employee"],
      pos: "left"
    },
    nav: true,
    title: "Jobs"
  },
  {
    route: "clients",
    name: "clients",
    moduleId: PLATFORM.moduleName("../components/clients/clientList/clientList"),
    title: "Clients",
    nav: true,
    settings: {
      nav: [
        {
          icon: "list",
          route: "clients/ClientsList",
          name: "clientList",
          moduleId: PLATFORM.moduleName(
            "../components/clients/clientList/clientList"
          ),
          href: "#clients/clientsList",
          title: "Client List",
          roles: ["Employee", "Admin"]
        },
        {
          icon: "user",
          route: "clients/create",
          name: "aboutTeam",
          moduleId: PLATFORM.moduleName(
            "../components/clients/clientCreate/clientCreate"
          ),
          href: "#clients/Create",
          title: "Create Client",
          roles: ["Employee", "Admin"]
        }
      ],
      icon: "user",
      auth: true,
      roles: ["Employee", "Admin"],
      pos: "left"
    }
  },
  {
    route: "clients/ClientsList",
    name: "clientList",
    moduleId: PLATFORM.moduleName("../components/clients/clientList/clientList"),
    settings: {
      icon: "list",
      auth: true,
      roles: ["Employee", "Admin"],
      pos: "left"
    }
  },
  {
    route: "clients/create",
    name: "aboutTeam",
    moduleId: PLATFORM.moduleName("../components/clients/clientCreate/clientCreate"),
    settings: {
      icon: "user",
      auth: true,
      roles: ["Employee", "Admin"],
      pos: "left"
    }
  },
  {
    route: "companyDetail",
    name: "companyDetail",
    moduleId: PLATFORM.moduleName("../components/administration/companyDetail/companyDetail"),
    settings: {
      icon: "list",
      auth: true,
      roles: ["Employee", "Admin"],
      pos: "left"
    },
    nav: true,
    title: "Company Detail"
  },
  {
    route: "user",
    name: "user",
    moduleId: PLATFORM.moduleName("../components/administration/user/user"),
    settings: {
      icon: "user",
      auth: true,
      roles: ["Employee", "Admin"],
      pos: "right"
    },
    nav: true,
    title: "User"
  },
  {
    route: "notFound",
    name: "notFound",
    settings: { auth: false },
    moduleId: PLATFORM.moduleName("../components/notFound/notFound"),
    nav: false,
    title: "Not Found"
  }
]
</code>```

Each one has a settings option in which there is an array of roles.

I wanted to loop through each array member to check if, say, the member was in the role of "Admin" and then add it to a new array using say "push".

However I am looking to learn JavaScript and extend my knowledge. I thought I would use the options of "map" and the "fat arrow" function to streamline the code so that I had a new array that contained all items where the roles contained a userRole of admin.

This is my attempt:

```<code>console.log(this.menu.map(r => r.filter(f => f.settings.roles === userRole)));
</code>```

The full function is

```<code>public userMenu(userName: string, userRole: string): any {
const fullMenu = this.menuList();
console.log("userRole: ", userRole);
console.log(this.menu.map(r => r.filter(f => f.settings.roles === userRole)));
}
</code>```

"userRole" exists and displays in the console but I am getting this error:

Uncaught TypeError: Cannot read property 'map' of undefined

How do I structure the map function to work so that I return only those items that have "Admin" as part of the role array in the larger array above.

答:
I wanted to loop through each array member to check if, say, the member was in the role of "Admin" and then add it to a new array using say "push".

The  filter, map functions return new array so you do not need to create new array by yourself. If you need to loop through array, use forEach instead

Uncaught TypeError: Cannot read property 'map' of undefined

Please show your code that sets this.menu

console.log(this.menu.map(r => r.filter(f => f.settings.roles === userRole)));

map, filter , reduce can only be used with array. The above code shown that you use filter against r, an object (as menu is an array of object)

f.settings.roles === userRole: userRole is string but settings.roles is array so you must use includes (or indexOf) to use as condition of filter

As you only want to filter items that satisfy conditions, use filter is enough, like this

menu.filter(r => r.settings.roles && r.settings.roles.includes('Admin'))

Body:
I have had a look for this around SO  and whilst there is a lot of info on these concepts I am having trouble understanding how to bring all these ideas together to satisfy my problem.

I have an array:

[
  {
    route: ["", "scheduler"],
    name: "scheduler",
    settings: {
      icon: "user",
      auth: true,
      roles: ["Employee", "Admin"],
      pos: "left"
    },
    moduleId: PLATFORM.moduleName("../components/scheduler/scheduler"),
    nav: true,
    title: "scheduler"
  },
  {
    route: "jobs",
    name: "jobs",
    moduleId: PLATFORM.moduleName("../components/jobs/jobsList"),
    settings: {
      icon: "list",
      auth: true,
      roles: ["Employee"],
      pos: "left"
    },
    nav: true,
    title: "Jobs"
  },
  {
    route: "clients",
    name: "clients",
    moduleId: PLATFORM.moduleName("../components/clients/clientList/clientList"),
    title: "Clients",
    nav: true,
    settings: {
      nav: [
        {
          icon: "list",
          route: "clients/ClientsList",
          name: "clientList",
          moduleId: PLATFORM.moduleName(
            "../components/clients/clientList/clientList"
          ),
          href: "#clients/clientsList",
          title: "Client List",
          roles: ["Employee", "Admin"]
        },
        {
          icon: "user",
          route: "clients/create",
          name: "aboutTeam",
          moduleId: PLATFORM.moduleName(
            "../components/clients/clientCreate/clientCreate"
          ),
          href: "#clients/Create",
          title: "Create Client",
          roles: ["Employee", "Admin"]
        }
      ],
      icon: "user",
      auth: true,
      roles: ["Employee", "Admin"],
      pos: "left"
    }
  },
  {
    route: "clients/ClientsList",
    name: "clientList",
    moduleId: PLATFORM.moduleName("../components/clients/clientList/clientList"),
    settings: {
      icon: "list",
      auth: true,
      roles: ["Employee", "Admin"],
      pos: "left"
    }
  },
  {
    route: "clients/create",
    name: "aboutTeam",
    moduleId: PLATFORM.moduleName("../components/clients/clientCreate/clientCreate"),
    settings: {
      icon: "user",
      auth: true,
      roles: ["Employee", "Admin"],
      pos: "left"
    }
  },
  {
    route: "companyDetail",
    name: "companyDetail",
    moduleId: PLATFORM.moduleName("../components/administration/companyDetail/companyDetail"),
    settings: {
      icon: "list",
      auth: true,
      roles: ["Employee", "Admin"],
      pos: "left"
    },
    nav: true,
    title: "Company Detail"
  },
  {
    route: "user",
    name: "user",
    moduleId: PLATFORM.moduleName("../components/administration/user/user"),
    settings: {
      icon: "user",
      auth: true,
      roles: ["Employee", "Admin"],
      pos: "right"
    },
    nav: true,
    title: "User"
  },
  {
    route: "notFound",
    name: "notFound",
    settings: { auth: false },
    moduleId: PLATFORM.moduleName("../components/notFound/notFound"),
    nav: false,
    title: "Not Found"
  }
]

Each one has a settings option in which there is an array of roles.

I wanted to loop through each array member to check if, say, the member was in the role of "Admin" and then add it to a new array using say "push".

However I am looking to learn JavaScript and extend my knowledge. I thought I would use the options of "map" and the "fat arrow" function to streamline the code so that I had a new array that contained all items where the roles contained a userRole of admin.

This is my attempt:

console.log(this.menu.map(r => r.filter(f => f.settings.roles === userRole)));

The full function is

public userMenu(userName: string, userRole: string): any {
const fullMenu = this.menuList();
console.log("userRole: ", userRole);
console.log(this.menu.map(r => r.filter(f => f.settings.roles === userRole)));
}

"userRole" exists and displays in the console but I am getting this error:

Uncaught TypeError: Cannot read property 'map' of undefined

How do I structure the map function to work so that I return only those items that have "Admin" as part of the role array in the larger array above.


问:
In Linux, how do I determine optimal value of optmem_max?

We have a Linux project where we are pushing struct information over buffers. Recently, we found that the kernel parameter optmem_max was too small. I was asked to increase this by a supervisor. While I understand how to do this, I don't really understand how I know how big to make this.

Further, I don't really get what optmem_max is.

Here's what the kernel documentation says:

"Maximum ancillary buffer size allowed per socket. Ancillary data is a sequence of struct cmsghdr structures with appended data."

(I don't really understand what this means in English).

I see many examples on the Internet suggesting that this should be increased for better performance.

In:

/etc/sysctl.conf

I added this line to fix the problem:

net.core.optmem_max=1020000

Once this is done, we got better performance.

So to summarize my question:

In English, what is optmem_max?

Why is it so low by default in most Linux distros if making it bigger improves performance?

How does one measure what a good size for this number to be?

What are the ramifications of making this really large?

Aside from /etc/sysctl.conf, where is this set in the kernel by default? I grepped the kernel, but I could find no trace of the default value of optmem_max being set to 20480 which is the default on our system.

答:
In English, what is optmem_max?

optmem_max is a kernel option that affects the memory allocated to the cmsg list maintained by the kernel that contains "extra" packet information like SCM_RIGHTS or IP_TTL.

Increasing this option allows the kernel to allocate more memory as needed for more control messages that need to be sent for each socket connected (including IPC sockets/pipes).

Why is it so low by default in most Linux distros if making it bigger improves performance?

Most distributions have normal users in mind and most normal users, even if using Linux/Unix as a server, do not have a farm of servers that have fiber channels between them or server processes that don't need GB of IPC transfer.

A 20KB buffer is large enough for "most" that it minimizes the kernel memory required by default and is also easily enough configured that one can do so if they need.

How does one measure what a good size for this number to be?

Depends on your usage, but the Arch Wiki suggests a 64KB size for optmem_max and a 16MB size for rmem_max and wmem_max (which are the send and receive buffers).

What are the ramifications of making this really large?

More kernel memory that can be allocated to each socket connected, and maybe unnecessarily.

Aside from /etc/sysctl.conf, where is this set in the kernel by default? I grepped the kernel, but I could find no trace of the default value of optmem_max being set to 20480 which is the default on our system.

I'm not a Linux kernel source aficionado, but it looks like it could be in net/core/sock.c:318.

Hope that can help.


问:
Python how to calcualate average of individual list of a list
I have a list in a list with a lot of data:

```<code>data =  [ [4,25,1,6,3,1,6,...],[45,2,1,5,6,20,29],[491,5,195,239,194,09]
         ..[2,1,5,6,1,95] ]
</code>```

and what I've been trying to figure out how to do is calculate the mean of each individual list and turn it into a column of data looking like this:

```<code>List# average
1     (Mean value of the first list)
2     (Mean value of the second list)
....
15    (mean value of the 15th list)
</code>```

I've tried to put in to loop of iteration like this:

```<code>def average(data)
    for i in range(16):
        total = 0.0
        for x in data[i]:
            total = total + x
    return total / len(data[i])
</code>```

but it only calculate the mean of the first list so far. I also want to calculate the mean of the each of those individual list with the first piece of data sliced off but I don't know how to do that with list in a list.

Edit: changed as suggested but I still have only 1 result from the function, not the average from every sublist.

Body:
I have a list in a list with a lot of data:

data =  [ [4,25,1,6,3,1,6,...],[45,2,1,5,6,20,29],[491,5,195,239,194,09]
         ..[2,1,5,6,1,95] ]

and what I've been trying to figure out how to do is calculate the mean of each individual list and turn it into a column of data looking like this:

List# average
1     (Mean value of the first list)
2     (Mean value of the second list)
....
15    (mean value of the 15th list)

I've tried to put in to loop of iteration like this:

def average(data)
    for i in range(16):
        total = 0.0
        for x in data[i]:
            total = total + x
    return total / len(data[i])

but it only calculate the mean of the first list so far. I also want to calculate the mean of the each of those individual list with the first piece of data sliced off but I don't know how to do that with list in a list.

Edit: changed as suggested but I still have only 1 result from the function, not the average from every sublist.

Body:
Other answer will solve your issue , Just wanted to let you know that you can do in one line without any loop :

data=[ [4,25,1,6,3,1,6],[45,2,1,5,6,20,29],[491,5,195,239,194,9],[2,1,5,6,1,95] ]

print(list(map(lambda x:sum(x)/len(x),data)))
#do your stuff with this result

output:

[6.571428571428571, 15.428571428571429, 188.83333333333334, 18.333333333333332]


问:
Using Zenject to wire up Mapbox SDK
I'm using the Mapbox SDK and RoadArchitect and trying to build some game initialization code that uses Mapbox to generate a list of vectors, then take that list of vectors and call functions in Road Architect to generate road GameObjects. In order to do this, I need to wait until Mapbox has finished it's work before I can run the code to generate roads. I extended the Mapbox MergedModifierStack as ObservedModifierStack and added a StackComplete event.

My current scene setup has 2 relevant GameObjects:

Map (Mapbox AbstractMap)

which contains (pseudo propery path, might not be 100% accurate): Map.VectorTileFactory.Factories[m].Visualizer.ObservedModifierStack .Modifiers[n].MyModifier

RoadArchitect GSDRoadSystem

Most of the objects in the Map hierarchy are ScriptableObject and all are added/configured through inspectors in the editor UI.

public class MyModifier {
    public MyModifier (MyDataObject myDataObject) { ... }
}

public class MyObjectCreator {
    public MyObjectCreator(MyDataObject myDataObject, ModifierStack modifierStack) {
        ...
        modifierStack.StackComplete += OnStackComplete();
    }
}
```

In My OnStackComplete event handler I am attempting to execute functions against GSDRoadSystem. I say "attempt" because I haven't been able to figure out how to wire everything up to be injected, short of rewriting large portions of the Mapbox code simply to decorate everything with [Inject], something I'm reluctant to do given the SDK is still in heavy development.

The main issue seems to be that MyModifier isn't having MyDataObject injected, I'm guessing because Mapbox/Unity is controlling the lifecycle (due to configuration through inspectors/editor), but I don't know how to get around or work with that through Zenject.

My other option is to mess around with the Unity messaging system, and passing the vector list in the message to MyObjectCreator which would locate the appropriate GSDRoadSystem through the Unity provided service locators. Not ideal, but given this is a one-time setup and the RoadArchitect processing is going to dwarf any extra time or memory that might take I'm okay with it, even if it is a bit inelegant, although I'd rather learn how to get Zenject to wire things up, if that is at all possible (maybe it isn't because of how Mapbox built things).

I do have a fairly extensive background working with DI (Autofac, Ninject, poor-man's, etc.) but this is my first foray into Unity3d. It's possible I'm allowing Unity to cloud things and the solution is obvious, but I'm not seeing it right now.

答: For objects that are not created by Zenject and are not in the initial scene, you need to manually inject them yourself.  You can do this by first injecting DiContainer into one of your classes and then calling DiContainer.Inject or DiContainer.InjectGameObject on the object that was created by third party code.

Title: Using Zenject to wire up Mapbox SDK

Body:
I'm using the Mapbox SDK and RoadArchitect and trying to build some game initialization code that uses Mapbox to generate a list of vectors, then take that list of vectors and call functions in Road Architect to generate road GameObjects. In order to do this, I need to wait until Mapbox has finished it's work before I can run the code to generate roads. I extended the Mapbox MergedModifierStack as ObservedModifierStack and added a StackComplete event.

My current scene setup has 2 relevant GameObjects:

Map (Mapbox AbstractMap)

which contains (pseudo propery path, might not be 100% accurate): Map.VectorTileFactory.Factories[m].Visualizer.ObservedModifierStack .Modifiers[n].MyModifier

RoadArchitect GSDRoadSystem

Most of the objects in the Map hierarchy are ScriptableObject and all are added/configured through inspectors in the editor UI.

public class MyModifier {
    public MyModifier (MyDataObject myDataObject) { ... }
}

public class MyObjectCreator {
    public MyObjectCreator(MyDataObject myDataObject, ModifierStack modifierStack) {
        ...
        modifierStack.StackComplete += OnStackComplete();
    }
}

In My OnStackComplete event handler I am attempting to execute functions against GSDRoadSystem. I say "attempt" because I haven't been able to figure out how to wire everything up to be injected, short of rewriting large portions of the Mapbox code simply to decorate everything with [Inject], something I'm reluctant to do given the SDK is still in heavy development.

The main issue seems to be that MyModifier isn't having MyDataObject injected, I'm guessing because Mapbox/Unity is controlling the lifecycle (due to configuration through inspectors/editor), but I don't know how to get around or work with that through Zenject.

My other option is to mess around with the Unity messaging system, and passing the vector list in the message to MyObjectCreator which would locate the appropriate GSDRoadSystem through the Unity provided service locators. Not ideal, but given this is a one-time setup and the RoadArchitect processing is going to dwarf any extra time or memory that might take I'm okay with it, even if it is a bit inelegant, although I'd rather learn how to get Zenject to wire things up, if that is at all possible (maybe it isn't because of how Mapbox built things).

I do have a fairly extensive background working with DI (Autofac, Ninject, poor-man's, etc.) but this is my first foray into Unity3d. It's possible I'm allowing Unity to cloud things and the solution is obvious, but I'm not seeing it right now.


答:
The combination formula for "n choose k" is given by

where n and k are whole numbers.  The generalized version for x and y in the set of real numbers is given by

where Γ(x) is the gamma function, a generalized form of the factorial.

To create this in Python, you can use the following:

```<code>import math

def generalized_binomial(x,y):
    return math.gamma(x+1) / (math.gamma(y+1) * math.gamma(x-y+1))

generalized_binomial(5,2.1)
# returns:
10.304042688575835
</code>```

Title: how to calculate binomial coefficents with non-integer numbers

Body: I know how to calculate binomial coefficients for choose(5,2), but now I want to know if there is a function that I can calculate choose(5,2.1) in python or R programming language?

Body:
The combination formula for "n choose k" is given by

where n and k are whole numbers.  The generalized version for x and y in the set of real numbers is given by

where Γ(x) is the gamma function, a generalized form of the factorial.

To create this in Python, you can use the following:

import math

def generalized_binomial(x,y):
    return math.gamma(x+1) / (math.gamma(y+1) * math.gamma(x-y+1))

generalized_binomial(5,2.1)
# returns:
10.304042688575835


问:
Anyone actually using Mosso Files (Amazon S3 competitor)?
We have a bunch of data on S3 (images) but just started reading about Mosso Files (rackspace). Sometime this month they are going to add CDN capabilities so any file you upload is part of the limelight CDN.

Anyone using this service, it's not as well documented or publicized at S3.

答:
Yes, it's not well documented or publicized as S3. But dude it has CDN support which S3 is lack off (unless you willing to pay extra of course). Bad thing is you can't FTP into Mosso CloudFile, you will either have to upload it through web-based control panel or API. Yet, it's still cheap and worth especially with CDN.

I am using the service and it's pretty good and cost effective compare to S3.

OwnerDisplayName: Kyle West

OwnerDisplayName: Ryan


问:
how to build opencv for python3 when both python2 and python3 are installed
I was trying to build opencv for python3. However, cmake always sets python build option to be python2.7.11 even after I manually specified include and lib option for python3:

```<code>    --   Python 2:
    --   Interpreter:                 /home/ryu/anaconda2/bin/python2.7 (ver 2.7.11)

    --   Python 3:
    --     Interpreter:                 /usr/bin/python3 (ver 3.4.3)
    --     Libraries:                   /usr/lib/x86_64-linux-gnu/libpython3.4m (ver 3.4.3)
    --     numpy:                       /home/ryu/.local/lib/python3.4/site-packages/numpy/core/include (ver 1.11.0)

    --  packages path:               lib/python3.4/dist-packages

--
--   **Python (for build):            /home/ryu/anaconda2/bin/python2.7**
</code>```

Did I miss some cmake option?

OS: Ubuntu 14,04

thanks

答:
Changing the options in cmake did nothing for me no matter what options I modified. The simpliest (hacky) solution for me was to

sudo mv /usr/bin/python2.7 /usr/bin/pythonNO-temp

Then you build and install opencv

then

sudo mv /usr/bin/pythonNO-temp /usr/bin/python2.7

Body:
I was trying to build opencv for python3. However, cmake always sets python build option to be python2.7.11 even after I manually specified include and lib option for python3:

    --   Python 2:
    --   Interpreter:                 /home/ryu/anaconda2/bin/python2.7 (ver 2.7.11)

    --   Python 3:
    --     Interpreter:                 /usr/bin/python3 (ver 3.4.3)
    --     Libraries:                   /usr/lib/x86_64-linux-gnu/libpython3.4m (ver 3.4.3)
    --     numpy:                       /home/ryu/.local/lib/python3.4/site-packages/numpy/core/include (ver 1.11.0)

    --  packages path:               lib/python3.4/dist-packages

--
--   **Python (for build):            /home/ryu/anaconda2/bin/python2.7**

Did I miss some cmake option?

OS: Ubuntu 14,04

thanks