问:
RoundRobin functional approach - why does my function have side effects?

Objective

I am trying to create a Round Robin algorithm ( https://en.wikipedia.org/wiki/Round-robin_scheduling ) in a pure functional way.

This function, is supposed to received an array like the following:

```<code>[
    [ 1, 2 ],
    [ 3, 4 ]
]
</code>```

And produce the following output:

[ 1, 3, 2, 4 ]

Code

To achieve this, I decided to implement round robin recursively like the following:

```<code>const roundRobin = (arr, results) => {
    if (arr.length === 0) return results;

    const newResults = arr.reduce((acc, current) => {

        if (current.length > 0) {
            acc.results.push(current.shift());
            acc.arr.push(current);
        }
        return acc;

    }, { arr: [], results });

    return roundRobin(newResults.arr, newResults.results);
};
</code>```

Here, I feel up an array of results, and I finish when I have nothing left to add to it. One would use this code like the following:

```<code>const array =     [
        [ 1, 2 ],
        [ 3, 4 ]
    ];

const result = roundRobin( array, [] );
</code>```

Problem

In my code I am using reduce in my arr parameter to ensure I don't modify the original. However, if I print array before using roundRobin and after, the variable is changed ! I mutate it somehow!

Questions:

If I am using reduce, which is pure, how am I mutating my parameters?

Is there another pure/functional way of implementing roundRobin?

答:
Array#shift is doing the mutating.

```<code>var array = [0, 1, 2, 3, 4];
array.shift(); // -> 0
array; // -> [1, 2, 3, 4];
</code>```

The easiest way around that is to clone the array. Usually that can be done with Array#concat but since your arrays are nested (though simple) you can do this:

```<code>const roundRobin = (arr, results) => {
    arr = JSON.parse(JSON.stringify(arr));
    if (arr.length === 0) return results;
    // ...
</code>```

If you're concerned that the global JSON makes the function impure, you can abstract that out.

```<code>const deepClone = (obj) => JSON.parse(JSON.stringify(obj));
roundRobin(deepClone(array), []);
</code>```

Body:
Objective

I am trying to create a Round Robin algorithm ( https://en.wikipedia.org/wiki/Round-robin_scheduling ) in a pure functional way.

This function, is supposed to received an array like the following:

[
    [ 1, 2 ],
    [ 3, 4 ]
]

And produce the following output:

[ 1, 3, 2, 4 ]

Code

To achieve this, I decided to implement round robin recursively like the following:

const roundRobin = (arr, results) => {
    if (arr.length === 0) return results;

    const newResults = arr.reduce((acc, current) => {

        if (current.length > 0) {
            acc.results.push(current.shift());
            acc.arr.push(current);
        }
        return acc;

    }, { arr: [], results });

    return roundRobin(newResults.arr, newResults.results);
};

Here, I feel up an array of results, and I finish when I have nothing left to add to it. One would use this code like the following:

const array =     [
        [ 1, 2 ],
        [ 3, 4 ]
    ];

const result = roundRobin( array, [] );

Problem

In my code I am using reduce in my arr parameter to ensure I don't modify the original. However, if I print array before using roundRobin and after, the variable is changed ! I mutate it somehow!

Questions:

If I am using reduce, which is pure, how am I mutating my parameters?

Is there another pure/functional way of implementing roundRobin?

Body:
Array#shift is doing the mutating.

var array = [0, 1, 2, 3, 4];
array.shift(); // -> 0
array; // -> [1, 2, 3, 4];

The easiest way around that is to clone the array. Usually that can be done with Array#concat but since your arrays are nested (though simple) you can do this:

const roundRobin = (arr, results) => {
    arr = JSON.parse(JSON.stringify(arr));
    if (arr.length === 0) return results;
    // ...

If you're concerned that the global JSON makes the function impure, you can abstract that out.

const deepClone = (obj) => JSON.parse(JSON.stringify(obj));
roundRobin(deepClone(array), []);


来源: stackexchange

问:
HTML input pattern that consists of 4 numbers and 2 letters at the end
Ive looked around for different validation patterns but didnt find any good examples that would help me create something like that. For example "5676AB".
Needs to have 4 numbers at the beginning, followed by 2 characters (can be uppercase and also lowercase).

If anyone would help me I would be very thankful!

答: Do you mean patter attribute of input? Try this pattern="[0-9]{4}[A-Za-z]{2}"

ContentLicense: CC BY-SA 3.0


问:
Why GCC does not report uninitialized variable?
```<code>#include <ios>
#include <iostream>
#include <map>

using namespace std;

int main() {
  ios_base::sync_with_stdio(false);
  map<int, int> v;
  int i;
  int t;
  while (cin >> i) {
    v[i] = t++;
  }
  auto mi = i;
  auto mt = t;
  for (const auto p : v) {
    if (p.second < mt) {
      mi = p.first;
      mt = p.second;
    }
  }
  cout << mi << '\n';
  return 0;
}
</code>```

The abovementioned program makes heavy use of an uninitialized variable t, but GCC does not report it with -Wall or -Wuninitialized. Why is it so?

It is worth noting that Clang catches it:

```<code>main.cpp:13:12: warning: variable 't' is uninitialized when used here [-Wuninitialized]
    v[i] = t++;
           ^
</code>```

Used g++ (GCC) 7.2.1 20170915 (Red Hat 7.2.1-2).

Used clang version 4.0.1 (tags/RELEASE_401/final).

As you can see in https://godbolt.org/g/kmYMC1 GCC 7.2 does not report it even when it should. I will create a ticket in GCC's issue tracker.

答:
GCC can only detect uninitialized variables when optimization is enabled, because the logic for tracking the values of variables is part of the optimization machinery.

If you compile with -O -Wall you get a warning:

```<code><source>: In function 'int main()':
12 : <source>:12:13: warning: 't' may be used uninitialized in this function [-Wmaybe-uninitialized]
     v[i] = t++;
            ~^~
Compiler exited with result code 0
</code>```

https://godbolt.org/g/327bsi

Body:
#include <ios>
#include <iostream>
#include <map>

using namespace std;

int main() {
  ios_base::sync_with_stdio(false);
  map<int, int> v;
  int i;
  int t;
  while (cin >> i) {
    v[i] = t++;
  }
  auto mi = i;
  auto mt = t;
  for (const auto p : v) {
    if (p.second < mt) {
      mi = p.first;
      mt = p.second;
    }
  }
  cout << mi << '\n';
  return 0;
}

The abovementioned program makes heavy use of an uninitialized variable t, but GCC does not report it with -Wall or -Wuninitialized. Why is it so?

It is worth noting that Clang catches it:

main.cpp:13:12: warning: variable 't' is uninitialized when used here [-Wuninitialized]
    v[i] = t++;
           ^

Used g++ (GCC) 7.2.1 20170915 (Red Hat 7.2.1-2).

Used clang version 4.0.1 (tags/RELEASE_401/final).

As you can see in https://godbolt.org/g/kmYMC1 GCC 7.2 does not report it even when it should. I will create a ticket in GCC's issue tracker.

Body:
GCC can only detect uninitialized variables when optimization is enabled, because the logic for tracking the values of variables is part of the optimization machinery.

If you compile with -O -Wall you get a warning:

<source>: In function 'int main()':
12 : <source>:12:13: warning: 't' may be used uninitialized in this function [-Wmaybe-uninitialized]
     v[i] = t++;
            ~^~
Compiler exited with result code 0

https://godbolt.org/g/327bsi


问:
Using a "big sound" module with arduino to create a decibel meter
I am trying to create a sound meter to measure the decibels in a room and I am currently using a nodemcu 12e as I want to insert those measures to a row in a mySQL server and a "big sound module" (https://tkkrlab.nl/wiki/Arduino_KY-038_Microphone_sound_sensor_module).

The only thing I have achieved so far is to get the raw values of the sensor, as they don't seem to change, although I have tried to adjust the gain turning the screw in the microphone, with no result, as it seems to stay in the same values even when playing loud music.

It seems to react to loud noises, and clapping makes the output to spike up - allowing me to control that lighting up the connected led:

```<code>#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "yourssid";
const char* password = "yourpass";

ESP8266WebServer server(80);

const int led = 13;

int sensorPin = A0; // select the input pin for the potentiometer
int ledPin = D7; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor

void setup(void){
  pinMode(led, OUTPUT);
  digitalWrite(led, 0);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }

  });

  //SETUP SOUND SENSOR
  pinMode (ledPin, OUTPUT);
}

void loop(void){
  sensorValue = analogRead (sensorPin);
  Serial.println (sensorValue);//, DEC);
  if (sensorValue > 100){
    digitalWrite (ledPin, HIGH);
    delay (1000);
    digitalWrite (ledPin, LOW);
  }
}
</code>```

I am reading the analog value of the sensor and I tried to get the lower values possible as seen I was trying to calibrate the mic. The values I am constantly getting are between 19 and 20:

As you can see, on clapping I get a spike of the value.

The thing is that the values don't change at all when loud music is playing, only getting different values when it detects a loud noise (like clapping).   How can I change the code or system to get the values in decibels?

答:
You might not get this running with this microphone module.

The mdule act as a switch. The switching threshold is set by the potentiometer on board of the microphone module.

What you would need is a low-level amlified microphone. Then you would get an input range from 0 (no noise) to 1023 (loud noise). This value then could be mapped to decibel. But again - not with this module.

Regards
Harry

Body:
I am trying to create a sound meter to measure the decibels in a room and I am currently using a nodemcu 12e as I want to insert those measures to a row in a mySQL server and a "big sound module" (https://tkkrlab.nl/wiki/Arduino_KY-038_Microphone_sound_sensor_module).

The only thing I have achieved so far is to get the raw values of the sensor, as they don't seem to change, although I have tried to adjust the gain turning the screw in the microphone, with no result, as it seems to stay in the same values even when playing loud music.

It seems to react to loud noises, and clapping makes the output to spike up - allowing me to control that lighting up the connected led:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "yourssid";
const char* password = "yourpass";

ESP8266WebServer server(80);

const int led = 13;

int sensorPin = A0; // select the input pin for the potentiometer
int ledPin = D7; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor

void setup(void){
  pinMode(led, OUTPUT);
  digitalWrite(led, 0);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }

  });

  //SETUP SOUND SENSOR
  pinMode (ledPin, OUTPUT);
}

void loop(void){
  sensorValue = analogRead (sensorPin);
  Serial.println (sensorValue);//, DEC);
  if (sensorValue > 100){
    digitalWrite (ledPin, HIGH);
    delay (1000);
    digitalWrite (ledPin, LOW);
  }
}

I am reading the analog value of the sensor and I tried to get the lower values possible as seen I was trying to calibrate the mic. The values I am constantly getting are between 19 and 20:

As you can see, on clapping I get a spike of the value.

The thing is that the values don't change at all when loud music is playing, only getting different values when it detects a loud noise (like clapping).   How can I change the code or system to get the values in decibels?


问:
Jenkins pipeline not failing based on batch exit code
I am having trouble with a Jenkins pipeline that is not failing when a called batch file fails. I have checked the batch file, it returns a non-zero status code, but somehow this seems to be not considered. Does anyone of you have a hint for me?

desired pipeline

```<code>node {
  stage('1'){
    dir('_src') {
      bat 'call test.bat'
    }
  }
}
</code>```

Calling the batch in cmd window results in the following

```<code>>call test.bat
INFO: Started ...
ERROR
Press any key to continue . . .
>echo %ERRORLEVEL%
2
</code>```

I also used the following pipeline for testing

```<code>node {
  stage('1'){
    dir('_src') {
      bat '''call test.bat
      echo %ERRORLEVEL%'''
    }
  }
}
</code>```

... with this output

```<code>C:\_src>call test.bat
INFO: Started ...
ERROR
Press any key to continue . . .
2
</code>```

Still, the pipeline is not failing. Any ideas?

答:
It should be:</p>

```<code>node {
  stage('1'){
    dir('_src') {
      bat '''call test.bat
      exit %ERRORLEVEL%'''
    }
  }
}
</code>```

Body:
I am having trouble with a Jenkins pipeline that is not failing when a called batch file fails. I have checked the batch file, it returns a non-zero status code, but somehow this seems to be not considered. Does anyone of you have a hint for me?

desired pipeline

node {
  stage('1'){
    dir('_src') {
      bat 'call test.bat'
    }
  }
}

Calling the batch in cmd window results in the following

>call test.bat
INFO: Started ...
ERROR
Press any key to continue . . .
>echo %ERRORLEVEL%
2

I also used the following pipeline for testing

node {
  stage('1'){
    dir('_src') {
      bat '''call test.bat
      echo %ERRORLEVEL%'''
    }
  }
}

... with this output

C:\_src>call test.bat
INFO: Started ...
ERROR
Press any key to continue . . .
2

Still, the pipeline is not failing. Any ideas?

Body:
It should be:

node {
  stage('1'){
    dir('_src') {
      bat '''call test.bat
      exit %ERRORLEVEL%'''
    }
  }
}


问:
Why does adding and subtracting two #define'd macros not work on iPhone / Objective-c
In my iPhone app, I have this in my .h file

```<code>#define ORIENTATION_IS_PORTRAIT UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])
#define FULLSCREEN_MODE         ORIENTATION_IS_PORTRAIT?460:300
#define AD_HEIGHT               ORIENTATION_IS_PORTRAIT?50:32
#define FULLSCREEN_MODE_WITH_AD FULLSCREEN_MODE - AD_HEIGHT //doesn't work
</code>```

To sum it up, I have a macro to detect the orientation. I have another for the height of my UIWebView when it is in full screen mode (activated by a button press). I need to keep the ad at the bottom. However, to get the height of the UIWebView minus the ad height will only return the AD_HEIGHT.

For addition, (FULLSCREEN_MODE + AD_HEIGHT) returns the FULLSCREEN_MODE only.

Also, when using constants, where exactly do I put them. I searched and could only find answers like "in the .m file", but where??

答:
What you want is to have it like this:

```<code>#define FULLSCREEN_MODE         (ORIENTATION_IS_PORTRAIT?460:300)
#define AD_HEIGHT               (ORIENTATION_IS_PORTRAIT?50:32)
#define FULLSCREEN_MODE_WITH_AD (FULLSCREEN_MODE - AD_HEIGHT)
</code>```

For more complex expressions, I'd suggest you wrap that in do { ... } while(0) instead of just grouping them together.

What's happening here is it's being parsed as:

```<code>UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]) ? 460 : 300 - UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]) ? 50 : 32
</code>```

which is not the math you want.

Body:
In my iPhone app, I have this in my .h file

#define ORIENTATION_IS_PORTRAIT UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])
#define FULLSCREEN_MODE         ORIENTATION_IS_PORTRAIT?460:300
#define AD_HEIGHT               ORIENTATION_IS_PORTRAIT?50:32
#define FULLSCREEN_MODE_WITH_AD FULLSCREEN_MODE - AD_HEIGHT //doesn't work

To sum it up, I have a macro to detect the orientation. I have another for the height of my UIWebView when it is in full screen mode (activated by a button press). I need to keep the ad at the bottom. However, to get the height of the UIWebView minus the ad height will only return the AD_HEIGHT.

For addition, (FULLSCREEN_MODE + AD_HEIGHT) returns the FULLSCREEN_MODE only.

Also, when using constants, where exactly do I put them. I searched and could only find answers like "in the .m file", but where??

Body:
What you want is to have it like this:

#define FULLSCREEN_MODE         (ORIENTATION_IS_PORTRAIT?460:300)
#define AD_HEIGHT               (ORIENTATION_IS_PORTRAIT?50:32)
#define FULLSCREEN_MODE_WITH_AD (FULLSCREEN_MODE - AD_HEIGHT)

For more complex expressions, I'd suggest you wrap that in do { ... } while(0) instead of just grouping them together.

What's happening here is it's being parsed as:

UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]) ? 460 : 300 - UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]) ? 50 : 32

which is not the math you want.

ContentLicense: CC BY-SA 2.5


问:
How to send message in rabbitmq on docker?
Again, it supposed to be simple, but wasn't able to find any documentation about it

In my previous question I had a problems with running rabbitmq container in docker. It has been solved, but now another one appeared

Container was created with this line

```<code>docker run -d --hostname my-rabbit --name some-rabbit -p 15672:15672 rabbitmq:3-management
</code>```

I was trying to create a simple console application to check how message sending is working (from base tutorial):

```<code>var factory = new ConnectionFactory()
{
  HostName = "localhost",
  Port = 15672
};

using (var connection = factory.CreateConnection())
{
  using (var channel = connection.CreateModel())
  {
    channel.QueueDeclare("Test", false, false, false, null);

    var mess = new RepMessage()
    {
       ConnectionString = "TestingString",
       QueueID = 5
    };

    var jsonified = JsonConvert.SerializeObject(mess);
    var messBody = Encoding.UTF8.GetBytes(jsonified);
    channel.BasicPublish("", "Test", null, messBody);

    Console.WriteLine(string.Format("Message with ConStr={0}, QueueID={1} has been send", mess.ConnectionString, mess.QueueID));
  }
}
</code>```

And result is, its not working.
I am receiving exception None of the specified endpoints were reachable and inner exception as connection.start was never received, likely due to a network timeout

If I remove port, then my inner exception transforms in No connection could be made because the target machine actively refused it 127.0.0.1:5672

What am I missing, is is this example not supposed to work with docker?

答: Port 15672 is a port of rabbitmq management plugin web interface. When you are sending message to rabbit - you need to connect to different port (by default - 5672). So change your code to connect to that port and map it in docker via -p 5672:5672.

Body:
Again, it supposed to be simple, but wasn't able to find any documentation about it

In my previous question I had a problems with running rabbitmq container in docker. It has been solved, but now another one appeared

Container was created with this line

docker run -d --hostname my-rabbit --name some-rabbit -p 15672:15672 rabbitmq:3-management

I was trying to create a simple console application to check how message sending is working (from base tutorial):

var factory = new ConnectionFactory()
{
  HostName = "localhost",
  Port = 15672
};

using (var connection = factory.CreateConnection())
{
  using (var channel = connection.CreateModel())
  {
    channel.QueueDeclare("Test", false, false, false, null);

    var mess = new RepMessage()
    {
       ConnectionString = "TestingString",
       QueueID = 5
    };

    var jsonified = JsonConvert.SerializeObject(mess);
    var messBody = Encoding.UTF8.GetBytes(jsonified);
    channel.BasicPublish("", "Test", null, messBody);

    Console.WriteLine(string.Format("Message with ConStr={0}, QueueID={1} has been send", mess.ConnectionString, mess.QueueID));
  }
}

And result is, its not working.
I am receiving exception None of the specified endpoints were reachable and inner exception as connection.start was never received, likely due to a network timeout

If I remove port, then my inner exception transforms in No connection could be made because the target machine actively refused it 127.0.0.1:5672

What am I missing, is is this example not supposed to work with docker?


问:
R regular expression for p#q#c#
What would the regular expression be to encompass variable names such as p3q10000c150 and p29q2990c98? I want to add all variables in the format of p-any number-q-any number-c-any number to a list in R.

Thanks!

答:
If your objective is to pull out the 3 numbers and put them in a 3 column data frame or matrix then any of these alternatives would do it.

The regular expression in #1 matches p and then one or more digits and then q and then one or more digits and then c and one or more digits.  The parentheses form capture groups which are placed in the corresponding columns of the prototype data frame given as the third argument.

In #2 each non-digit ("\\D") is replaced with a space and then read.table reads in the data using the indicated column names.

In #3 we convert each element of the input to DCF format, namely c("\np: 3\nq: 10000\nc: 150", "\np: 29\nq: 2990\nc: 98") and then read it in using read.dcf and conver the columns to numeric.  This creates a matrix whereas the prior two alternatives create data frames.

The second alternative seems simplest but the third one is more general in that it does not hard code the header names or the number of columns.  (If we used col.names = strsplit(input, "\\d+")[[1]] in #2 then it would be similarly general.)

```<code># 1
strcapture("p(\\d+)q(\\d+)c(\\d+)", input,
   data.frame(p = character(), q = character(), c = character()))

# 2
read.table(text = gsub("\\D", " ", input), col.names = c("p", "q", "c"))

# 3
apply(read.dcf(textConnection(gsub("(\\D)", "\n\\1: ", input))), 2, as.numeric)
</code>```

The first two above give this data.frame and the third one gives the corresponding numeric matrix.

```<code>   p     q   c
1  3 10000 150
2 29  2990  98
</code>```

Note: The input is assumed to be:

```<code>input <- c("p3q10000c150", "p29q2990c98")
</code>```

Title: R regular expression for p#q#c#

Body:
If your objective is to pull out the 3 numbers and put them in a 3 column data frame or matrix then any of these alternatives would do it.

The regular expression in #1 matches p and then one or more digits and then q and then one or more digits and then c and one or more digits.  The parentheses form capture groups which are placed in the corresponding columns of the prototype data frame given as the third argument.

In #2 each non-digit ("\\D") is replaced with a space and then read.table reads in the data using the indicated column names.

In #3 we convert each element of the input to DCF format, namely c("\np: 3\nq: 10000\nc: 150", "\np: 29\nq: 2990\nc: 98") and then read it in using read.dcf and conver the columns to numeric.  This creates a matrix whereas the prior two alternatives create data frames.

The second alternative seems simplest but the third one is more general in that it does not hard code the header names or the number of columns.  (If we used col.names = strsplit(input, "\\d+")[[1]] in #2 then it would be similarly general.)

# 1
strcapture("p(\\d+)q(\\d+)c(\\d+)", input,
   data.frame(p = character(), q = character(), c = character()))

# 2
read.table(text = gsub("\\D", " ", input), col.names = c("p", "q", "c"))

# 3
apply(read.dcf(textConnection(gsub("(\\D)", "\n\\1: ", input))), 2, as.numeric)

The first two above give this data.frame and the third one gives the corresponding numeric matrix.

   p     q   c
1  3 10000 150
2 29  2990  98

Note: The input is assumed to be:

input <- c("p3q10000c150", "p29q2990c98")


问:
How do I get a consistent byte representation of strings in C# without manually specifying an encoding?
How do I convert a string to a byte[] in .NET (C#) without manually specifying a specific encoding?

I'm going to encrypt the string. I can encrypt it without converting, but I'd still like to know why encoding comes to play here.

Also, why should encoding even be taken into consideration? Can't I simply get what bytes the string has been stored in? Why is there a dependency on character encodings?

答:
I'm not sure, but I think the string stores its info as an array of Chars, which is inefficient with bytes.  Specifically, the definition of a Char is "Represents a Unicode character".

take this example sample:

```<code>String str = "asdf éß";
String str2 = "asdf gh";
EncodingInfo[] info =  Encoding.GetEncodings();
foreach (EncodingInfo enc in info)
{
    System.Console.WriteLine(enc.Name + " - "
      + enc.GetEncoding().GetByteCount(str)
      + enc.GetEncoding().GetByteCount(str2));
}
</code>```

Take note that the Unicode answer is 14 bytes in both instances, whereas the UTF-8 answer is only 9 bytes for the first, and only 7 for the second.

So if you just want the bytes used by the string, simply use Encoding.Unicode, but it will be inefficient with storage space.

OwnerDisplayName: Vulcan Eager

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Dale Ragan

Body:
I'm not sure, but I think the string stores its info as an array of Chars, which is inefficient with bytes.  Specifically, the definition of a Char is "Represents a Unicode character".

take this example sample:

String str = "asdf éß";
String str2 = "asdf gh";
EncodingInfo[] info =  Encoding.GetEncodings();
foreach (EncodingInfo enc in info)
{
    System.Console.WriteLine(enc.Name + " - "
      + enc.GetEncoding().GetByteCount(str)
      + enc.GetEncoding().GetByteCount(str2));
}

Take note that the Unicode answer is 14 bytes in both instances, whereas the UTF-8 answer is only 9 bytes for the first, and only 7 for the second.

So if you just want the bytes used by the string, simply use Encoding.Unicode, but it will be inefficient with storage space.

OwnerDisplayName: Ed Marty


问:
Using bash, how do you make a classpath out of all files in a directory?
This will be a really simple freebie for a bash guru:

Question

Using bash, how do you make a classpath out of all files in a directory?

Details

Given a directory:

```<code>LIB=/path/to/project/dir/lib
</code>```

that contains nothing but *.jar files such as:

```<code>junit-4.8.1.jar
jurt-3.2.1.jar
log4j-1.2.16.jar
mockito-all-1.8.5.jar
</code>```

I need to create a colon-separated classpath variable in the form:

```<code>CLASSPATH=/path/to/project/dir/lib/junit-4.8.1.jar:/path/to/project/dir/lib/jurt-3.2.1.jar:/path/to/project/dir/lib/log4j-1.2.16.jar:/path/to/project/dir/lib/mockito-all-1.8.5.jar
</code>```

Some seudo-code that nearly expresses the logic I'm looking for would be along the lines of:

```<code>for( each file in directory ) {
   classpath = classpath + ":" + LIB + file.name
}
</code>```

What is a simple way to accomplish this via bash script?

答:
Here's another variation:

```<code>printf -v CLASSPATH "$LIB/%s:" *.jar; CLASSPATH=${CLASSPATH%:}
</code>```

printf -v is somewhat like sprintf. The brace expansion removes the extra colon from the end.

Body:
This will be a really simple freebie for a bash guru:

Question

Using bash, how do you make a classpath out of all files in a directory?

Details

Given a directory:

LIB=/path/to/project/dir/lib

that contains nothing but *.jar files such as:

junit-4.8.1.jar
jurt-3.2.1.jar
log4j-1.2.16.jar
mockito-all-1.8.5.jar

I need to create a colon-separated classpath variable in the form:

CLASSPATH=/path/to/project/dir/lib/junit-4.8.1.jar:/path/to/project/dir/lib/jurt-3.2.1.jar:/path/to/project/dir/lib/log4j-1.2.16.jar:/path/to/project/dir/lib/mockito-all-1.8.5.jar

Some seudo-code that nearly expresses the logic I'm looking for would be along the lines of:

for( each file in directory ) {
   classpath = classpath + ":" + LIB + file.name
}

What is a simple way to accomplish this via bash script?

Body:
Here's another variation:

printf -v CLASSPATH "$LIB/%s:" *.jar; CLASSPATH=${CLASSPATH%:}

printf -v is somewhat like sprintf. The brace expansion removes the extra colon from the end.


问:
javascript: left-merge two objects using EcmaScript 6 / immutable js
I work in javascript Project.

I'm now about search after option to merge two objects, as the second object will only ovveride fields of the first object and not add new fields which the second not has.

Something like:

```<code>const firstObj = {name:'jon', age:'6}
const secondObj = {name:'nir', mark:'100%'}

const mergedObj = leftMerge(firstObj, secondObj);
</code>```

So I like mergedObj to be:

```<code>{name:'nir', age:'6'}
</code>```

Is I have any way to do that with javascript (I worl with EcmaScript 6), or with immutable.js library?

答:
There's not builtin for this (Object.assign merges all properties), but you can write it really easily yourself:

```<code>function leftMerge(a, b) {
    const res = {};
    for (const p in a)
        res[p] = (p in b ? b : a)[p];
    return res;
}
</code>```

Body:
I work in javascript Project.

I'm now about search after option to merge two objects, as the second object will only ovveride fields of the first object and not add new fields which the second not has.

Something like:

const firstObj = {name:'jon', age:'6}
const secondObj = {name:'nir', mark:'100%'}

const mergedObj = leftMerge(firstObj, secondObj);

So I like mergedObj to be:

{name:'nir', age:'6'}

Is I have any way to do that with javascript (I worl with EcmaScript 6), or with immutable.js library?

Body:
There's not builtin for this (Object.assign merges all properties), but you can write it really easily yourself:

function leftMerge(a, b) {
    const res = {};
    for (const p in a)
        res[p] = (p in b ? b : a)[p];
    return res;
}


问:
COUNT Changes with Join on another Table MySQL
I have the following Database Structure

```<code>Table Employee:

Name     ENr
Name 1   1
Name 2   2
Name 3   3
...

Table Travel:

Employee  Costs
Name 1    8000
Name 1    56000
Name 2    800
</code>```

and so on.

Now I want to Select The Name of the employees, the Count of the Travels and the Average Costs, as well as the ENr

Thats my SQL Select so far:

```<code>SELECT   employee,  COUNT(travel.employee), AVG(costs) FROM  travel  GROUP BY employee
</code>```

However, as soon as I try to connect with the employee Table to add the ENr, my count is simply wrong.
I tried to connect with simple:

```<code>SELECT ENr, Employee.. FROM travel, employee
</code>```

And also with an INNER JOIN.

Hope somebody could help me out :)

答:
Never use commas in the FROM clause.  Always use proper, explicit JOIN syntax.

You need JOIN conditions:

```<code>SELECT e.name, e.eNR, COUNT(*), AVG(t.costs)
FROM employee e JOIN
     travel t
     ON e.name = t.name
GROUP BY e.name, e.eNR;
</code>```

Additional comments:

When you have more than one table in a query, use table aliases and qualified column names.

Include all non-aggregated columns in the GROUP BY.

name is a lousy foreign key.  Usually, you want foreign keys to be unique (names may not be unique).  And numbers are more efficient for indexing purposes.

Body:
I have the following Database Structure

Table Employee:

Name     ENr
Name 1   1
Name 2   2
Name 3   3
...

Table Travel:

Employee  Costs
Name 1    8000
Name 1    56000
Name 2    800

and so on.

Now I want to Select The Name of the employees, the Count of the Travels and the Average Costs, as well as the ENr

Thats my SQL Select so far:

SELECT   employee,  COUNT(travel.employee), AVG(costs) FROM  travel  GROUP BY employee

However, as soon as I try to connect with the employee Table to add the ENr, my count is simply wrong.
I tried to connect with simple:

SELECT ENr, Employee.. FROM travel, employee

And also with an INNER JOIN.

Hope somebody could help me out :)

Body:
Never use commas in the FROM clause.  Always use proper, explicit JOIN syntax.

You need JOIN conditions:

SELECT e.name, e.eNR, COUNT(*), AVG(t.costs)
FROM employee e JOIN
     travel t
     ON e.name = t.name
GROUP BY e.name, e.eNR;

Additional comments:

When you have more than one table in a query, use table aliases and qualified column names.

Include all non-aggregated columns in the GROUP BY.

name is a lousy foreign key.  Usually, you want foreign keys to be unique (names may not be unique).  And numbers are more efficient for indexing purposes.


问:
Uncaught Error: [$injector:modulerr] ui.tree
I have my app.js:

```<code>angular.module('myApp', ['ui.tree'])
  .controller('myCtrl', function($scope) {
    $scope.remove = function(scope) {
      scope.remove();
    };

    $scope.toggle = function(scope) {
      scope.toggle();
    };

    $scope.moveLastToTheBeginning = function() {
      var a = $scope.data.pop();
      $scope.data.splice(0, 0, a);
    };

    $scope.newSubItem = function(scope) {
      var nodeData = scope.$modelValue;
      nodeData.nodes.push({
        id: nodeData.id * 10 + nodeData.nodes.length,
        title: nodeData.title + '.' + (nodeData.nodes.length + 1),
        nodes: []
      });
    };

    $scope.collapseAll = function() {
      $scope.$broadcast('angular-ui-tree:collapse-all');
    };

    $scope.expandAll = function() {
      $scope.$broadcast('angular-ui-tree:expand-all');
    };
</code>```

The index.html starts with:

```<code><script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="angular-ui-tree.min.js"></script>
<link rel="stylesheet" type="text/css" href="angular-ui-tree.min.css">
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <!-- Nested node template -->
</code>```

I have angular-ui-tree.min.js and angular.min.js in the same folder where app.js is. Still getting the below error:

```<code>angular.min.js:6 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.11/$injector/modulerr?p0=myApp&p1=Error%3A%20%5B%24injector%3Anomod%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.5.11%2F%24injector%2Fnomod%3Fp0%3DmyApp%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A6%3A426%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A25%3A235%0A%20%20%20%20at%20b%20(http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A24%3A282)%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A25%3A20%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A40%3A17%0A%20%20%20%20at%20q%20(http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A7%3A371)%0A%20%20%20%20at%20g%20(http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A39%3A382)%0A%20%20%20%20at%20fb%20(http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A43%3A381)%0A%20%20%20%20at%20c%20(http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A21%3A19)%0A%20%20%20%20at%20Gc%20(http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A21%3A332)
    at angular.min.js:6
    at angular.min.js:40
    at q (angular.min.js:7)
    at g (angular.min.js:39)
    at fb (angular.min.js:43)
    at c (angular.min.js:21)
    at Gc (angular.min.js:21)
    at se (angular.min.js:20)
    at angular.min.js:323
    at HTMLDocument.b (angular.min.js:192)
</code>```

答:
As said in the comments, there might be an error in your versions (Angular & UI Tree).

See this Plunkr working: https://plnkr.co/edit/U2U5vMi7m9G8BzC494ma?p=preview

```<code>  <head>
    <script data-require="angular.js@1.6.5" data-semver="1.6.5" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-tree/2.22.6/angular-ui-tree.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-tree/2.22.6/angular-ui-tree.min.css" />
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
</code>```

Body:
I have my app.js:

angular.module('myApp', ['ui.tree'])
  .controller('myCtrl', function($scope) {
    $scope.remove = function(scope) {
      scope.remove();
    };

    $scope.toggle = function(scope) {
      scope.toggle();
    };

    $scope.moveLastToTheBeginning = function() {
      var a = $scope.data.pop();
      $scope.data.splice(0, 0, a);
    };

    $scope.newSubItem = function(scope) {
      var nodeData = scope.$modelValue;
      nodeData.nodes.push({
        id: nodeData.id * 10 + nodeData.nodes.length,
        title: nodeData.title + '.' + (nodeData.nodes.length + 1),
        nodes: []
      });
    };

    $scope.collapseAll = function() {
      $scope.$broadcast('angular-ui-tree:collapse-all');
    };

    $scope.expandAll = function() {
      $scope.$broadcast('angular-ui-tree:expand-all');
    };

The index.html starts with:

<link rel="stylesheet" type="text/css" href="angular-ui-tree.min.css">
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">

I have angular-ui-tree.min.js and angular.min.js in the same folder where app.js is. Still getting the below error:

angular.min.js:6 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.11/$injector/modulerr?p0=myApp&p1=Error%3A%20%5B%24injector%3Anomod%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.5.11%2F%24injector%2Fnomod%3Fp0%3DmyApp%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A6%3A426%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A25%3A235%0A%20%20%20%20at%20b%20(http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A24%3A282)%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A25%3A20%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A40%3A17%0A%20%20%20%20at%20q%20(http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A7%3A371)%0A%20%20%20%20at%20g%20(http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A39%3A382)%0A%20%20%20%20at%20fb%20(http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A43%3A381)%0A%20%20%20%20at%20c%20(http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A21%3A19)%0A%20%20%20%20at%20Gc%20(http%3A%2F%2Flocalhost%3A8000%2Fangular.min.js%3A21%3A332)
    at angular.min.js:6
    at angular.min.js:40
    at q (angular.min.js:7)
    at g (angular.min.js:39)
    at fb (angular.min.js:43)
    at c (angular.min.js:21)
    at Gc (angular.min.js:21)
    at se (angular.min.js:20)
    at angular.min.js:323
    at HTMLDocument.b (angular.min.js:192)

Body:
As said in the comments, there might be an error in your versions (Angular & UI Tree).

See this Plunkr working: https://plnkr.co/edit/U2U5vMi7m9G8BzC494ma?p=preview

  <head>
    <script data-require="angular.js@1.6.5" data-semver="1.6.5" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-tree/2.22.6/angular-ui-tree.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-tree/2.22.6/angular-ui-tree.min.css" />
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>


问:
How to correctly write parameter in url when scope is array type?
I created a scope and pointed it to the array type.

```<code>has_scope: by_industry,: type =>: array
</code>```

And now I want to make this scope working.

I tried to pass parameter in url like this:

```<code>http://localhost:3000/v1/find_friends?by_industry=[1,2]
</code>```

Does not work.

How to correctly write parameter in url when scope is array type?

答:
To pass arrays through query parameters you use the key + brackets syntax:

```<code>?foo[]=1&foo[]=2
</code>```

It's klunky and its ugly but thats how its been done since the early days of the web and this old CGI convention is used by Rack. The main advantage vs foo=[1,2] is that it is language agnostic and the params can be parsed out without interpreting the string (which is a security hazard).

Body:
I created a scope and pointed it to the array type.

has_scope: by_industry,: type =>: array

And now I want to make this scope working.

I tried to pass parameter in url like this:

http://localhost:3000/v1/find_friends?by_industry=[1,2]

Does not work.

How to correctly write parameter in url when scope is array type?

Body:
To pass arrays through query parameters you use the key + brackets syntax:

?foo[]=1&foo[]=2

It's klunky and its ugly but thats how its been done since the early days of the web and this old CGI convention is used by Rack. The main advantage vs foo=[1,2] is that it is language agnostic and the params can be parsed out without interpreting the string (which is a security hazard).


答:
Easy way to make immutable object in JS is to use Object.freeze.

I created your input array as:

```<code>const array1 = Object.freeze([
    Object.freeze([ 1, 2 ]),
    Object.freeze([ 3, 4 ])
])
</code>```

Then, when I tried to call your function I got:

```<code>Uncaught TypeError: Cannot add/remove sealed array elements
at Array.shift (<anonymous>)
at arr.reduce (<anonymous>:7:38)
at Array.reduce (<anonymous>)
at roundRobin (<anonymous>:4:28)
at <anonymous>:6:17
</code>```

You're using shift, which is mutating orignal array.

Replace it with Array.slice(0,1)[0] and it will start working.

Title: RoundRobin functional approach - why does my function have side effects?

Body:
Objective

I am trying to create a Round Robin algorithm ( https://en.wikipedia.org/wiki/Round-robin_scheduling ) in a pure functional way.

This function, is supposed to received an array like the following:

[
    [ 1, 2 ],
    [ 3, 4 ]
]

And produce the following output:

[ 1, 3, 2, 4 ]

Code

To achieve this, I decided to implement round robin recursively like the following:

const roundRobin = (arr, results) => {
    if (arr.length === 0) return results;

    const newResults = arr.reduce((acc, current) => {

        if (current.length > 0) {
            acc.results.push(current.shift());
            acc.arr.push(current);
        }
        return acc;

    }, { arr: [], results });

    return roundRobin(newResults.arr, newResults.results);
};

Here, I feel up an array of results, and I finish when I have nothing left to add to it. One would use this code like the following:

const array =     [
        [ 1, 2 ],
        [ 3, 4 ]
    ];

const result = roundRobin( array, [] );

Problem

In my code I am using reduce in my arr parameter to ensure I don't modify the original. However, if I print array before using roundRobin and after, the variable is changed ! I mutate it somehow!

Questions:

If I am using reduce, which is pure, how am I mutating my parameters?

Is there another pure/functional way of implementing roundRobin?

Body:
Easy way to make immutable object in JS is to use Object.freeze.

I created your input array as:

const array1 = Object.freeze([
    Object.freeze([ 1, 2 ]),
    Object.freeze([ 3, 4 ])
])

Then, when I tried to call your function I got:

Uncaught TypeError: Cannot add/remove sealed array elements
at Array.shift (<anonymous>)
at arr.reduce (<anonymous>:7:38)
at Array.reduce (<anonymous>)
at roundRobin (<anonymous>:4:28)
at <anonymous>:6:17

You're using shift, which is mutating orignal array.

Replace it with Array.slice(0,1)[0] and it will start working.


问:
how to parse or convert
Is there easyer way to parse in c# then this:

```<code>float temp;
if (float.TryParse(quantity.ToString(), out temp))
{
     noteProduct.Quantity = temp;
}
</code>```

Thanks

答:
This is how I solved it. This is more easier to use instead of declaring temp variables and make if statements. </p>

```<code>   public class Parsers
    {
        private Parsers() { }

        public static void SetLong(ref long item, object value)
        {
            long temp;
            if (value != null && long.TryParse(value.ToString(), out temp)) { item = temp; }
        }

        public static void SetDateTime(ref DateTime item, object value)
        {
            DateTime temp;
            if (value != null && DateTime.TryParse(value.ToString(), out temp)) { item = temp; }
        }

        public static void SetInt(ref int item, object value)
        {
            int temp;
            if (value != null && int.TryParse(value.ToString(), out temp)) { item = temp; }
        }

        public static void SetString(ref string item, object value)
        {
            if (value != null) { item = value.ToString(); }
        }
    }
</code>```

Title: how to parse or convert

Body:
Is there easyer way to parse in c# then this:

float temp;
if (float.TryParse(quantity.ToString(), out temp))
{
     noteProduct.Quantity = temp;
}

Thanks

Body:
This is how I solved it. This is more easier to use instead of declaring temp variables and make if statements.

   public class Parsers
    {
        private Parsers() { }

        public static void SetLong(ref long item, object value)
        {
            long temp;
            if (value != null && long.TryParse(value.ToString(), out temp)) { item = temp; }
        }

        public static void SetDateTime(ref DateTime item, object value)
        {
            DateTime temp;
            if (value != null && DateTime.TryParse(value.ToString(), out temp)) { item = temp; }
        }

        public static void SetInt(ref int item, object value)
        {
            int temp;
            if (value != null && int.TryParse(value.ToString(), out temp)) { item = temp; }
        }

        public static void SetString(ref string item, object value)
        {
            if (value != null) { item = value.ToString(); }
        }
    }


问:
Best open source Mixed Integer Optimization Solver
I am using CPLEX for solving huge optimization models (more than 100k variables) now I'd like to see if I can find an open source alternative, I solve mixed integer problems (MILP) and CPLEX works great but it is very expensive if we want to scale so I really need to find an alternative or start writing our own ad-hoc optimization library (which will be painful)

Any suggestion/insight would be much appreciated

答:
I am surprised that nobody has mentioned MIPCL (http://www.mipcl-cpp.appspot.com/index.html). This solver claims to be  open source under LGPL license (source: http://www.mipcl-cpp.appspot.com/licence.html), thus it is also suitable to be used in non-open-source applications. But what is missing to be really open source is the source code of the solver itself.

Hans Mittelmann very recently (10 Sep 2017) did Mixed Integer Linear Programming Benchmark: http://plato.asu.edu/ftp/milpc.html (you might also be interested in looking at the overview page http://plato.asu.edu/bench.html or the slides of his talk: http://plato.asu.edu/talks/informs2017.pdf).

In the Mixed Integer Linear Programming Benchmark with 12 threads and a time limit of 2 hours MIPCL managed to solve 79 instances. Only the commercial solvers CPLEX, Gurobi and XPRESS managed to solve more under the given constraints (86 or 87 instances, respectively).

Also in terms of the chosen performance metric (again using 12 threads) MIPCL is faster than the benchmarked SCIP derivates (FSCIPC, FSCIPS) and the open source solver CBC. Again only the commercial solvers CPLEX, Gurobi and XPRESS outcompete MIPCL significantly in terms of performance.

OwnerDisplayName: Siamak

LastEditorDisplayName: Zach Scrivena


问:
Android 7 open APK with ACTION_VIEW not working (Package installer has stopped)
My app has an auto update feature which download an APK and then uses a Intent.ACTION_VIEW to open the package installer.

Up to 7 it worked perfectly (by feeding the Intent with a normal file://)

With Android 7 I had to change to use a FileProvider. The only difference in the code is:

```<code>Intent installIntent = new Intent(Intent.ACTION_VIEW);
          if (android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
            installIntent.setDataAndType(uri,
                manager.getMimeTypeForDownloadedFile(downloadId));
          } else {

            Uri apkUri = FileProvider.getUriForFile(AutoUpdate.this,
                BuildConfig.APPLICATION_ID, file);
              installIntent.setDataAndType(apkUri,manager.getMimeTypeForDownloadedFile(downloadId));
          }
          activity.startActivity(installIntent);
</code>```

Once the startActivity is called I get this every single time

Is this a bug with Android 7 ? Or something/permission is missing my side ?

EDIT AndroidManifest

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.READ_LOGS" />

 <application ...>
 ...
   <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.myapp"
            android:exported="false"
            android:enabled="true"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
  </application>
</code>```

The path xmlfile

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="myfolder" path="."/>
</paths>
</code>```

答:
try like below, it helped me and its working in Android N7.0.</p>

```<code>File toInstall = new File(appDirectory, appName + ".apk");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    Uri apkUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", toInstall);
    Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
    intent.setData(apkUri);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    activity.startActivity(intent);
} else {
    Uri apkUri = Uri.fromFile(toInstall);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    activity.startActivity(intent);
}
</code>```

Body:
My app has an auto update feature which download an APK and then uses a Intent.ACTION_VIEW to open the package installer.

Up to 7 it worked perfectly (by feeding the Intent with a normal file://)

With Android 7 I had to change to use a FileProvider. The only difference in the code is:

Intent installIntent = new Intent(Intent.ACTION_VIEW);
          if (android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
            installIntent.setDataAndType(uri,
                manager.getMimeTypeForDownloadedFile(downloadId));
          } else {

            Uri apkUri = FileProvider.getUriForFile(AutoUpdate.this,
                BuildConfig.APPLICATION_ID, file);
              installIntent.setDataAndType(apkUri,manager.getMimeTypeForDownloadedFile(downloadId));
          }
          activity.startActivity(installIntent);

Once the startActivity is called I get this every single time

Is this a bug with Android 7 ? Or something/permission is missing my side ?

EDIT AndroidManifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.READ_LOGS" />

 <application ...>
 ...
   <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.myapp"
            android:exported="false"
            android:enabled="true"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
  </application>

The path xmlfile

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="myfolder" path="."/>
</paths>

Body:
try like below, it helped me and its working in Android N7.0.

File toInstall = new File(appDirectory, appName + ".apk");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    Uri apkUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", toInstall);
    Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
    intent.setData(apkUri);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    activity.startActivity(intent);
} else {
    Uri apkUri = Uri.fromFile(toInstall);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    activity.startActivity(intent);
}


问:
Creating Coupon counter click
I am trying to create a coupon click counter.

I received the default number of clicks using the code

```<code><?php $couponusers = get_field('coupon_users'); ?>
</code>```

And I displayed the default number of clicks using the code,

```<code><p><?php echo $couponusers ?></p>
</code>```

Now, I want to increase the value of ‘coupon_users’ whenever a click is made. Any suggestions on how to do this?

The page I need help with: https://deals.onlinerockershub.com/bluehost-web-hosting/

答:
Add this action to your functions.php

function coupon_callback() {
    //
    // Add here cookie check
    //
    if(is_page('1')){ // ID of "Thank you for coupon click" page
        update_field('coupon_users',$couponusers); // or similar
    }
    return;
}
add_filter( 'wp', 'coupon_callback' );

Title: Creating Coupon counter click

Body:
I am trying to create a coupon click counter.

I received the default number of clicks using the code

<?php $couponusers = get_field('coupon_users'); ?>

And I displayed the default number of clicks using the code,

<?php echo $couponusers ?>

Now, I want to increase the value of ‘coupon_users’ whenever a click is made. Any suggestions on how to do this?

The page I need help with: https://deals.onlinerockershub.com/bluehost-web-hosting/


问:
how to get this json object table filter working
I have a website with a list of json objects arranged something like this:

```<code> [
    {
        "a": true or false,
        "b": "information",
        "c": "information",
        "d": "information",
        "e": "information"
    },
    ...
 ]
</code>```

The idea of this code is to print out all the objects on a table and have a checkbox which filters out the false objects out when needed. The site is supposed to just have the the table with unfiltered object on there, but after I added the checkbox event listener the full table list disappeared. When I check the checkbox I get the filtered objects and it keeps adding more and more of the same filtered content on the bottom of the table if I keep re-clicking it.

What am I doing wrong here? Here is the code I have:

```<code>var stuff = document.getElementById("stuff-info");
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'url');
ourRequest.onload = function() {
    var ourData = JSON.parse(ourRequest.responseText);
    renderHTML(ourData);
};
ourRequest.send();

function renderHTML(data) {
    var htmlString = "";
    var filteredData = data.filter(function(element) {
        return element.a
    });
    var checkbox = document.querySelector("input[name=hide]");

    checkbox.addEventListener('change', function() {
        if (this.checked) {
            for (i = 0; i < filteredData.length; i++) {
                htmlString += "<table><tr><td>" + filteredData[i].b + "</td><td>" + filteredData[i].c + "</td><td>" + filteredData[i].d + "</td><td>" + filteredData[i].e + "</td></tr>"
            }
        } else {
            for (i = 0; i < data.length; i++) {
                htmlString += "<table><tr><td>" + data[i].b + "</td><td>" + data[i].c + "</td><td>" + data[i].d + "</td><td>" + data[i].e + "</td></tr>"
            }
        }
        stuff.insertAdjacentHTML('beforeend', htmlString);
    });
}
</code>```

答:
Might be easier to filter with CSS selector:

#filter:checked ~ table .filter { display: none }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type=checkbox id=filter> Filter

<table border=1>
  <tr class=filter><td>1</td><td>a</td></tr>
  <tr><td>2</td><td>b</td></tr>
  <tr class=filter><td>3</td><td>c</td></tr>
  <tr><td>4</td><td>d</td></tr>
</table></code>```

Body:
I have a website with a list of json objects arranged something like this:

 [
    {
        "a": true or false,
        "b": "information",
        "c": "information",
        "d": "information",
        "e": "information"
    },
    ...
 ]

The idea of this code is to print out all the objects on a table and have a checkbox which filters out the false objects out when needed. The site is supposed to just have the the table with unfiltered object on there, but after I added the checkbox event listener the full table list disappeared. When I check the checkbox I get the filtered objects and it keeps adding more and more of the same filtered content on the bottom of the table if I keep re-clicking it.

What am I doing wrong here? Here is the code I have:

var stuff = document.getElementById("stuff-info");
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'url');
ourRequest.onload = function() {
    var ourData = JSON.parse(ourRequest.responseText);
    renderHTML(ourData);
};
ourRequest.send();

function renderHTML(data) {
    var htmlString = "";
    var filteredData = data.filter(function(element) {
        return element.a
    });
    var checkbox = document.querySelector("input[name=hide]");

    checkbox.addEventListener('change', function() {
        if (this.checked) {
            for (i = 0; i < filteredData.length; i++) {
                htmlString += "

" + filteredData[i].b + "	" + filteredData[i].c + "	" + filteredData[i].d + "	" + filteredData[i].e + "
"
            }
        } else {
            for (i = 0; i < data.length; i++) {
                htmlString += "

" + data[i].b + "	" + data[i].c + "	" + data[i].d + "	" + data[i].e + "
"
            }
        }
        stuff.insertAdjacentHTML('beforeend', htmlString);
    });
}

Body:
Might be easier to filter with CSS selector:

#filter:checked ~ table .filter { display: none }

<input type=checkbox id=filter> Filter

<table border=1>
  <tr class=filter><td>1</td><td>a</td></tr>
  <tr><td>2</td><td>b</td></tr>
  <tr class=filter><td>3</td><td>c</td></tr>
  <tr><td>4</td><td>d</td></tr>
</table>


答:
Surround every macro with () - it's a good habit and will save you some unexpected behavior.

example:

```<code>#define FULLSCREEN_MODE         (ORIENTATION_IS_PORTRAIT?460:300)
</code>```

The preprocessor does a direct replacement of one piece of text for another. If you have order of operations issues, the parentheses will save you.

Title: Why does adding and subtracting two #define'd macros not work on iPhone / Objective-c

Body:
In my iPhone app, I have this in my .h file

#define ORIENTATION_IS_PORTRAIT UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])
#define FULLSCREEN_MODE         ORIENTATION_IS_PORTRAIT?460:300
#define AD_HEIGHT               ORIENTATION_IS_PORTRAIT?50:32
#define FULLSCREEN_MODE_WITH_AD FULLSCREEN_MODE - AD_HEIGHT //doesn't work

To sum it up, I have a macro to detect the orientation. I have another for the height of my UIWebView when it is in full screen mode (activated by a button press). I need to keep the ad at the bottom. However, to get the height of the UIWebView minus the ad height will only return the AD_HEIGHT.

For addition, (FULLSCREEN_MODE + AD_HEIGHT) returns the FULLSCREEN_MODE only.

Also, when using constants, where exactly do I put them. I searched and could only find answers like "in the .m file", but where??

Body:
Surround every macro with () - it's a good habit and will save you some unexpected behavior.

example:

#define FULLSCREEN_MODE         (ORIENTATION_IS_PORTRAIT?460:300)

The preprocessor does a direct replacement of one piece of text for another. If you have order of operations issues, the parentheses will save you.


问:
typeof 90/'hi' is NaN while typeof (90/'hi') is number. Why so?
I was playing around the NaN of JavaScript and found some strange behavior while using typeof operator on a result of number/string.
why so?</p>

答:
```<code>typeof NaN === 'number'; // Despite being "Not-A-Number"
</code>```

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

And the precedence of typeof is higher than /, so you are evaluating (typeof '90')/'hi', which is NaN

source: https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Body:
typeof NaN === 'number'; // Despite being "Not-A-Number"

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

And the precedence of typeof is higher than /, so you are evaluating (typeof '90')/'hi', which is NaN

source: https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Operators/Operator_Precedence


问:
Does creating new object reseting properties of class
I am new to OO programming. Suppose I have class and 2d array inside full of values.
If I create object of a class in another class, is that 2d array going to be empty?
If yes, what is the way to preserve values, while making new instance of a class?</p>

答:
It will be empty. If you define in the class constructor the method which fill the array, always that constructor is thrown, the array will be full of values.

Something like:

```<code>public myclass() {

int array[] = new int[20];
...
}
</code>```

Body:
It will be empty. If you define in the class constructor the method which fill the array, always that constructor is thrown, the array will be full of values.

Something like:

public myclass() {

int array[] = new int[20];
...
}


问:
Karaf OSGI How to copy files as part of postProcessing?
I have some files that I need to copy to a directory configured in the .cfg file as part of installing the bundle in Karaf server. I couldn't figure out what exactly is the js method to invoke. Below id the snippet I used to extract a jar using postProcess  in metatype.js, but how do I copy a file..

var postProcess = function(group, map ) {
       if(map["destination.script.path"] && map["destination.script.path"].trim()!='') {
               scope.installTasks.expandResources(java.lang.System.getProperty('karaf.base') +"/data/hrc/install/source/resources.jar",map["destination.script.path"]+"/scripts",false,
         function(key,success)  {
       print("expanded " + success);
   },
   function(key,fail){
       print(fail.getMessage());
   });
       }
};

var success = function(source,val){
 //print(val);
}
var fail = function(source,e){
 //print(source);
}```

This is how my OSGI-INF looks like

答: Sorry, installTasks is an internal utility used in my project.</p>

Body:
I have some files that I need to copy to a directory configured in the .cfg file as part of installing the bundle in Karaf server. I couldn't figure out what exactly is the js method to invoke. Below id the snippet I used to extract a jar using postProcess  in metatype.js, but how do I copy a file..

var postProcess = function(group, map ) {
       if(map["destination.script.path"] && map["destination.script.path"].trim()!='') {
               scope.installTasks.expandResources(java.lang.System.getProperty('karaf.base') +"/data/hrc/install/source/resources.jar",map["destination.script.path"]+"/scripts",false,
         function(key,success)  {
       print("expanded " + success);
   },
   function(key,fail){
       print(fail.getMessage());
   });
       }
};

var success = function(source,val){
 //print(val);
}
var fail = function(source,e){
 //print(source);
}

This is how my OSGI-INF looks like


问:
Does PHP 5.x have some kind of HashSet or Set Class?
I'm used to Java where I have HashSets, ArrayLists and other Collections. But I'm workting on a PHP project right now.

I need to create a set, fill that set with objects (Strings in this case), but the Set can only contain each object once. In addition I want to remove a certain object in the end from this set if it exists. This would be pretty easy with the Java collection classes. But how can I implement that in PHP?

Are there any methods of array() that I am missing? I'm using PHP 5.3.

答:
I'm not exactly sure, but I think SplObjectStorage does what you want:

http://php.net/manual/en/class.splobjectstorage.php

Oh, and strings are not objects. So you can just do this:

```<code>$foo['bar'] = true;
</code>```

and the array will work as a way to uniquely store the strings.

Body:
I'm not exactly sure, but I think SplObjectStorage does what you want:

http://php.net/manual/en/class.splobjectstorage.php

Oh, and strings are not objects. So you can just do this:

$foo['bar'] = true;

and the array will work as a way to uniquely store the strings.


问:
Is there a data race if pthread_cond_signal is the last call in a thread?
Compiling this with -fsanitize=thread yields a data race report between pthread_cond_signal and pthread_cond_destroy:

```<code>#include <stdio.h>
#include <pthread.h>
#include <err.h>

bool done = false;

pthread_mutex_t mutex;
pthread_cond_t cond;

void *func(void *)
{
    pthread_mutex_lock(&mutex);

    done = true;

    pthread_mutex_unlock(&mutex);

    pthread_cond_signal(&cond);

    return NULL;
}

int main()
{
    pthread_t thread;

    pthread_cond_init(&cond, NULL);
    pthread_mutex_init(&mutex, NULL);

    if (pthread_create(&thread, NULL, func, NULL) != 0)
        err(1, "pthread_create()");

    pthread_mutex_lock(&mutex);

    while (!done)
        pthread_cond_wait(&cond, &mutex);

    pthread_mutex_unlock(&mutex);

    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mutex);

    pthread_join(thread, NULL);

    return 0;
}
</code>```

The report goes away if I call pthread_mutex_unlock after pthread_cond_signal. But the manual says pthread_cond_signal doesn't need the mutex to be taken. Is it documented anywhere that calling pthread_cond_signal as the last call that references a pthread_cond_t, and destroying it from the thread that does pthread_cond_wait is not legal ?

答:
It is totally legal to call pthread_cond_signal as the last call.
And it is also not needed to hold a mutex for the the pthread_cond_signal.

But in your case if you do not do this it is possible that you create a data race. This is illegal.

In your case it is possible that when your thread unlocks the mutex your main thread starts to run and destroys the condition. This is your data race.

So you have two possibilities.

Either you hold the mutex when calling pthread_cond_signal so that your main thread cannot access the condition before it is used.

Or you can first join your thread and then destroy the condition. Both will work.

But in general i recommend to stick to std::thread, std::mutex and std::condition_variable

Body:
Compiling this with -fsanitize=thread yields a data race report between pthread_cond_signal and pthread_cond_destroy:

#include <stdio.h>
#include <pthread.h>
#include <err.h>

bool done = false;

pthread_mutex_t mutex;
pthread_cond_t cond;

void *func(void *)
{
    pthread_mutex_lock(&mutex);

    done = true;

    pthread_mutex_unlock(&mutex);

    pthread_cond_signal(&cond);

    return NULL;
}

int main()
{
    pthread_t thread;

    pthread_cond_init(&cond, NULL);
    pthread_mutex_init(&mutex, NULL);

    if (pthread_create(&thread, NULL, func, NULL) != 0)
        err(1, "pthread_create()");

    pthread_mutex_lock(&mutex);

    while (!done)
        pthread_cond_wait(&cond, &mutex);

    pthread_mutex_unlock(&mutex);

    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mutex);

    pthread_join(thread, NULL);

    return 0;
}

The report goes away if I call pthread_mutex_unlock after pthread_cond_signal. But the manual says pthread_cond_signal doesn't need the mutex to be taken. Is it documented anywhere that calling pthread_cond_signal as the last call that references a pthread_cond_t, and destroying it from the thread that does pthread_cond_wait is not legal ?


答:
Is it documented anywhere that calling pthread_cond_signal as the last call that references a pthread_cond_t, and destroying it from the thread that does pthread_cond_wait is not legal ?

They cannot cover all corner cases in documentation. Yes it is legal to call pthread_cond_signal() after mutex unlocked, it is not legal to destroy it at the same time as pthread_cond_signal() can be called.

Title: Is there a data race if pthread_cond_signal is the last call in a thread?


问:
What is the best perl module to extract text from a pdf?
What is the best way to extract text from a pdf?</p>

答:
The CAM::PDF module is pretty useful for extracting text and maintaining some information about where it came from in the document. It installs /usr/local/bin/getpdftext.pl which demonstrates simple extraction. However, CAM::PDF can only read PDFs that are completely valid.

If you are dealing with ill-formed PDFs, you may need a more lenient parser, such as pdftotext. It dumps foo.pdf to foo.txt, which you could then read into Perl.


问:
Why does Managed ODP.Net demand SERVICE_NAME?
I am migrating a .Net 4.6.2 application from using Microsoft's System.Data.OracleClient to Oracle's own managed ODP.Net (Nuget package, version 12.2.11)for connecting to an Oracle database. I have the Oracle client installed (11gR2) and apart from changing references, using clauses, type names etc the code is pretty much the same. However, whilst my pre-migrate code connects quite happily, the post-migrate will not connect. Instead it throws an OracleException

```<code>ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA.
</code>```

The tnsnames.ora file is the same, and the application's connection string is the same, and I have never before needed to specify a service name.

TnsNames.ora:

```<code>ORACLEDBSERVER2 =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = OracleDBServer2)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SID = orcdb10g)
      (SERVER = DEDICATED)
    )
</code>```

Connection string:

```<code>USER ID=MATTESTNHADMIN;PASSWORD=XXXXX;DATA SOURCE=oracledbserver2
</code>```

Why is it now demanding a SERVICE NAME? Even if I add a clause to the CONNECT_DATA part (SERVICE_NAME = orcdb10g) I get the same error.

答:
I assume your program does not find the tnsnames.ora file. Unlike the old drivers the ODP.NET managed driver does not read TNS_ADMIN value from the Registy.

See this answer https://stackoverflow.com/a/28283924/3027266 to see how ODP.NET managed driver is looking for tnsnames.ora file.

Note, when you use ODP.NET managed driver then you don't have to install any further Oracle client.

Body:
I am migrating a .Net 4.6.2 application from using Microsoft's System.Data.OracleClient to Oracle's own managed ODP.Net (Nuget package, version 12.2.11)for connecting to an Oracle database. I have the Oracle client installed (11gR2) and apart from changing references, using clauses, type names etc the code is pretty much the same. However, whilst my pre-migrate code connects quite happily, the post-migrate will not connect. Instead it throws an OracleException

ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA.

The tnsnames.ora file is the same, and the application's connection string is the same, and I have never before needed to specify a service name.

TnsNames.ora:

ORACLEDBSERVER2 =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = OracleDBServer2)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SID = orcdb10g)
      (SERVER = DEDICATED)
    )

Connection string:

USER ID=MATTESTNHADMIN;PASSWORD=XXXXX;DATA SOURCE=oracledbserver2

Why is it now demanding a SERVICE NAME? Even if I add a clause to the CONNECT_DATA part (SERVICE_NAME = orcdb10g) I get the same error.


问:
How do you initialise an Angular 4 model from the serving ASP.NET MVC page?
I would like to initialise an Angular 4 application's model with some data that I supply on my ASP.NET MVC razor generated page. [I suggest however that the server rendering mechanism is irrelevant.]

I've attempted to construct the minimum viable example below.

To start I created the application using ng new stackoverflow-question. Then I edited the following files:

src/index.html

This page would normally be generated on the server side, but for simplicity:

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>StackOverflow</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
  <script type="text/javascript">

  // I want this data to be injected into my Angular app's someDataFromTheHostPage field.
  // The below would normally be generated by server-side code.
  var someData = [
      { name: 'fido', kind: 'dog' },
      { name: 'mittens', kind: 'cat' },
      { name: 'gingernut', kind: 'hamster' }
    ];
  </script>
</body>
</html>
</code>```

src/app/app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  // I want this to be set by script on the page
  someDataFromTheHostPage : object = null;
}
```

<h2>src/app/app.component.html</h2>

```

    Welcome to {{title}}!

Here is the data from the host page:

```
  {{someDataFromTheHostPage | json}}
```
```

So, to reiterate the inline comments from the code above: I'm after a mechanism by which the data provided in the host page, index.html, can be injected into the app.component's field ready for binding the the html template.

This is actually a much simplified version of my app where the intention is for the data to be used to initialise an Angular Service.

I appreciate that there may be more than one way to achieve this so different answers for each mechanism would be welcome and then people can up vote the preferred way.

Many thanks.

答:
Option A - read/access the variable yourself

app.component.ts

```<code>declare var someData: any;

@Component({
    ...
})
export class AppComponent {
    someDataFromTheHostPage: any = someData; // <= window.someData
}
</code>```

Option B - use a decorator to read/access the variable

app.component.ts

```<code>import { HostPageVariable } from "./host-page-variable.decorator";

@Component({
    ...
})
export class AppComponent {
    @HostPageVariable("someData") // get the data from a variable called 'someData'
    someDataFromTheHostPage: any;

    @HostPageVariable() // auto-map the name of the variable - get the data from a variable called 'someData'
    someData: any;
}
</code>```

host-page-variable.decorator.ts

```<code>export function HostPageVariable(name?: string) {
    return function OnChangeHandler(target: any, propertyKey: string): void {
        if (name == undefined) {
            name = propertyKey;
        }
        Object.defineProperty(target, propertyKey, {
            get(): any {
                return window[name];
            }
        });
    };
}
</code>```

Body:
I would like to initialise an Angular 4 application's model with some data that I supply on my ASP.NET MVC razor generated page. [I suggest however that the server rendering mechanism is irrelevant.]

I've attempted to construct the minimum viable example below.

To start I created the application using ng new stackoverflow-question. Then I edited the following files:

src/index.html

This page would normally be generated on the server side, but for simplicity:

<!doctype html>

  <meta charset="utf-8">
  <title>StackOverflow</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

src/app/app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  // I want this to be set by script on the page
  someDataFromTheHostPage : object = null;
}

src/app/app.component.html

    Welcome to {{title}}!

Here is the data from the host page:

  {{someDataFromTheHostPage | json}}

So, to reiterate the inline comments from the code above: I'm after a mechanism by which the data provided in the host page, index.html, can be injected into the app.component's field ready for binding the the html template.

This is actually a much simplified version of my app where the intention is for the data to be used to initialise an Angular Service.

I appreciate that there may be more than one way to achieve this so different answers for each mechanism would be welcome and then people can up vote the preferred way.

Many thanks.

Body:
Option A - read/access the variable yourself

app.component.ts

declare var someData: any;

@Component({
    ...
})
export class AppComponent {
    someDataFromTheHostPage: any = someData; // <= window.someData
}

Option B - use a decorator to read/access the variable

app.component.ts

import { HostPageVariable } from "./host-page-variable.decorator";

@Component({
    ...
})
export class AppComponent {
    @HostPageVariable("someData") // get the data from a variable called 'someData'
    someDataFromTheHostPage: any;

    @HostPageVariable() // auto-map the name of the variable - get the data from a variable called 'someData'
    someData: any;
}

host-page-variable.decorator.ts

export function HostPageVariable(name?: string) {
    return function OnChangeHandler(target: any, propertyKey: string): void {
        if (name == undefined) {
            name = propertyKey;
        }
        Object.defineProperty(target, propertyKey, {
            get(): any {
                return window[name];
            }
        });
    };
}


问:
It takes forever to start a build in Jenkins and to find an idle slave for it
We are operating one Jenkins master and about 70 swarm slaves with various operating systems. All machines are virtual running on a VMware ESX server.

For some months we are faced with these issues:

When you manually trigger a build using the web interface it takes about ten minutes for the build to be scheduled as waiting in the list.

When the job finally is in the build queue, it takes another ten minutes for master to recognize there is an idle build node which can actually perform the build.

Sometimes a node is shown busy in the node list, but when you look at it the job there is already done.

I cannot present what I've done before, since I have no clue where to start with this. I'm thankful for any clue where to look at or what to try.

答: This is far from an answer, but this open issue is somewhat similar to what you describe.</p>


问:
Spring Mongo > How to get list AggregationOperations from Aggregation
I have a function that receive an Aggregation aggregation as a param.

I would like to get all AggregationOperation from aggregation. Is there any way to do it?

```<code>public Aggregation newCustomAggregation(Aggregation aggregation, Criteria c) {
    // How to get list operation aggregation there?
    listOperation.push(Aggregation.match(c));
    return Aggregation
            .newAggregation(listOperations);
}
</code>```

My purpose is new another Aggregation with my custom MatchAggregation.

答:
Aggregation has a property operations which will give you all applied operation in Aggregation.

```<code> protected List<AggregationOperation>   allOperations = aggregation.operations ;
</code>```

will give you all applied operations.

Body:
I have a function that receive an Aggregation aggregation as a param.

I would like to get all AggregationOperation from aggregation. Is there any way to do it?

public Aggregation newCustomAggregation(Aggregation aggregation, Criteria c) {
    // How to get list operation aggregation there?
    listOperation.push(Aggregation.match(c));
    return Aggregation
            .newAggregation(listOperations);
}

My purpose is new another Aggregation with my custom MatchAggregation.

Body:
Aggregation has a property operations which will give you all applied operation in Aggregation.

 protected List<AggregationOperation>   allOperations = aggregation.operations ;

will give you all applied operations.


问:
SAPUI5: Malformed URI literal syntax in key
I creating a SAPUI5 application using the "SAP Fiori Master-Detail Application" Template.  I have the Master and Detail pages working and properly connecting to my OData service.  What I am trying to do now is route the Detail page to a second (different) Detail page.

The first Detail page (I'll call Detail1) contains a list of the Detail2 objects.  Clicking one of those objects in a list should take you to the Detail2 page (where it displays even more information).

I created a new Detail2 View and Controller using WebIDE, so it came with some filler code.  I also created a new route in the manifest.json file:

```<code>{
    "name": "detail2Object",
    "pattern": "Detail2(Master={masterId},Id={detail1Id})",
    "titleTarget": "",
    "greedy": false,
    "target": ["master", "detail2"]
}

"detail2Object": {
    "viewType": "XML",
    "transition": "slide",
    "clearAggregation": true,
    "viewName": "Detail2",
    "title": "",
    "viewId": "detail2page",
    "viewLevel": 3
}
</code>```

As you can see from the pattern, the service takes in two parameters: Master and ID (which are the Master ID and the first Defects Id).

Testing the service independent from my application returns data just fine:  http://{root}.com:{port}/sap/opu/odata/sap/TEST_SRV/Detail2(Master='552364',Id='0004')

I created a NavTo function in my Detail1 controller to pass in the Master and Id parameters:

```<code>_onNav : function (oEvent) {
            // get the list item, either from the listItem parameter or from the event's source itself (will depend on the device-dependent mode).
            this._showDetail2(oEvent.getParameter("listItem") || oEvent.getSource());
},

_showDetail2 : function (oItem) {
            this.getRouter().navTo("detail2Object", {
                masterId: oItem.getBindingContext().getProperty("Master"),
                detail1Id: oItem.getBindingContext().getProperty("Id")
            });
}
</code>```

When I run the application through WebIDE testing (both with the live OData and with Mockdata I created) clicking on the Detail2 object in the Detail1 page navigates me to a new page that displays this error:

This <"ObjectName"> is not available

Going into the F12 tools, I see the following error:

MockServer: Malformed URI literal syntax in key 'Id' -

HTTP request
  failed400,Bad
  Request,{"error":{"code":400,"message":{"lang":"en","value":"Malformed
  URI literal syntax in key 'Id'"}}} -

This is occurring even though the url correctly pulled the parameters:

http://localhost:54634/webapp/test/mockServer.html?hc_reset&origional-url=mockServer.html&sap-ui-appCacheBuster=..%2F..%2F..%2F&sap-ui-xx-componentPreload=off#/Detail2(Master='552364',Id='0004')

Through a lot of research, the only thing I am finding is that this error may have something to do with the metadata file.  However, both Id's are of type Edm.String and they are both spelled the exact same way, so I don't think that's the issue.  Also, as stated earlier, the service runs just fine with the same parameters running independently from the application.

Any help would be greatly appreciated.

Update

Detail1 View which contains a list of the Detail2 objects:

```<code>        <List noDataText="Drop list items here" id="__list0" items="{DetailToDetail2}" headerText="Defects">
            <items>
                <ObjectListItem type="Navigation" title="{Detail2Title}" number="{Qty}" numberUnit="Detail Qty" press="_onNav">
                <attributes>
                    <ObjectAttribute text="{Detail2_Attr}" id="__attribute11" title="Detail2 Attr"/>
                    <ObjectAttribute id="__attribute12" title="Detail2 Attr2" text="{Detail2_Attr2}"/>
                </attributes>
                </ObjectListItem>
            </items>
        </List>
</code>```

The item="{DetailToDetail2}" appears as a NavigationProperty and Association in the metadata of service.

This is how it looks in the Detail1 Entity:

```<code><NavigationProperty Name="DetailToDetail2" Relationship="TEST_SRV.DetailToDetail2" FromRole="FromRole_DetailToDetail2" ToRole="ToRole_DetailToDetail2"/>
</code>```

This is the entire Detail2 Entity:

```<code>        <EntityType Name="Detail2" sap:content-version="1">
            <Key>
                <PropertyRef Name="Id"/>
                <PropertyRef Name="Master"/>
            </Key>
            <Property Name="Id" Type="Edm.String" Nullable="false" MaxLength="4" sap:unicode="false" sap:label="Id" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
            <Property Name="Master" Type="Edm.String" Nullable="false" MaxLength="12" sap:unicode="false" sap:label="Master" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
            <Property Name="Attr1" Type="Edm.String" MaxLength="40" sap:unicode="false" sap:label="Attribute 1" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
            <Property Name="Qty" Type="Edm.Int32" sap:unicode="false" sap:label="Detail Qty" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
            <Property Name="Attr2" Type="Edm.String" MaxLength="40" sap:unicode="false" sap:label="Attribute 2" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
            <Property Name="Attr3" Type="Edm.String" MaxLength="4" sap:unicode="false" sap:label="Attribute 3" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
        </EntityType>
</code>```

And here is the DetailToDetail2 Association:

```<code>        <Association Name="DetailToDetail2" sap:content-version="1">
            <End Type="TEST_SRV.Detail1" Multiplicity="1" Role="FromRole_DetailToDetail2"/>
            <End Type="TEST_SRV.Detail2" Multiplicity="*" Role="ToRole_DetailToDetail2"/>
            <ReferentialConstraint>
                <Principal Role="FromRole_DetailToDetail2">
                    <PropertyRef Name="Id"/>
                </Principal>
                <Dependent Role="ToRole_DetailToDetail2">
                    <PropertyRef Name="Master"/>
                </Dependent>
            </ReferentialConstraint>
        </Association>
</code>```

答:
I found the "Malformed URI" error was occurring not at the routing or navigation, but with the binding after getting to the page.

My Detail2 controllers _onObjectMatched function looked like this:

```<code>_onObjectMatched : function (oEvent) {
        var sObjectMasterId =  oEvent.getParameter("arguments").masterId;
        var sObjectDetailId =  oEvent.getParameter("arguments").detail1Id;
        this.getModel().metadataLoaded().then( function() {
          var sObjectPath = this.getModel().createKey("Detail2", {
            masterId:  sObjectMasterId,
            detail1Id : sObjectDetailId
          });
          this._bindView("/" + sObjectPath);
        }.bind(this));
</code>```

Through debugging I found that the sObjectPath variable was being set to Detail2(Id=null, Master=null). That is when I realized masterId and detail1Id are not the correct parameter names to use because we are not binding to the route, we are binding to the path.  So I replaced masterId with Master and detail1Id with Id:

```<code>_onObjectMatched : function (oEvent) {
    var sObjectMasterId =  oEvent.getParameter("arguments").masterId;
    var sObjectDetailId =  oEvent.getParameter("arguments").detail1Id;
    this.getModel().metadataLoaded().then( function() {
      var sObjectPath = this.getModel().createKey("Detail2", {
        Master:  sObjectMasterId,
        Id: sObjectDetailId
      });
      this._bindView("/" + sObjectPath);
    }.bind(this));
</code>```

Voila, it worked!

Thank you to everyone who responded and pointed me away from the routing and towards the binding.  I would suggest to anyone getting the "Malformed URI" error to review all bindings and navigation to verify that all parameters are spelt correctly.

Reviewing the Routing with Parameters tutorial was also a significant help.

Body:
I creating a SAPUI5 application using the "SAP Fiori Master-Detail Application" Template.  I have the Master and Detail pages working and properly connecting to my OData service.  What I am trying to do now is route the Detail page to a second (different) Detail page.

The first Detail page (I'll call Detail1) contains a list of the Detail2 objects.  Clicking one of those objects in a list should take you to the Detail2 page (where it displays even more information).

I created a new Detail2 View and Controller using WebIDE, so it came with some filler code.  I also created a new route in the manifest.json file:

{
    "name": "detail2Object",
    "pattern": "Detail2(Master={masterId},Id={detail1Id})",
    "titleTarget": "",
    "greedy": false,
    "target": ["master", "detail2"]
}

"detail2Object": {
    "viewType": "XML",
    "transition": "slide",
    "clearAggregation": true,
    "viewName": "Detail2",
    "title": "",
    "viewId": "detail2page",
    "viewLevel": 3
}

As you can see from the pattern, the service takes in two parameters: Master and ID (which are the Master ID and the first Defects Id).

Testing the service independent from my application returns data just fine:  http://{root}.com:{port}/sap/opu/odata/sap/TEST_SRV/Detail2(Master='552364',Id='0004')

I created a NavTo function in my Detail1 controller to pass in the Master and Id parameters:

_onNav : function (oEvent) {
            // get the list item, either from the listItem parameter or from the event's source itself (will depend on the device-dependent mode).
            this._showDetail2(oEvent.getParameter("listItem") || oEvent.getSource());
},

_showDetail2 : function (oItem) {
            this.getRouter().navTo("detail2Object", {
                masterId: oItem.getBindingContext().getProperty("Master"),
                detail1Id: oItem.getBindingContext().getProperty("Id")
            });
}

When I run the application through WebIDE testing (both with the live OData and with Mockdata I created) clicking on the Detail2 object in the Detail1 page navigates me to a new page that displays this error:

This <"ObjectName"> is not available

Going into the F12 tools, I see the following error:

MockServer: Malformed URI literal syntax in key 'Id' -

HTTP request
  failed400,Bad
  Request,{"error":{"code":400,"message":{"lang":"en","value":"Malformed
  URI literal syntax in key 'Id'"}}} -

This is occurring even though the url correctly pulled the parameters:

http://localhost:54634/webapp/test/mockServer.html?hc_reset&origional-url=mockServer.html&sap-ui-appCacheBuster=..%2F..%2F..%2F&sap-ui-xx-componentPreload=off#/Detail2(Master='552364',Id='0004')

Through a lot of research, the only thing I am finding is that this error may have something to do with the metadata file.  However, both Id's are of type Edm.String and they are both spelled the exact same way, so I don't think that's the issue.  Also, as stated earlier, the service runs just fine with the same parameters running independently from the application.

Any help would be greatly appreciated.

Update

Detail1 View which contains a list of the Detail2 objects:

        <List noDataText="Drop list items here" id="__list0" items="{DetailToDetail2}" headerText="Defects">
            <items>
                <ObjectListItem type="Navigation" title="{Detail2Title}" number="{Qty}" numberUnit="Detail Qty" press="_onNav">
                <attributes>
                    <ObjectAttribute text="{Detail2_Attr}" id="__attribute11" title="Detail2 Attr"/>
                    <ObjectAttribute id="__attribute12" title="Detail2 Attr2" text="{Detail2_Attr2}"/>
                </attributes>
                </ObjectListItem>
            </items>
        </List>

The item="{DetailToDetail2}" appears as a NavigationProperty and Association in the metadata of service.

This is how it looks in the Detail1 Entity:

<NavigationProperty Name="DetailToDetail2" Relationship="TEST_SRV.DetailToDetail2" FromRole="FromRole_DetailToDetail2" ToRole="ToRole_DetailToDetail2"/>

This is the entire Detail2 Entity:

        <EntityType Name="Detail2" sap:content-version="1">
            <Key>
                <PropertyRef Name="Id"/>
                <PropertyRef Name="Master"/>
            </Key>
            <Property Name="Id" Type="Edm.String" Nullable="false" MaxLength="4" sap:unicode="false" sap:label="Id" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
            <Property Name="Master" Type="Edm.String" Nullable="false" MaxLength="12" sap:unicode="false" sap:label="Master" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
            <Property Name="Attr1" Type="Edm.String" MaxLength="40" sap:unicode="false" sap:label="Attribute 1" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
            <Property Name="Qty" Type="Edm.Int32" sap:unicode="false" sap:label="Detail Qty" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
            <Property Name="Attr2" Type="Edm.String" MaxLength="40" sap:unicode="false" sap:label="Attribute 2" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
            <Property Name="Attr3" Type="Edm.String" MaxLength="4" sap:unicode="false" sap:label="Attribute 3" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
        </EntityType>

And here is the DetailToDetail2 Association:

        <Association Name="DetailToDetail2" sap:content-version="1">
            <End Type="TEST_SRV.Detail1" Multiplicity="1" Role="FromRole_DetailToDetail2"/>
            <End Type="TEST_SRV.Detail2" Multiplicity="*" Role="ToRole_DetailToDetail2"/>
            <ReferentialConstraint>
                <Principal Role="FromRole_DetailToDetail2">
                    <PropertyRef Name="Id"/>
                </Principal>
                <Dependent Role="ToRole_DetailToDetail2">
                    <PropertyRef Name="Master"/>
                </Dependent>
            </ReferentialConstraint>
        </Association>

Body:
I found the "Malformed URI" error was occurring not at the routing or navigation, but with the binding after getting to the page.

My Detail2 controllers _onObjectMatched function looked like this:

_onObjectMatched : function (oEvent) {
        var sObjectMasterId =  oEvent.getParameter("arguments").masterId;
        var sObjectDetailId =  oEvent.getParameter("arguments").detail1Id;
        this.getModel().metadataLoaded().then( function() {
          var sObjectPath = this.getModel().createKey("Detail2", {
            masterId:  sObjectMasterId,
            detail1Id : sObjectDetailId
          });
          this._bindView("/" + sObjectPath);
        }.bind(this));

Through debugging I found that the sObjectPath variable was being set to Detail2(Id=null, Master=null). That is when I realized masterId and detail1Id are not the correct parameter names to use because we are not binding to the route, we are binding to the path.  So I replaced masterId with Master and detail1Id with Id:

_onObjectMatched : function (oEvent) {
    var sObjectMasterId =  oEvent.getParameter("arguments").masterId;
    var sObjectDetailId =  oEvent.getParameter("arguments").detail1Id;
    this.getModel().metadataLoaded().then( function() {
      var sObjectPath = this.getModel().createKey("Detail2", {
        Master:  sObjectMasterId,
        Id: sObjectDetailId
      });
      this._bindView("/" + sObjectPath);
    }.bind(this));

Voila, it worked!

Thank you to everyone who responded and pointed me away from the routing and towards the binding.  I would suggest to anyone getting the "Malformed URI" error to review all bindings and navigation to verify that all parameters are spelt correctly.

Reviewing the Routing with Parameters tutorial was also a significant help.