问:
RabbitMQ to Azure IoT-Hub?
Currently we want to access our Azure IoT-Hub using RabbitMQ. We know that there are other options and already tested a few, but this project is to test if it is possible and suitable for us.

```<code>using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
</code>```

Our Code looks somewhat like this:

```<code>var factory = new ConnectionFactory();
factory.HostName = $"{IOT_HUB_NAME}.azure-devices.net";

// This fails with the message: 'None of the specified endpoints were reachable.'
using (var connection = factory.CreateConnection())
{
    // ...
}
</code>```

The endpoint the factory wants to connect to is:
amqp://<IoT-Hub Name>.azure-devices.net:5672

Our IT-Department already checked our filewall: it is not blocking this connection.

A quick check using telnet results in a connection error:

```<code>telnet <IoT-Hub Name>.azure-devices.net 5672
</code>```

However, the port 5671 (another port required by AMQP) is available.

I already tried setting the factory.Port = 5671 with no success. Another check using the Microsoft Azure IoT SDK reveiled that it is indeed possible to connect to the IoT-Hub.

This leads me to the assumption that I either miss an important configuration or it might not be possible to connect to Azure IoT-Hubs with RabbitMQ.

答: You certainly want to look into addressing specific endpoints such as the device to cloud messaging one and into the authentication mechanisms linked from this doc as well.</p>

Title: RabbitMQ to Azure IoT-Hub?

Body:
Currently we want to access our Azure IoT-Hub using RabbitMQ. We know that there are other options and already tested a few, but this project is to test if it is possible and suitable for us.

using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;

Our Code looks somewhat like this:

var factory = new ConnectionFactory();
factory.HostName = $"{IOT_HUB_NAME}.azure-devices.net";

// This fails with the message: 'None of the specified endpoints were reachable.'
using (var connection = factory.CreateConnection())
{
    // ...
}

The endpoint the factory wants to connect to is:
amqp://<IoT-Hub Name>.azure-devices.net:5672

Our IT-Department already checked our filewall: it is not blocking this connection.

A quick check using telnet results in a connection error:

telnet <IoT-Hub Name>.azure-devices.net 5672

However, the port 5671 (another port required by AMQP) is available.

I already tried setting the factory.Port = 5671 with no success. Another check using the Microsoft Azure IoT SDK reveiled that it is indeed possible to connect to the IoT-Hub.

This leads me to the assumption that I either miss an important configuration or it might not be possible to connect to Azure IoT-Hubs with RabbitMQ.


来源: stackexchange

问:
Targeting element attributes in IE9+
I need to target an h1 tag that has this attribute: style=color:#230870 and apply a text-shadow. It works great, except in IE of course. Sample code I've found seem to work but my code is using the '#' and in IE it gets rendered as: style="color: rgb(35, 8, 112); in the H1.

Here is my code on CodePen

#mydiv h1[style*=red] {
    text-shadow: 2px 2px 5px #443E55;
}
#mydiv h2[style*=70] {
    text-shadow: 2px 2px 1px #ffcc00;
}
#mydiv h2[style*=rgb] {
    text-shadow: 2px 2px 1px #ffcc00;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="mydiv">
 <h1>THIS IS A REGULAR H1 TAG</h1>
 <h1 style="color:red">THIS IS H1 WITH "red" AS IT'S ATTRIBUTE VALUE AND A DROP SHADOW</h1>
 <h1 style="color:#230870">THIS H1 WITH BLUE #230870 CSS ATTRIBUE VALUE WITH A DROP SHADOW</h1>
  <h1 style="color: rgb(35, 8, 112);">THIS H1 WITH BLUE #230870 BUT IE RENDERS THE ATTRIBUTE as: 'style="color: rgb(35, 8, 112)'</h1>

</div></code>```

What am I doing wrong?

答:
Your HTML are all h1, but your CSS target h2 (2nd and 3rd)

Also use h1[style*="70"] to target the 2nd one

h1[style*=red] {
    text-shadow: 2px 2px 5px #443E55;
}
h1[style*="70"] {
    text-shadow: 2px 2px 1px #ffcc00;
}
h1[style*=rgb] {
    text-shadow: 2px 2px 1px #ffcc00;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="mydiv">
 <h1>THIS IS A REGULAR H1 TAG</h1>
 <h1 style="color:red">THIS IS H1 WITH "red" AS IT'S ATTRIBUTE VALUE AND A DROP SHADOW</h1>
 <h1 style="color:#230870">THIS H1 WITH BLUE #230870 CSS ATTRIBUE VALUE WITH A DROP SHADOW</h1>
  <h1 style="color: rgb(35, 8, 112);">THIS H1 WITH BLUE #230870 BUT IE RENDERS THE ATTRIBUTE as: 'style="color: rgb(35, 8, 112)'</h1>

</div></code>```

ContentLicense: CC BY-SA 3.0

Title: Targeting element attributes in IE9+

Body:
I need to target an h1 tag that has this attribute: style=color:#230870 and apply a text-shadow. It works great, except in IE of course. Sample code I've found seem to work but my code is using the '#' and in IE it gets rendered as: style="color: rgb(35, 8, 112); in the H1.

Here is my code on CodePen

#mydiv h1[style*=red] {
    text-shadow: 2px 2px 5px #443E55;
}
#mydiv h2[style*=70] {
    text-shadow: 2px 2px 1px #ffcc00;
}
#mydiv h2[style*=rgb] {
    text-shadow: 2px 2px 1px #ffcc00;
}

THIS IS A REGULAR H1 TAG

THIS IS H1 WITH "red" AS IT'S ATTRIBUTE VALUE AND A DROP SHADOW

THIS H1 WITH BLUE #230870 CSS ATTRIBUE VALUE WITH A DROP SHADOW

THIS H1 WITH BLUE #230870 BUT IE RENDERS THE ATTRIBUTE as: 'style="color: rgb(35, 8, 112)'

What am I doing wrong?

Body:
Your HTML are all h1, but your CSS target h2 (2nd and 3rd)

Also use h1[style*="70"] to target the 2nd one

h1[style*=red] {
    text-shadow: 2px 2px 5px #443E55;
}
h1[style*="70"] {
    text-shadow: 2px 2px 1px #ffcc00;
}
h1[style*=rgb] {
    text-shadow: 2px 2px 1px #ffcc00;
}

<div id="mydiv">
 <h1>THIS IS A REGULAR H1 TAG</h1>
 <h1 style="color:red">THIS IS H1 WITH "red" AS IT'S ATTRIBUTE VALUE AND A DROP SHADOW</h1>
 <h1 style="color:#230870">THIS H1 WITH BLUE #230870 CSS ATTRIBUE VALUE WITH A DROP SHADOW</h1>
  <h1 style="color: rgb(35, 8, 112);">THIS H1 WITH BLUE #230870 BUT IE RENDERS THE ATTRIBUTE as: 'style="color: rgb(35, 8, 112)'</h1>

</div>


问:
NotSupportedException: The invoked member is not supported in a dynamic module in C# Unity 5
This is for my graduation project. The game idea briefly is to help students practice programming by providing some interesting missions that require a C# code solution something like codingame.com, when the user produces the correct output the result is visualised in a Unity scene.

I am using a C# compiler plugin to compile the user's code in the Unity 5 run-time. Everything is working fine (each scene alone start playing the scene in the editor and stopping it) but when I advance from scene to the next one this error rises when I build the user's C# code in the run-time (NotSupportedException: The invoked member is not supported in a dynamic module) (the error always rises in the second scene or the next scene).

The Error:

```<code>NotSupportedException: The invoked member is not supported in a dynamic module
</code>```

Error

The Line that produces the error:

```<code>this.assemblyReferences = domain.GetAssemblies().Select(a => a.Location).ToArray();
</code>```

assemblyRefrences is an array of strings: string[] assemblyReferences;

this line is in a script called ScriptBundleLoader in its constructor

答:
The error happens because you are trying to get the location of an in-memory assembly (the ones you have created on the fly) and those assemblies aren't located anywhere.

If you want to avoid this error try something like this:

```<code>this.assemblyReferences = domain.GetAssemblies().Select(a =>
{
    try{ return a.Location; }catch{ return null; }

}).Where(s => s != null).ToArray();
</code>```

EDIT:

As Jon Skeet pointed it can be used "IsDynamic" instead of trapping the exception:

```<code>this.assemblyReferences = domain.GetAssemblies()
    .Where(a => !a.IsDynamic)
    .Select(a => a.Location)
    .ToArray();
</code>```

Body:
This is for my graduation project. The game idea briefly is to help students practice programming by providing some interesting missions that require a C# code solution something like codingame.com, when the user produces the correct output the result is visualised in a Unity scene.

I am using a C# compiler plugin to compile the user's code in the Unity 5 run-time. Everything is working fine (each scene alone start playing the scene in the editor and stopping it) but when I advance from scene to the next one this error rises when I build the user's C# code in the run-time (NotSupportedException: The invoked member is not supported in a dynamic module) (the error always rises in the second scene or the next scene).

The Error:

NotSupportedException: The invoked member is not supported in a dynamic module

Error

The Line that produces the error:

this.assemblyReferences = domain.GetAssemblies().Select(a => a.Location).ToArray();

assemblyRefrences is an array of strings: string[] assemblyReferences;

this line is in a script called ScriptBundleLoader in its constructor

Body:
The error happens because you are trying to get the location of an in-memory assembly (the ones you have created on the fly) and those assemblies aren't located anywhere.

If you want to avoid this error try something like this:

this.assemblyReferences = domain.GetAssemblies().Select(a =>
{
    try{ return a.Location; }catch{ return null; }

}).Where(s => s != null).ToArray();

EDIT:

As Jon Skeet pointed it can be used "IsDynamic" instead of trapping the exception:

this.assemblyReferences = domain.GetAssemblies()
    .Where(a => !a.IsDynamic)
    .Select(a => a.Location)
    .ToArray();


问:
Opencart logout link was not shown in journal theme after logged in
I upgraded theme journal from 1.8.2 to 2.1 and the text “Welcome visitor…..” with login and register links disappeared. I can do my own in secondary menu, but then when I login, it will not change to name and logout link. What to do?</p>

答:
Go to Journal > Menus > Secondary Menu and in Link use Opencart Page & Login (Account) to display the name when logged in and Opencart Page & Register (Logout) to display the logout link.

Also have a look at the screenshot http://imgur.com/a/A2DG2


问:
String matching on a R column
My data frame has a column on which I am trying to run string matching and then update the string upon match.I have tried couple approaches but none seemed to have work. My frame looks like the below. For column "IntNames" row 2, I would like to substitute "clin2|clin3|clin4" with only clin2 and for row3 "clin6|clin7|clin8|clin9|clin10" with only clin6. The idea is to only retain the first element for such values. I appreciate all your help and input on this.  </p>

```<code>DataFrame:

   IntNames                   values1    values2
clin1                           100        10
clin2|clin3|clin4               200         4
clin6|clin7|clin8|clin9|clin10  240         5

This is what I have written:
newIntNames <- ifelse(myFrame$IntNames=="|",myFrame$IntNames[0],myFrame$IntNames)
</code>```

答:
Drop the ifelse statement and use substitution for this task:</p>

```<code>myFrame$IntNames <- sub('\\|.*', '', myFrame$IntNames)

#   IntNames values1 values2
# 1    clin1     100      10
# 2    clin2     200       4
# 3    clin6     240       5
</code>```

Title: String matching on a R column

Body:
My data frame has a column on which I am trying to run string matching and then update the string upon match.I have tried couple approaches but none seemed to have work. My frame looks like the below. For column "IntNames" row 2, I would like to substitute "clin2|clin3|clin4" with only clin2 and for row3 "clin6|clin7|clin8|clin9|clin10" with only clin6. The idea is to only retain the first element for such values. I appreciate all your help and input on this.

DataFrame:

   IntNames                   values1    values2
clin1                           100        10
clin2|clin3|clin4               200         4
clin6|clin7|clin8|clin9|clin10  240         5

This is what I have written:
newIntNames <- ifelse(myFrame$IntNames=="|",myFrame$IntNames[0],myFrame$IntNames)

Body:
Drop the ifelse statement and use substitution for this task:

myFrame$IntNames <- sub('\\|.*', '', myFrame$IntNames)

#   IntNames values1 values2
# 1    clin1     100      10
# 2    clin2     200       4
# 3    clin6     240       5


问:
Find words in text, php
How to resolve this problem:

Write a PHP program that finds the word in a text.
The suffix is separated from the text by a pipe.
For example: suffix|SOME_TEXT;

input: text|lorem ips llfaa Loremipsumtext.
output: Loremipsumtext

My code is this, but logic maybe is wrong:

```<code>$mystring = fgets(STDIN);
$find   = explode('|', $mystring);
$pos = strpos($find, $mystring);

if ($pos === false) {
    echo "The string '$find' was not found in the string '$mystring'.";
}
else {
    echo "The string '$find' was found in the string '$mystring',";
    echo " and exists at position $pos.";
}
</code>```

答:
explode() returns an array, so you need to use $find[0] for the suffix, and $find[1] for the text. So it should be:

```<code>$suffix = $find[0];
$text = $find[1];
$pos = strpos($text, $suffix);

if ($pos === false) {
    echo "The string '$suffix' was not found in '$text'.";
} else {
    echo "The string '$suffix' was found in '$text', ";
    echo " and exists at position $pos.";
}
</code>```

However, this returns the position of the suffix, not the word containing it. It also doesn't check that the suffix is at the end of the word, it will find it anywhere in the word. If you want to match words rather than just strings, a regular expression would be a better method.

```<code>$suffix = $find[0];
$regexp = '/\b[a-z]*' . $suffix . '\b/i';
$text = $find[1];
$found = preg_match($regexp, $text, $match);

if ($found) {
    echo echo "The suffix '$suffix' was found in '$text', ";
    echo " and exists in the word '$match[0]'.";
} else {
    echo "The suffix '$suffix' was not found in '$text'.";
}
</code>```

Title: Find words in text, php

Body:
How to resolve this problem:

Write a PHP program that finds the word in a text.
The suffix is separated from the text by a pipe.
For example: suffix|SOME_TEXT;

input: text|lorem ips llfaa Loremipsumtext.
output: Loremipsumtext

My code is this, but logic maybe is wrong:

$mystring = fgets(STDIN);
$find   = explode('|', $mystring);
$pos = strpos($find, $mystring);

if ($pos === false) {
    echo "The string '$find' was not found in the string '$mystring'.";
}
else {
    echo "The string '$find' was found in the string '$mystring',";
    echo " and exists at position $pos.";
}

Body:
explode() returns an array, so you need to use $find[0] for the suffix, and $find[1] for the text. So it should be:

$suffix = $find[0];
$text = $find[1];
$pos = strpos($text, $suffix);

if ($pos === false) {
    echo "The string '$suffix' was not found in '$text'.";
} else {
    echo "The string '$suffix' was found in '$text', ";
    echo " and exists at position $pos.";
}

However, this returns the position of the suffix, not the word containing it. It also doesn't check that the suffix is at the end of the word, it will find it anywhere in the word. If you want to match words rather than just strings, a regular expression would be a better method.

$suffix = $find[0];
$regexp = '/\b[a-z]*' . $suffix . '\b/i';
$text = $find[1];
$found = preg_match($regexp, $text, $match);

if ($found) {
    echo echo "The suffix '$suffix' was found in '$text', ";
    echo " and exists in the word '$match[0]'.";
} else {
    echo "The suffix '$suffix' was not found in '$text'.";
}


问:
Batch command - read csv file and create filename with multi identified content
I have multiple files each with the same file name

Example:

Test.csv

Test (1).csv

Test (2).csv

Test (3).csv

But the content within each file is different.

On the 1st and 2nd line of the file within token spots 2 and 4 I am able to identify the file.  I would like to rename the files with these two data points.

Example

Within Test.csv file, line record 1 and 2

H,Projected,Cost

1,Food,Apple,Fruit,55

Within Test (1).csv line record 1 and 2

H,Actual,Cost

1,Food,Apple,Fruit,45

Within Test (2).csv line record 1 and 2

H,Projected,Cost

1,Car,Honda,Auto,5500

Within Test (3).csv line record 1 and 2

H,Actual,Cost

1,Car,Honda,Auto,6500

I would like to rename the following files as

Test.csv      = Fruit_Projected.csv

Test (1).csv  = Fruit_Actual.csv

Test (2).csv  = Auto_Projected.csv

Test (3).csv  = Auto_Acutal.csv

Right now I can identify and rename the files with the data on line 2 and the 4th token.  I want to be able to concatenate the two the data on line 2 (token 4) and line 1 (token 2) .  Below is my current code.

```<code>@echo off

for %%i in (*.csv) do (
  for /f "skip=1 token=4 delims=," %%j in ('findstr /B /I "^" "%%i"') do (
    ren "%%i" "%%j.temp_txt"
  )
)

ren *.temp_txt *.csv
</code>```

答:
The following (untested) batch iterates the csv's and counts the lines of the contents, stores line1 token2 in the var L1T2 amd line2 token4 to L2T4.

The resulting rename command is stored in a (pseudo) array and executed at the end.

To really execute the renames remove the echo in the last line.

```<code>@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
Set Cnt=0
for %%i in (*.csv) do (
  Set /A "Line=0,Cnt+=1"
  for /f "tokens=2,4 delims=," %%A in ('Type "%%i"') do (
    Set /A Line+=1
    If !Line! equ 1 Set "L1T2=%%A"
    If !Line! equ 2 Set "L2T4=%%B"
  )
  Set Ren[!Cnt!]=ren "%%i" "!L2T4!_!L1T2!.csv"
)
For /L %%C in (1,1,%Cnt%) Do Echo !Ren[%%C]!
</code>```

Body:
I have multiple files each with the same file name

Example:

Test.csv

Test (1).csv

Test (2).csv

Test (3).csv

But the content within each file is different.

On the 1st and 2nd line of the file within token spots 2 and 4 I am able to identify the file.  I would like to rename the files with these two data points.

Example

Within Test.csv file, line record 1 and 2

H,Projected,Cost

1,Food,Apple,Fruit,55

Within Test (1).csv line record 1 and 2

H,Actual,Cost

1,Food,Apple,Fruit,45

Within Test (2).csv line record 1 and 2

H,Projected,Cost

1,Car,Honda,Auto,5500

Within Test (3).csv line record 1 and 2

H,Actual,Cost

1,Car,Honda,Auto,6500

I would like to rename the following files as

Test.csv      = Fruit_Projected.csv

Test (1).csv  = Fruit_Actual.csv

Test (2).csv  = Auto_Projected.csv

Test (3).csv  = Auto_Acutal.csv

Right now I can identify and rename the files with the data on line 2 and the 4th token.  I want to be able to concatenate the two the data on line 2 (token 4) and line 1 (token 2) .  Below is my current code.

@echo off

for %%i in (*.csv) do (
  for /f "skip=1 token=4 delims=," %%j in ('findstr /B /I "^" "%%i"') do (
    ren "%%i" "%%j.temp_txt"
  )
)

ren *.temp_txt *.csv

Body:
The following (untested) batch iterates the csv's and counts the lines of the contents, stores line1 token2 in the var L1T2 amd line2 token4 to L2T4.

The resulting rename command is stored in a (pseudo) array and executed at the end.

To really execute the renames remove the echo in the last line.

@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
Set Cnt=0
for %%i in (*.csv) do (
  Set /A "Line=0,Cnt+=1"
  for /f "tokens=2,4 delims=," %%A in ('Type "%%i"') do (
    Set /A Line+=1
    If !Line! equ 1 Set "L1T2=%%A"
    If !Line! equ 2 Set "L2T4=%%B"
  )
  Set Ren[!Cnt!]=ren "%%i" "!L2T4!_!L1T2!.csv"
)
For /L %%C in (1,1,%Cnt%) Do Echo !Ren[%%C]!


问:
MySQL wait_timeout Variable - GLOBAL vs SESSION
```<code>SHOW VARIABLES LIKE "%wait%"

Result: 28800

SET @@GLOBAL.wait_timeout=300

SHOW GLOBAL VARIABLES LIKE "%wait%"

Result: 300

SHOW SESSION VARIABLES LIKE "%wait%"

Result:28800
</code>```

I am confused by the results. Why does the last query give Result:28800 ?

答:
Your session status are set once you start a session, and by default, take the current GLOBAL value.

If you disconnected after you did SET @@GLOBAL.wait_timeout=300, then subsequently reconnected, you'd see

```<code>SHOW SESSION VARIABLES LIKE "%wait%";

Result: 300
</code>```

Similarly, at any time, if you did

```<code>mysql> SET session wait_timeout=300;
</code>```

You'd get

```<code>mysql> SHOW SESSION VARIABLES LIKE 'wait_timeout';

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout  | 300   |
+---------------+-------+
</code>```

Body:
SHOW VARIABLES LIKE "%wait%"

Result: 28800

SET @@GLOBAL.wait_timeout=300

SHOW GLOBAL VARIABLES LIKE "%wait%"

Result: 300

SHOW SESSION VARIABLES LIKE "%wait%"

Result:28800

I am confused by the results. Why does the last query give Result:28800 ?

Body:
Your session status are set once you start a session, and by default, take the current GLOBAL value.

If you disconnected after you did SET @@GLOBAL.wait_timeout=300, then subsequently reconnected, you'd see

SHOW SESSION VARIABLES LIKE "%wait%";

Result: 300

Similarly, at any time, if you did

mysql> SET session wait_timeout=300;

You'd get

mysql> SHOW SESSION VARIABLES LIKE 'wait_timeout';

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout  | 300   |
+---------------+-------+

ContentLicense: CC BY-SA 2.5


问:
How do I change a global variables contents within a function
I have created the following sample program to demonstrate what I'm trying to do:

```<code>name = "d"

def namechange (name):

    global name
    name = "Henry"
    return name

print name
</code>```

The errors that is produced:

```<code>SyntaxError: name 'name' is local and global
</code>```

I understand that the name variable is local and global, but I am new to this and do not know how to resolve this issue. Please help

答:
```<code>def namechange (name):
</code>```

This introduces a local variable name.

```<code>global name
</code>```

Yet this also introduces the global variable name in the same scope.

Hence the syntax error that name is both local and global. In order to fix this, you have to either remove the local variable, or the global variable. In your case, you could do both.

You could either remove the local variable and just make the function modify the global variable, like this:

```<code>def namechange ():
    global name
    name = "Henry"
</code>```

In that case, you don’t actually need to return anything, since this already modifies the global variable.

Or you could remove the global variable, and make this function just return the new value:

```<code>def namechange (name):
    name = "Henry"
    return name
</code>```

In that case, it would be the caller’s responsibility to update the variable from the outer scope:

```<code>name = "d"
new_name = namechange(name)
print(new_name) # Henry
</code>```

Body:
I have created the following sample program to demonstrate what I'm trying to do:

name = "d"

def namechange (name):

    global name
    name = "Henry"
    return name

print name

The errors that is produced:

SyntaxError: name 'name' is local and global

I understand that the name variable is local and global, but I am new to this and do not know how to resolve this issue. Please help

Body:
def namechange (name):

This introduces a local variable name.

global name

Yet this also introduces the global variable name in the same scope.

Hence the syntax error that name is both local and global. In order to fix this, you have to either remove the local variable, or the global variable. In your case, you could do both.

You could either remove the local variable and just make the function modify the global variable, like this:

def namechange ():
    global name
    name = "Henry"

In that case, you don’t actually need to return anything, since this already modifies the global variable.

Or you could remove the global variable, and make this function just return the new value:

def namechange (name):
    name = "Henry"
    return name

In that case, it would be the caller’s responsibility to update the variable from the outer scope:

name = "d"
new_name = namechange(name)
print(new_name) # Henry


问:
Reading and writing the same file simultaneosly with c++
I'm trying to read and write a file as I loop through its lines. At each line, I will do an evaluation to determine if I want to write it into the file or skip it and move onto the next line. This is a basically a skeleton of what I have so far.

```<code>void readFile(char* fileName)
{
    char line[1024];
    fstream file("test.file", ios::in | ios::out);

    if(file.is_open())
    {
        while(file.getline(line,MAX_BUFFER))
        {

            //evaluation

            file.seekg(file.tellp());
            file << line;
            file.seekp(file.tellg());
        }
    }
}
</code>```

As I'm reading in the lines, I seem to be having issues with the starting index of the string copied into the line variable. For example, I may be expecting the string in the line variable to be "000/123/FH/" but it actually goes in as "123/FH/". I suspect that I have an issue with file.seekg(file.tellp()) and file.seekp(file.tellg()) but I am not sure what it is.

答:
You are reading and writing to the same file you might end up of having duplicate lines in the file.

You could find this very useful. Imagine your 1st time of reaching the while loop and starting from the beginning of the file you do file.getline(line, MAX_BUFFER). Now the get pointer (for reading) moves MAX_BUFFER places from the beginning of the file (your starting point).

After you've determine to write back to the file seekp() helps to specify with respect to a reference point the location you want to write to, syntax: file.seekp(num_bytes,"ref"); where ref will be ios::beg(beginning), ios::end, ios::cur  (current position in file).

As in your code after reading, find a way to use MAX_BUFFER to refer to a location with respect to a reference.

```<code> while(file.good())
        {
            file.getline(line,MAX_BUFFER);
            ...
            if(//for some reasone you want to write back)
            {
                 // set put-pointer to location for writing
                file.seekp(num_bytes, "ref");
                file << line;

             }
            //set get-pointer to desired location for the next read

            file.seekg(num_bytes, "ref");

        }
</code>```

Body:
I'm trying to read and write a file as I loop through its lines. At each line, I will do an evaluation to determine if I want to write it into the file or skip it and move onto the next line. This is a basically a skeleton of what I have so far.

void readFile(char* fileName)
{
    char line[1024];
    fstream file("test.file", ios::in | ios::out);

    if(file.is_open())
    {
        while(file.getline(line,MAX_BUFFER))
        {

            //evaluation

            file.seekg(file.tellp());
            file << line;
            file.seekp(file.tellg());
        }
    }
}

As I'm reading in the lines, I seem to be having issues with the starting index of the string copied into the line variable. For example, I may be expecting the string in the line variable to be "000/123/FH/" but it actually goes in as "123/FH/". I suspect that I have an issue with file.seekg(file.tellp()) and file.seekp(file.tellg()) but I am not sure what it is.

Body:
You are reading and writing to the same file you might end up of having duplicate lines in the file.

You could find this very useful. Imagine your 1st time of reaching the while loop and starting from the beginning of the file you do file.getline(line, MAX_BUFFER). Now the get pointer (for reading) moves MAX_BUFFER places from the beginning of the file (your starting point).

After you've determine to write back to the file seekp() helps to specify with respect to a reference point the location you want to write to, syntax: file.seekp(num_bytes,"ref"); where ref will be ios::beg(beginning), ios::end, ios::cur  (current position in file).

As in your code after reading, find a way to use MAX_BUFFER to refer to a location with respect to a reference.

 while(file.good())
        {
            file.getline(line,MAX_BUFFER);
            ...
            if(//for some reasone you want to write back)
            {
                 // set put-pointer to location for writing
                file.seekp(num_bytes, "ref");
                file << line;

             }
            //set get-pointer to desired location for the next read

            file.seekg(num_bytes, "ref");

        }

ContentLicense: CC BY-SA 4.0


问:
Trying to create a setter method for my wrapper class matrix
I have defined a own class, which implements a Wrapper class matrix for a 2-dimnesional Array. With a setter-method 'set(int n, int m, double d)' I want to set/change the value at the position n(row),m(colum) into d.

```<code>public class Matrix {

double matrix [][];
int matrixSize;

public Matrix(int matrixSize){
    this.matrix = new double [matrixSize][matrixSize];
}

public void setMatrixSize(int size){
    matrixSize = size;
}

public int getMatrixSize(){
    return matrixSize;
}

public void set(int n, int m, double d){
    double matrix [n][m] = d;
}}
</code>```

I know, that my last method does not work, but I don't really know how to set the value double d at the array matrix at the position n, m.

If some of you may can help me I would be very grateful.

答:
Fix the set method like this:

```<code>public void set(int n, int m, double d){
    this.matrix[n][m] = d;
}
</code>```

Body:
I have defined a own class, which implements a Wrapper class matrix for a 2-dimnesional Array. With a setter-method 'set(int n, int m, double d)' I want to set/change the value at the position n(row),m(colum) into d.

public class Matrix {

double matrix [][];
int matrixSize;

public Matrix(int matrixSize){
    this.matrix = new double [matrixSize][matrixSize];
}

public void setMatrixSize(int size){
    matrixSize = size;
}

public int getMatrixSize(){
    return matrixSize;
}

public void set(int n, int m, double d){
    double matrix [n][m] = d;
}}

I know, that my last method does not work, but I don't really know how to set the value double d at the array matrix at the position n, m.

If some of you may can help me I would be very grateful.

Body:
Fix the set method like this:

public void set(int n, int m, double d){
    this.matrix[n][m] = d;
}


问:
Equality check involving constexpr instance
I added the following member in my class:

```<code>constexpr static folly::Unit nullUnit {};
</code>```

Here is the link to folly::Unit :

https://github.com/facebook/folly/blob/master/folly/Unit.h

Depending on a flag, I would return either folly::unit or the nullUnit:

```<code>                  if (mutate_resp->processed()) {
                      LOG(INFO) << "check returns folly::unit";
                      return folly::unit;
                  }
                  LOG(INFO) << "check returns nullUnit";
                  return nullUnit;
</code>```

I perform equality check like this:

```<code>if (ret == folly::unit) return true;
return false;
</code>```

However, it seems the comparison is always true even though I saw the following in output:

```<code>I0608 22:43:37.729920 18225 raw-async-table.cc:132] check returns folly::unit
I0608 22:43:37.731446 18225 raw-async-table.cc:135] check returns nullUnit
</code>```

Any hint is appreciated

答:
Folly has this:

```<code>constexpr Unit unit {};
</code>```

And you have this:

```<code>constexpr static folly::Unit nullUnit {};
</code>```

It makes sense that these are the same.  Moreover, Folly has this:

```<code>bool operator==(const Unit& /*other*/) const { return true; }
</code>```

So clearly any Unit is going to compare equal to any other.

Body:
I added the following member in my class:

constexpr static folly::Unit nullUnit {};

Here is the link to folly::Unit :

https://github.com/facebook/folly/blob/master/folly/Unit.h

Depending on a flag, I would return either folly::unit or the nullUnit:

                  if (mutate_resp->processed()) {
                      LOG(INFO) << "check returns folly::unit";
                      return folly::unit;
                  }
                  LOG(INFO) << "check returns nullUnit";
                  return nullUnit;

I perform equality check like this:

if (ret == folly::unit) return true;
return false;

However, it seems the comparison is always true even though I saw the following in output:

I0608 22:43:37.729920 18225 raw-async-table.cc:132] check returns folly::unit
I0608 22:43:37.731446 18225 raw-async-table.cc:135] check returns nullUnit

Any hint is appreciated

Body:
Folly has this:

constexpr Unit unit {};

And you have this:

constexpr static folly::Unit nullUnit {};

It makes sense that these are the same.  Moreover, Folly has this:

bool operator==(const Unit& /*other*/) const { return true; }

So clearly any Unit is going to compare equal to any other.


问:
How to use stringByAddingPercentEncodingWithAllowedCharacters() for a URL in Swift 2.0
I was using this, in Swift 1.2

```<code>let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
</code>```

This now gives me a warning asking me to use

```<code>stringByAddingPercentEncodingWithAllowedCharacters
</code>```

I need to use a NSCharacterSet as an argument, but there are so many and I cannot determine what one will give me the same outcome as the previously used method.

An example URL I want to use will be like this

```<code>http://www.mapquestapi.com/geocoding/v1/batch?key=YOUR_KEY_HERE&callback=renderBatch&location=Pottsville,PA&location=Red Lion&location=19036&location=1090 N Charlotte St, Lancaster, PA
</code>```

The URL Character Set for encoding seems to contain sets the trim my
URL. i.e,

The path component of a URL is the component immediately following the
  host component (if present). It ends wherever the query or fragment
  component begins. For example, in the URL
  http://www.example.com/index.php?key1=value1, the path component is
  /index.php.

However I don't want to trim any aspect of it.
When I used my String, for example myurlstring it would fail.

But when used the following, then there were no issues. It encoded the string with some magic and I could get my URL data.

```<code>let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
</code>```

As it

Returns a representation of the String using a given encoding to
  determine the percent escapes necessary to convert the String into a
  legal URL string

Thanks

答:
In Swift 3.1, I am using something like the following:

```<code>let query = "param1=value1&param2=" + valueToEncode.addingPercentEncoding(withAllowedCharacters: .alphanumeric)
</code>```

It's safer than .urlQueryAllowed and the others, because it this will encode every characters other than A-Z, a-z and 0-9. This works better when the value you are encoding may use special characters like ?, &, =, + and spaces.

Body:
I was using this, in Swift 1.2

let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

This now gives me a warning asking me to use

stringByAddingPercentEncodingWithAllowedCharacters

I need to use a NSCharacterSet as an argument, but there are so many and I cannot determine what one will give me the same outcome as the previously used method.

An example URL I want to use will be like this

http://www.mapquestapi.com/geocoding/v1/batch?key=YOUR_KEY_HERE&callback=renderBatch&location=Pottsville,PA&location=Red Lion&location=19036&location=1090 N Charlotte St, Lancaster, PA

The URL Character Set for encoding seems to contain sets the trim my
URL. i.e,

The path component of a URL is the component immediately following the
  host component (if present). It ends wherever the query or fragment
  component begins. For example, in the URL
  http://www.example.com/index.php?key1=value1, the path component is
  /index.php.

However I don't want to trim any aspect of it.
When I used my String, for example myurlstring it would fail.

But when used the following, then there were no issues. It encoded the string with some magic and I could get my URL data.

let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

As it

Returns a representation of the String using a given encoding to
  determine the percent escapes necessary to convert the String into a
  legal URL string

Thanks

Body:
In Swift 3.1, I am using something like the following:

let query = "param1=value1&param2=" + valueToEncode.addingPercentEncoding(withAllowedCharacters: .alphanumeric)

It's safer than .urlQueryAllowed and the others, because it this will encode every characters other than A-Z, a-z and 0-9. This works better when the value you are encoding may use special characters like ?, &, =, + and spaces.


问:
Class JavaLaunchHelper is implemented in two places
Today I upgraded my Intellij Idea on macOS Sierra, and now, when I run apps in console I have this error:

objc[3648]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/bin/java (0x10d19c4c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x10ea194e0). One of the two will be used. Which one is undefined.

答:
I am using Intellij Idea 2017 and I got into the same problem. What solved the problem for me was to simply

close the project in intelliJ

File -> New -> project from existing resources

use Import from external model (if any)

open the project again.


问:
Sorting API values in a table using php
I'm trying to build something like https://coinranking.com/. I plan on doing this by sorting the results from the API at http://www.coincap.io/front using the position24 value as sorting parameter.
So far, I managed to pull an ordered list with the prices, but I'd like to display the values from other objects (volume, mktcap, etc) as well in a table. Would I have to repeat this function for every object?

```<code><php?
function compare($a, $b) {
    return intval($a->position24) - intval($b->position24);
}

$json = file_get_contents('http://www.coincap.io/front');
$data = json_decode($json);
usort($data, 'compare');
foreach ($data as $item) {
    echo $item->price . "\n"<;
}
?>
</code>```

答:
usort expecting array as parameter your $data is object maybe you should use json_decode($json,true); and

```<code>function compare($a, $b) {
    return intval($a['position24']) - intval($b['position24']);
}
</code>```

Title: Sorting API values in a table using php

Body:
I'm trying to build something like https://coinranking.com/. I plan on doing this by sorting the results from the API at http://www.coincap.io/front using the position24 value as sorting parameter.
So far, I managed to pull an ordered list with the prices, but I'd like to display the values from other objects (volume, mktcap, etc) as well in a table. Would I have to repeat this function for every object?

<php?
function compare($a, $b) {
    return intval($a->position24) - intval($b->position24);
}

$json = file_get_contents('http://www.coincap.io/front');
$data = json_decode($json);
usort($data, 'compare');
foreach ($data as $item) {
    echo $item->price . "\n"<;
}
?>

Body:
usort expecting array as parameter your $data is object maybe you should use json_decode($json,true); and

function compare($a, $b) {
    return intval($a['position24']) - intval($b['position24']);
}


问:
Reusing a ValueEventListener firebase
hi guys i have a ValueEventlistener class that listens for a value of 1 when the value is reached it changes the look of the buttons in my main activity. All works fine. But ive been informed that the way im using the listener is wrong. because i recall the same instance over and over

```<code>public class getRewards {
Firebase mListref;
 Button mstreaming,mcustom,mlauncher,mmovies;
Context mcontext;

public getRewards(Firebase ListRef, Context context){
    this.mListref = ListRef;
    this.mcontext = context;
}
public void getButtonRewards(Button a,Button b,Button c,Button d){
  this.mstreaming = a;
    this.mcustom = b;
    this.mlauncher = c;
    this.mmovies = d;
</code>```

//HERE IS WHERE I REUSE THE LISTENER IS THIS THE RIGHT WAY TO USE IT??

```<code>     RewardValueListener reward1 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward1);
    reward1.getButton(mstreaming,mcontext);
    RewardValueListener reward2 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward2);
    reward2.getButton(mcustom,mcontext);
    RewardValueListener reward3 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward3);
    reward3.getButton(mlauncher,mcontext);
    RewardValueListener reward4 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward4);
    reward4.getButton(mmovies,mcontext);
}
</code>```

}
what is the best way to reuse the listener to change all my buttons instead of just one or doing it the above way?

my Reward listener class

```<code>public class RewardValueListener  implements ValueEventListener {

FirebaseAuth mAuth;
String userid;
int i;
View view;
String dls;
Button mButton;
Context c;

public RewardValueListener() {

}

@Override
public void onDataChange(DataSnapshot dataSnapshot) {

    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    userid = user.getUid();
    dls = dataSnapshot.child(userid).child("counter").getValue(String.class);

    i = Integer.parseInt(dls);
    if (i == 1) {

        mButton.setBackground(c.getResources().getDrawable(R.drawable.buttonbkground2));

    }
}

@Override
public void onCancelled(FirebaseError firebaseError) {

}

public void getButton(Button button,Context context) {
    mButton = button;
    c=context;

}
</code>```

and finally how i call it on my main activity

```<code>   getRewards checkRewardStatus = new getRewards(mListRef,mContext);
    checkRewardStatus.getButtonRewards(mStreaming,mcustom,mUtil,mplayers);
</code>```

答:
If I understand correctly, you just want to encapsulate four buttons into a single object.

That would best be done using the View that holds them all.

```<code>public class Rewards {
    private Firebase mListref;
    private final Context mcontext;
    Button mstreaming,mcustom,mlauncher,mmovies;

    public Rewards(Context context, Firebase ref, View rootView){
        this.mListref = ref;
        this.mcontext = context;

        if (rootView != null) {
             this.mstreaming = (Button) rootView.findViewById(R.id.streaming);
            this.mcustom = (Button) rootView.findViewById(R.id.custom);
            this.mlauncher = (Button) rootView.findViewById(R.id.launcher);
            this.mmovies = (Button) rootView.findViewById(R.id.movies);
        }
    }
}
</code>```

How you create this depends on an Activity / Fragment situation, but generally, new Rewards(getContext(), firebaseRef, getView()). (Those methods won't all resolve, but I don't know how you are using this.)

Then, same as before, add to the constructor.

```<code>public class RewardValueListener implements ValueEventListener {

    private FirebaseAuth mAuth;
    private Rewards mRewards;

    public RewardValueListener(Rewards rewards) {
        this.mRewards = rewards;
    }

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        mAuth = FirebaseAuth.getInstance();
        String userId = mAuth.getCurrentUser().getUid();
        Integer counter = dataSnapshot.child(userid).child("counter").getValue(Integer.class);

        if (counter == 1) {
            // mRewards.mstreaming.setBackground( ... );
        } else if (counter == 2) {
            // mRewards.mcustom.setBackground( ... );
        }
    }
</code>```

Not sure what conditions your buttons are expected to be changing.

And to wrap-up.

```<code>View rootView = getView(); // TODO: Implement this somehow
Rewards rewards = new Rewards(mContext, mListref, rootView);
RewardValueListener listener = new RewardValueListener(rewards);
mListref.child("RewardsSystem").addValueEventListener(listener);
</code>```

In an Activity, you don't really need a method, and can instead use this

```<code>View rootView = findViewById(android.R.id.content);
</code>```

Title: Reusing a ValueEventListener firebase

Body:
hi guys i have a ValueEventlistener class that listens for a value of 1 when the value is reached it changes the look of the buttons in my main activity. All works fine. But ive been informed that the way im using the listener is wrong. because i recall the same instance over and over

public class getRewards {
Firebase mListref;
 Button mstreaming,mcustom,mlauncher,mmovies;
Context mcontext;

public getRewards(Firebase ListRef, Context context){
    this.mListref = ListRef;
    this.mcontext = context;
}
public void getButtonRewards(Button a,Button b,Button c,Button d){
  this.mstreaming = a;
    this.mcustom = b;
    this.mlauncher = c;
    this.mmovies = d;

//HERE IS WHERE I REUSE THE LISTENER IS THIS THE RIGHT WAY TO USE IT??

     RewardValueListener reward1 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward1);
    reward1.getButton(mstreaming,mcontext);
    RewardValueListener reward2 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward2);
    reward2.getButton(mcustom,mcontext);
    RewardValueListener reward3 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward3);
    reward3.getButton(mlauncher,mcontext);
    RewardValueListener reward4 = new RewardValueListener();
    mListref.child("RewardsSystem").addValueEventListener(reward4);
    reward4.getButton(mmovies,mcontext);
}

}
what is the best way to reuse the listener to change all my buttons instead of just one or doing it the above way?

my Reward listener class

public class RewardValueListener  implements ValueEventListener {

FirebaseAuth mAuth;
String userid;
int i;
View view;
String dls;
Button mButton;
Context c;

public RewardValueListener() {

}

@Override
public void onDataChange(DataSnapshot dataSnapshot) {

    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    userid = user.getUid();
    dls = dataSnapshot.child(userid).child("counter").getValue(String.class);

    i = Integer.parseInt(dls);
    if (i == 1) {

        mButton.setBackground(c.getResources().getDrawable(R.drawable.buttonbkground2));

    }
}

@Override
public void onCancelled(FirebaseError firebaseError) {

}

public void getButton(Button button,Context context) {
    mButton = button;
    c=context;

}

and finally how i call it on my main activity

   getRewards checkRewardStatus = new getRewards(mListRef,mContext);
    checkRewardStatus.getButtonRewards(mStreaming,mcustom,mUtil,mplayers);

Body:
If I understand correctly, you just want to encapsulate four buttons into a single object.

That would best be done using the View that holds them all.

public class Rewards {
    private Firebase mListref;
    private final Context mcontext;
    Button mstreaming,mcustom,mlauncher,mmovies;

    public Rewards(Context context, Firebase ref, View rootView){
        this.mListref = ref;
        this.mcontext = context;

        if (rootView != null) {
             this.mstreaming = (Button) rootView.findViewById(R.id.streaming);
            this.mcustom = (Button) rootView.findViewById(R.id.custom);
            this.mlauncher = (Button) rootView.findViewById(R.id.launcher);
            this.mmovies = (Button) rootView.findViewById(R.id.movies);
        }
    }
}

How you create this depends on an Activity / Fragment situation, but generally, new Rewards(getContext(), firebaseRef, getView()). (Those methods won't all resolve, but I don't know how you are using this.)

Then, same as before, add to the constructor.

public class RewardValueListener implements ValueEventListener {

    private FirebaseAuth mAuth;
    private Rewards mRewards;

    public RewardValueListener(Rewards rewards) {
        this.mRewards = rewards;
    }

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        mAuth = FirebaseAuth.getInstance();
        String userId = mAuth.getCurrentUser().getUid();
        Integer counter = dataSnapshot.child(userid).child("counter").getValue(Integer.class);

        if (counter == 1) {
            // mRewards.mstreaming.setBackground( ... );
        } else if (counter == 2) {
            // mRewards.mcustom.setBackground( ... );
        }
    }

Not sure what conditions your buttons are expected to be changing.

And to wrap-up.

View rootView = getView(); // TODO: Implement this somehow
Rewards rewards = new Rewards(mContext, mListref, rootView);
RewardValueListener listener = new RewardValueListener(rewards);
mListref.child("RewardsSystem").addValueEventListener(listener);

In an Activity, you don't really need a method, and can instead use this

View rootView = findViewById(android.R.id.content);


问:
How to change Keras backend (where's the json file)?
I have installed Keras, and wanted to switch the backend to Theano. I checked out this post, but still have no idea where to put the created json file. Also, below is the error I got when running import keras in Python Shell:

Using TensorFlow backend.

Traceback (most recent call last):   File "", line 1, in

      import keras   File "C:\Python27\lib\site-packages\keras__init__.py", line 2, in
      from . import backend   File "C:\Python27\lib\site-packages\keras\backend__init__.py", line 64, in

      from .tensorflow_backend import *   File "C:\Python27\lib\site-packages\keras\backend\tensorflow_backend.py",
  line 1, in
      import tensorflow as tf ImportError: No module named tensorflow

When running python -c "import keras; print(keras.__version__)" from Windows command line, I got:

Using TensorFlow backend. Traceback (most recent call last):   File
  "", line 1, in    File
  "C:\Python27\lib\site-packages\keras__init__.py", line 2, in
      from . import backend   File "C:\Python27\lib\site-packages\keras\backend__init__.py", line 64, in

      from .tensorflow_backend import *   File "C:\Python27\lib\site-packages\keras\backend\tensorflow_backend.py",
  line 1, in
      import tensorflow as tf ImportError: No module named tensorflow

Can someone please help? Thanks!

答:
In case you want to change the config, the json is available here: ~/.keras/keras.json

To do this dynamically in python 2.7 you can run:

```<code>from keras import backend as K
import os

def set_keras_backend(backend):

    if K.backend() != backend:
        os.environ['KERAS_BACKEND'] = backend
        reload(K)
        assert K.backend() == backend

set_keras_backend("theano")
</code>```

Body:
In case you want to change the config, the json is available here: ~/.keras/keras.json

To do this dynamically in python 2.7 you can run:

from keras import backend as K
import os

def set_keras_backend(backend):

    if K.backend() != backend:
        os.environ['KERAS_BACKEND'] = backend
        reload(K)
        assert K.backend() == backend

set_keras_backend("theano")


问:
How to read a column of 'dictionary' into pandas
I have a csv file with a column whose type is a dictionary (column 'b' in the example below). But b in df is a string type even though I define it as the dictionary type. I didn't find the solution to this question. Any suggestions?

```<code>a = pd.DataFrame({'a': [1,2,3], 'b':[{'a':3, 'haha':4}, {'c':3}, {'d':4}]})
a.to_csv('tmp.csv', index=None)
df = pd.read_csv('tmp.csv', dtype={'b':dict})
</code>```

答:
There is no dictionary type in pandas. So you should specify object in case you want normal Python objects:

```<code>df = pd.read_csv('tmp.csv', dtype={'b':object})
</code>```

This will contain strings because pandas doesn't know what dictionaries are. In case you want dictionaries again you could try to "eval" them with ast.literal_eval (safe string evaluation):

```<code>df['b'] = df['b'].apply(ast.literal_eval)

print(df['b'][0]['a'])  # 3
</code>```

If you're really confident that you never ever run this on untrusted csvs you could also use eval. But before you consider that I would recommend trying to use a DataFrame only with "native" pandas or NumPy types (or maybe a DataFrame in DataFrame approach). Best to avoid object dtypes as much as possible.

Body:
I have a csv file with a column whose type is a dictionary (column 'b' in the example below). But b in df is a string type even though I define it as the dictionary type. I didn't find the solution to this question. Any suggestions?

a = pd.DataFrame({'a': [1,2,3], 'b':[{'a':3, 'haha':4}, {'c':3}, {'d':4}]})
a.to_csv('tmp.csv', index=None)
df = pd.read_csv('tmp.csv', dtype={'b':dict})

Body:
There is no dictionary type in pandas. So you should specify object in case you want normal Python objects:

df = pd.read_csv('tmp.csv', dtype={'b':object})

This will contain strings because pandas doesn't know what dictionaries are. In case you want dictionaries again you could try to "eval" them with ast.literal_eval (safe string evaluation):

df['b'] = df['b'].apply(ast.literal_eval)

print(df['b'][0]['a'])  # 3

If you're really confident that you never ever run this on untrusted csvs you could also use eval. But before you consider that I would recommend trying to use a DataFrame only with "native" pandas or NumPy types (or maybe a DataFrame in DataFrame approach). Best to avoid object dtypes as much as possible.


问:
Python-3.6 How can I print all outcomes at the end instead of after each input?
Sorry guys but I'm confused about how to solve this...

Program takes a series of separate and random int inputs, compares each new int to the previous (higher, lower, equal): e.g, first number = 10, next number = 5, output = lower. This loops until user enters [0]

But I now want to change it so that all the outputs are at the end instead of 1 after each pair. Let's say overall input is 2, 3, 6, 6, 5, 1 [0]: print statement should be only after [0] which would say, e.g., higher higher equal lower lower (all in one statement).

Things I've tried... print(a) but of course (a) gets reassigned to each new number..... tried (rookie mistake): if b < a: b = "higher" but '<' not supported between instances of 'str' and 'int'...... tried a list but error: expected list but received int...... another error (can't remember what I tried): int object is not iterable. (Also, I know I should probably have some elifs instead of all these ifs but that's not causing problems...)

My code:

```<code>z = 0
done = False
a = int(input("Enter first number: "))
while not done:
    b = int(input("Enter next number [0 = done]: "))
    if b != z: #while program not done
        if b > a:
            print("higher")
        if b == a:
            print("equal")
        if b < a:
            print("lower")
        a = b #second number becomes first and repeat
    else:
        done = True
</code>```

Any help is greatly appreciated. Thank you.

答:
Track the responses, print at the end.</p>

```<code>z = 0
done = False
a = int(input("Enter first number: "))
track_comparisons = []
while not done:
    b = int(input("Enter next number [0 = done]: "))
    if b != z: #while program not done
        if b > a:
            track_comparisons.append('higher')
        elif b == a:                       #change to if, elif, else
            track_comparisons.append('equal')
        else:
            track_comparisons.append("lower")
        a = b #second number becomes first and repeat
    else:
        for response in track_comparisons:
            print(response, end=' ')
        done = True
</code>```

Body:
Sorry guys but I'm confused about how to solve this...

Program takes a series of separate and random int inputs, compares each new int to the previous (higher, lower, equal): e.g, first number = 10, next number = 5, output = lower. This loops until user enters [0]

But I now want to change it so that all the outputs are at the end instead of 1 after each pair. Let's say overall input is 2, 3, 6, 6, 5, 1 [0]: print statement should be only after [0] which would say, e.g., higher higher equal lower lower (all in one statement).

Things I've tried... print(a) but of course (a) gets reassigned to each new number..... tried (rookie mistake): if b < a: b = "higher" but '<' not supported between instances of 'str' and 'int'...... tried a list but error: expected list but received int...... another error (can't remember what I tried): int object is not iterable. (Also, I know I should probably have some elifs instead of all these ifs but that's not causing problems...)

My code:

z = 0
done = False
a = int(input("Enter first number: "))
while not done:
    b = int(input("Enter next number [0 = done]: "))
    if b != z: #while program not done
        if b > a:
            print("higher")
        if b == a:
            print("equal")
        if b < a:
            print("lower")
        a = b #second number becomes first and repeat
    else:
        done = True

Any help is greatly appreciated. Thank you.

Body:
Track the responses, print at the end.

z = 0
done = False
a = int(input("Enter first number: "))
track_comparisons = []
while not done:
    b = int(input("Enter next number [0 = done]: "))
    if b != z: #while program not done
        if b > a:
            track_comparisons.append('higher')
        elif b == a:                       #change to if, elif, else
            track_comparisons.append('equal')
        else:
            track_comparisons.append("lower")
        a = b #second number becomes first and repeat
    else:
        for response in track_comparisons:
            print(response, end=' ')
        done = True


答:
Python considers function parameters as local variable. So since your function is accepting a parameter also named name, Python now considers name to be a local variable:

```<code>>>> global_variable = 0
>>> def foo(global_variable): # your creating a local variable here.
    global global_variable

SyntaxError: name 'global_variable' is parameter and global
>>>
</code>```

The fix is to remove name from your functions parameters. That way, Python will see name as a global variable:

```<code>name = "d"

def namechange (): # remove name
    global name
    name = "Henry"

print name
</code>```

However, you should avoid using globals when you can. In this case, it would be a better solution to pass name as a parameter to your function, and let the caller deal with updating the variable:

```<code>name = "d"

def namechange (name):
    name = "Henry"
    return name

new_name = namechange(name)
print new_name
</code>```

Title: How do I change a global variables contents within a function

Body:
I have created the following sample program to demonstrate what I'm trying to do:

name = "d"

def namechange (name):

    global name
    name = "Henry"
    return name

print name

The errors that is produced:

SyntaxError: name 'name' is local and global

I understand that the name variable is local and global, but I am new to this and do not know how to resolve this issue. Please help

Body:
Python considers function parameters as local variable. So since your function is accepting a parameter also named name, Python now considers name to be a local variable:

>>> global_variable = 0
>>> def foo(global_variable): # your creating a local variable here.
    global global_variable

SyntaxError: name 'global_variable' is parameter and global
>>>

The fix is to remove name from your functions parameters. That way, Python will see name as a global variable:

name = "d"

def namechange (): # remove name
    global name
    name = "Henry"

print name

However, you should avoid using globals when you can. In this case, it would be a better solution to pass name as a parameter to your function, and let the caller deal with updating the variable:

name = "d"

def namechange (name):
    name = "Henry"
    return name

new_name = namechange(name)
print new_name


问:
What is an idiomatic way to handle failure in Racket?
I am used to OCaml where I rely heavily on the result type, along with a monadic interface to handle failures in my applications. Exceptions do exist in OCaml but I rarely use them, except for working around the absence of a return keyword.

Is there such a trend in Racket (especially typed Racket)? What is an idiomatic way to handle and propagate failure in Racket applications?

答:
There are a few idioms:

exceptions

Exceptions are used mainly for errors, but occasionally for other kinds of "exceptional" situations.

(vector-ref "hello" 0) raises an exception, because a string is not a vector

(string-ref "hello" 72) raises an exception, because the index is out of bounds

(open-output-file "/does/not/exist") raises an exception if the path doesn't exist, or can't be opened because of permissions

result values

Some functions return a union where the type acts like a datatype variant. A result of X or false is especially common.

(assoc 'a '((a . 1) (b . 2))) returns the pair (a . 1), but

(assoc 'c '((a . 1) (b . 2))) returns false

(read-string 10) returns either a string or the special eof object if there are no characters available before the end of the port

The cond => syntax can be useful for dealing with X or false results:

```<code>(cond [(assoc key alist) => cdr] [else default-value])
</code>```

failure continuations

Some functions take an extra (usually optional) argument that determines what happens on certain kinds of failures.

(hash-ref ht key) raises an error if ht doesn't contain an entry for key, but

(hash-ref ht key failure) either calls failure (if it is a procedure) or just returns it (otherwise) if ht doesn't contain key

but (hash-ref not-a-hash-table key failure) raises a contract violation exception; it doesn't call failure

Body:
There are a few idioms:

exceptions

Exceptions are used mainly for errors, but occasionally for other kinds of "exceptional" situations.

(vector-ref "hello" 0) raises an exception, because a string is not a vector

(string-ref "hello" 72) raises an exception, because the index is out of bounds

(open-output-file "/does/not/exist") raises an exception if the path doesn't exist, or can't be opened because of permissions

result values

Some functions return a union where the type acts like a datatype variant. A result of X or false is especially common.

(assoc 'a '((a . 1) (b . 2))) returns the pair (a . 1), but

(assoc 'c '((a . 1) (b . 2))) returns false

(read-string 10) returns either a string or the special eof object if there are no characters available before the end of the port

The cond => syntax can be useful for dealing with X or false results:

(cond [(assoc key alist) => cdr] [else default-value])

failure continuations

Some functions take an extra (usually optional) argument that determines what happens on certain kinds of failures.

(hash-ref ht key) raises an error if ht doesn't contain an entry for key, but

(hash-ref ht key failure) either calls failure (if it is a procedure) or just returns it (otherwise) if ht doesn't contain key

but (hash-ref not-a-hash-table key failure) raises a contract violation exception; it doesn't call failure


问:
Webpack less-loader Missing Base Path on Production Build
I've got a vue-js app that uses webpack.  Everything works fine in development and test environments, but I'm having trouble getting it to build for production.

I've got background images in the LESS files.  The image files are in /static.  (I'm not sure whether that's kosher or if they should be in side src/assets.)

At any rate, when the LESS has something like this:

```<code> background-url: url("/static/img/foobar/my-image.svg")
</code>```

Then the compilted CSS will have the same url

```<code> background-url: url("/static/img/foobar/my-image.svg")
</code>```

When the browser loaders, it can't find that imgate file. The browser is attempting to find the file here:

```<code>file:///static/img/foobar/my-image.svg
</code>```

Can anyone recommend a way to prepend the absolute path when the app builds for production?

答:
Do you have your static assets outside of our project directory in /static ?
Otherwise I don't get why your browser is trying to request it from file:///static/img/foobar/my-image.svg

anyway, your static assets should be part of your repo/project. They do not need to be in src directory, a /static folder within the root of your project is just fine.

when you compile your application - let's say into a dist folder - you should copy the images also in that dist folder. In my app I use the copy-webpack-plugin for that task (I have my images in ./public/assets/img/.. and I reference them as /assets/img/..)

```<code>    const CopyWebpackPlugin = require('copy-webpack-plugin');
    ...

    plugins: [
    ...
    /** copy all files from the public folder to the compilation root */
    new CopyWebpackPlugin([{
        from: 'public',
        to  : ''
    }]),
    ...
</code>```

also you should make sure that you have the file-loader in place for your static assets. I use it like so:

```<code>  {
       test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\??\#?v=[.0-9]+)?$/,
       use : 'file-loader?name=assets/[name].[hash].[ext]'
  }
</code>```

I hope this will help you to resolve your problem.

Body:
I've got a vue-js app that uses webpack.  Everything works fine in development and test environments, but I'm having trouble getting it to build for production.

I've got background images in the LESS files.  The image files are in /static.  (I'm not sure whether that's kosher or if they should be in side src/assets.)

At any rate, when the LESS has something like this:

 background-url: url("/static/img/foobar/my-image.svg")

Then the compilted CSS will have the same url

 background-url: url("/static/img/foobar/my-image.svg")

When the browser loaders, it can't find that imgate file. The browser is attempting to find the file here:

file:///static/img/foobar/my-image.svg

Can anyone recommend a way to prepend the absolute path when the app builds for production?

Body:
Do you have your static assets outside of our project directory in /static ?
Otherwise I don't get why your browser is trying to request it from file:///static/img/foobar/my-image.svg

anyway, your static assets should be part of your repo/project. They do not need to be in src directory, a /static folder within the root of your project is just fine.

when you compile your application - let's say into a dist folder - you should copy the images also in that dist folder. In my app I use the copy-webpack-plugin for that task (I have my images in ./public/assets/img/.. and I reference them as /assets/img/..)

    const CopyWebpackPlugin = require('copy-webpack-plugin');
    ...

    plugins: [
    ...
    /** copy all files from the public folder to the compilation root */
    new CopyWebpackPlugin([{
        from: 'public',
        to  : ''
    }]),
    ...

also you should make sure that you have the file-loader in place for your static assets. I use it like so:

  {
       test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\??\#?v=[.0-9]+)?$/,
       use : 'file-loader?name=assets/[name].[hash].[ext]'
  }

I hope this will help you to resolve your problem.


问:
Handling repeating return values, with individual messages
I have this code which works perfect for me, when running just one objShell.Run line.

```<code>Set objShell = WScript.CreateObject("WScript.Shell")

retval = objShell.Run ("cmd /c title Phase 1 & robocopy C:\this C:\that /MIR /L",1,True)

If retval < 0 Then
    MsgBox "cmd aborted, return value is: " & retval
ElseIf retval > 7 Then
    MsgBox "robocopy error, return value is: " & retval
Else
    MsgBox "robocopy successful, return value is: " & retval
End If
</code>```

How would I need to go, when I want to have multiple objShell.Run lines?
E.g.

```<code>retval = objShell.Run ("cmd /c title Phase 1 & robocopy C:\this C:\that /MIR /L",1,True)
retval = objShell.Run ("cmd /c title Phase 2 & robocopy C:\thistoo C:\thattoo /MIR /L",1,True)
retval = objShell.Run ("cmd /c title Phase 3 & robocopy C:\andthis C:\andthat /MIR /L",1,True)
</code>```

I could make each retval variable unique e.g. retval1, retval2, retval3
And iterate the [If..Then..Else] statement, but that feels clunky and probably not the nicest way to go.

For me the best way would be a MsgBox showing a "report" about each individual objShell.Run line, when they are finished. Except when all lines are successful, then a MsgBox "all done" will do just fine.

In which direction do I need to start my search? Functions, arrays?

答:
I've never used that object WScript.Shell,

but having had a look at your code, sample and explanation.
I think this is what you mean?

```<code>'-> Initialise
SequenceSteps = 3
Result = ""
ErrString = ""
MyCommandSequence(0) = "cmd /c title Phase 1 & robocopy C:\this C:\that /MIR /L"
MyCommandSequence(1) = "cmd /c title Phase 2 & robocopy C:\thistoo C:\thattoo /MIR /L"
MyCommandSequence(2) = "cmd /c title Phase 3 & robocopy C:\andthis C:\andthat /MIR /L"

'-> Process
ErrorOccurred = False
For Counta = 0 To SequenceSteps - 1
    Set objShell = WScript.CreateObject("WScript.Shell")
    retval = objShell.Run (MyCommandSequence(Counta), 1, True)
    '-> process request result
    If retval < 0 Then
        ErrString = "cmd aborted, return value is: " & retval
        '** NEW CODE LINE **
        Exit For
    ElseIf retval > 7 Then
        ErrString = "robocopy error, return value is: " & retval
        '** NEW CODE LINE **
        Exit For
    Else
        Result = Result  & "robocopy successful, return value is: " & retval & vbcrlf
    End If
Next
'-> Display Accordingly
If Trim(ErrString) <> "" Then
    MsgBox Result & vbcrlf & ErrString
Else
    MsgBox "All Done"
End if
</code>```

UPDATE

Re-Edited code

Body:
I have this code which works perfect for me, when running just one objShell.Run line.

Set objShell = WScript.CreateObject("WScript.Shell")

retval = objShell.Run ("cmd /c title Phase 1 & robocopy C:\this C:\that /MIR /L",1,True)

If retval < 0 Then
    MsgBox "cmd aborted, return value is: " & retval
ElseIf retval > 7 Then
    MsgBox "robocopy error, return value is: " & retval
Else
    MsgBox "robocopy successful, return value is: " & retval
End If

How would I need to go, when I want to have multiple objShell.Run lines?
E.g.

retval = objShell.Run ("cmd /c title Phase 1 & robocopy C:\this C:\that /MIR /L",1,True)
retval = objShell.Run ("cmd /c title Phase 2 & robocopy C:\thistoo C:\thattoo /MIR /L",1,True)
retval = objShell.Run ("cmd /c title Phase 3 & robocopy C:\andthis C:\andthat /MIR /L",1,True)

I could make each retval variable unique e.g. retval1, retval2, retval3
And iterate the [If..Then..Else] statement, but that feels clunky and probably not the nicest way to go.

For me the best way would be a MsgBox showing a "report" about each individual objShell.Run line, when they are finished. Except when all lines are successful, then a MsgBox "all done" will do just fine.

In which direction do I need to start my search? Functions, arrays?

Body:
I've never used that object WScript.Shell,

but having had a look at your code, sample and explanation.
I think this is what you mean?

'-> Initialise
SequenceSteps = 3
Result = ""
ErrString = ""
MyCommandSequence(0) = "cmd /c title Phase 1 & robocopy C:\this C:\that /MIR /L"
MyCommandSequence(1) = "cmd /c title Phase 2 & robocopy C:\thistoo C:\thattoo /MIR /L"
MyCommandSequence(2) = "cmd /c title Phase 3 & robocopy C:\andthis C:\andthat /MIR /L"

'-> Process
ErrorOccurred = False
For Counta = 0 To SequenceSteps - 1
    Set objShell = WScript.CreateObject("WScript.Shell")
    retval = objShell.Run (MyCommandSequence(Counta), 1, True)
    '-> process request result
    If retval < 0 Then
        ErrString = "cmd aborted, return value is: " & retval
        '** NEW CODE LINE **
        Exit For
    ElseIf retval > 7 Then
        ErrString = "robocopy error, return value is: " & retval
        '** NEW CODE LINE **
        Exit For
    Else
        Result = Result  & "robocopy successful, return value is: " & retval & vbcrlf
    End If
Next
'-> Display Accordingly
If Trim(ErrString) <> "" Then
    MsgBox Result & vbcrlf & ErrString
Else
    MsgBox "All Done"
End if

UPDATE

Re-Edited code


问:
How to switch Backend with Keras (from TensorFlow to Theano)
I tried to switch Backend with Keras (from TensorFlow to Theano) but did not manage.
I followed the temps described here but it doesn't work. I created a keras.json in the keras' directory (as it did not exist) but it doesn't change anything when I import it from Python.</p>

答:
In case you want to change the config permanently, the json is available here: ~/.keras/keras.json and you can change the backend.

To do this dynamically in python 2.7 you can run:

from keras import backend as K
import os

def set_keras_backend(backend):

    if K.backend() != backend:
        os.environ['KERAS_BACKEND'] = backend
        reload(K)
        assert K.backend() == backend

set_keras_backend("theano")
```


问:
Strict aliasing rule and strlen implementation of glibc
I have been reading about the strict aliasing rule for a while, and I'm starting to get really confused. First of all, I have read these questions and some answers:

strict-aliasing-rule-and-char-pointers

when-is-char-safe-for-strict-pointer-aliasing

is-the-strict-aliasing-rule-really-a-two-way-street

According to them (as far as I understand), accessing a char buffer using a pointer to another type violates the strict aliasing rule. However, the glibc implementation of strlen() has such code (with comments and the 64-bit implementation removed):

```<code>size_t strlen(const char *str)
{
    const char *char_ptr;
    const unsigned long int *longword_ptr;
    unsigned long int longword, magic_bits, himagic, lomagic;

    for (char_ptr = str; ((unsigned long int) char_ptr
             & (sizeof (longword) - 1)) != 0; ++char_ptr)
       if (*char_ptr == '\0')
           return char_ptr - str;

    longword_ptr = (unsigned long int *) char_ptr;

    himagic = 0x80808080L;
    lomagic = 0x01010101L;

    for (;;)
    {
        longword = *longword_ptr++;

        if (((longword - lomagic) & himagic) != 0)
        {
            const char *cp = (const char *) (longword_ptr - 1);

            if (cp[0] == 0)
                return cp - str;
            if (cp[1] == 0)
                return cp - str + 1;
            if (cp[2] == 0)
                return cp - str + 2;
            if (cp[3] == 0)
                return cp - str + 3;
        }
    }
}
</code>```

The longword_ptr = (unsigned long int *) char_ptr; line obviously aliases an unsigned long int to char. I fail to understand what makes this possible. I see that the code takes care of alignment problems, so no issues there, but  I think this is not related with the strict aliasing rule.

The accepted answer for the third linked question says:

However, there is a very common compiler extension allowing you to cast properly aligned pointers from char to other types and access them, however this is non-standard.

Only thing comes to my mind is the -fno-strict-aliasing option, is this the case? I could not find it documented anywhere what glibc implementors depend on, and the comments somehow imply that this cast is done without any concerns like it is obvious that there will be no problems. That makes me think that it is indeed obvious and I am missing something silly, but my search failed me.

答:
In ISO C this code would violate the strict aliasing rule. (And also violate the rule that you cannot define a function with the same name as a standard library function). However this code is not subject to the rules of ISO C.  The standard library doesn't even have to be implemented in a C-like language. The standard only specifies that the implementation implements the behaviour of the standard functions.

In this case, we could say that the implementation is in a C-like GNU dialect, and if the code is compiled with the writer's intended compiler and settings then it would implement the standard library function successfully.

Body:
I have been reading about the strict aliasing rule for a while, and I'm starting to get really confused. First of all, I have read these questions and some answers:

strict-aliasing-rule-and-char-pointers

when-is-char-safe-for-strict-pointer-aliasing

is-the-strict-aliasing-rule-really-a-two-way-street

According to them (as far as I understand), accessing a char buffer using a pointer to another type violates the strict aliasing rule. However, the glibc implementation of strlen() has such code (with comments and the 64-bit implementation removed):

size_t strlen(const char *str)
{
    const char *char_ptr;
    const unsigned long int *longword_ptr;
    unsigned long int longword, magic_bits, himagic, lomagic;

    for (char_ptr = str; ((unsigned long int) char_ptr
             & (sizeof (longword) - 1)) != 0; ++char_ptr)
       if (*char_ptr == '\0')
           return char_ptr - str;

    longword_ptr = (unsigned long int *) char_ptr;

    himagic = 0x80808080L;
    lomagic = 0x01010101L;

    for (;;)
    {
        longword = *longword_ptr++;

        if (((longword - lomagic) & himagic) != 0)
        {
            const char *cp = (const char *) (longword_ptr - 1);

            if (cp[0] == 0)
                return cp - str;
            if (cp[1] == 0)
                return cp - str + 1;
            if (cp[2] == 0)
                return cp - str + 2;
            if (cp[3] == 0)
                return cp - str + 3;
        }
    }
}

The longword_ptr = (unsigned long int *) char_ptr; line obviously aliases an unsigned long int to char. I fail to understand what makes this possible. I see that the code takes care of alignment problems, so no issues there, but  I think this is not related with the strict aliasing rule.

The accepted answer for the third linked question says:

However, there is a very common compiler extension allowing you to cast properly aligned pointers from char to other types and access them, however this is non-standard.

Only thing comes to my mind is the -fno-strict-aliasing option, is this the case? I could not find it documented anywhere what glibc implementors depend on, and the comments somehow imply that this cast is done without any concerns like it is obvious that there will be no problems. That makes me think that it is indeed obvious and I am missing something silly, but my search failed me.


答:
In method set (for matrix) you define a new matrix which has nothing in common with matrix from the class, it's function's 2D array, not array from the class.

You probably want to do this:

```<code>    public void set(int n, int m, double d){
        this.matrix [n][m] = d;
    }
</code>```

By using this.property, you say you're using property from the class and not from the method.

Hope it helped

Title: Trying to create a setter method for my wrapper class matrix

Body:
I have defined a own class, which implements a Wrapper class matrix for a 2-dimnesional Array. With a setter-method 'set(int n, int m, double d)' I want to set/change the value at the position n(row),m(colum) into d.

public class Matrix {

double matrix [][];
int matrixSize;

public Matrix(int matrixSize){
    this.matrix = new double [matrixSize][matrixSize];
}

public void setMatrixSize(int size){
    matrixSize = size;
}

public int getMatrixSize(){
    return matrixSize;
}

public void set(int n, int m, double d){
    double matrix [n][m] = d;
}}

I know, that my last method does not work, but I don't really know how to set the value double d at the array matrix at the position n, m.

If some of you may can help me I would be very grateful.

Body:
In method set (for matrix) you define a new matrix which has nothing in common with matrix from the class, it's function's 2D array, not array from the class.

You probably want to do this:

    public void set(int n, int m, double d){
        this.matrix [n][m] = d;
    }

By using this.property, you say you're using property from the class and not from the method.

Hope it helped


问:
Painting different vertical segments under curve using d3
I am trying to create a simple line graph using d3 which segments the curve and paint each segment with a different colour. Currently I am only able to colour the whole area under the curve.

Current:

Attempting to achieve (Pardon me for the terrible colouring. In a rush for time):

This is bits of relevant code. Please help!

```<code>var x = d3.scaleLinear();
var y = d3.scaleLinear();

//Set the range of the data
x.domain([0, Math.max(endGrowth, endPlateau) ,maxX]).range([0, width*0.8, width]);
y.domain([0, maxY]).range([height, 0]);

//Define the area under the Graph
var area1 = d3.area()
.x0(function(d){
    return x(d.Rank);
})
.y1(function(d){ return y(d.Elements);})
.y0(height);

//Add the colored regions
svg.append("path")
.data([data])
.attr("class", "areaUnderGraph")
.attr("fill", "blue")
.attr("transform", "translate(" + leftMarginLabel + ",0)")
.attr("d", area1);
</code>```

答:
Right now, the area under the curve is one path, so it can only be colored one color. The simplest way to color different portions under the curve different colors is to split them up in data. It's not clear where data is coming from, but you'd take sub-sections of the array, like

```<code>var segments = [data.slice(0, 2), data.slice(2)];

svg.selectAll("path")
  .data(segments)
  .enter()
  .append("path")
  .attr("fill", function(d) { /* use d to choose a color */ })
</code>```

That's the gist: you'd have multiple slices of the data, and instead of one path, you'd create multiple paths that you can color as you wish.

Body:
I am trying to create a simple line graph using d3 which segments the curve and paint each segment with a different colour. Currently I am only able to colour the whole area under the curve.

Current:

Attempting to achieve (Pardon me for the terrible colouring. In a rush for time):

This is bits of relevant code. Please help!

var x = d3.scaleLinear();
var y = d3.scaleLinear();

//Set the range of the data
x.domain([0, Math.max(endGrowth, endPlateau) ,maxX]).range([0, width*0.8, width]);
y.domain([0, maxY]).range([height, 0]);

//Define the area under the Graph
var area1 = d3.area()
.x0(function(d){
    return x(d.Rank);
})
.y1(function(d){ return y(d.Elements);})
.y0(height);

//Add the colored regions
svg.append("path")
.data([data])
.attr("class", "areaUnderGraph")
.attr("fill", "blue")
.attr("transform", "translate(" + leftMarginLabel + ",0)")
.attr("d", area1);

Body:
Right now, the area under the curve is one path, so it can only be colored one color. The simplest way to color different portions under the curve different colors is to split them up in data. It's not clear where data is coming from, but you'd take sub-sections of the array, like

var segments = [data.slice(0, 2), data.slice(2)];

svg.selectAll("path")
  .data(segments)
  .enter()
  .append("path")
  .attr("fill", function(d) { /* use d to choose a color */ })

That's the gist: you'd have multiple slices of the data, and instead of one path, you'd create multiple paths that you can color as you wish.


问:
Automatic connecting to a BLE device [Android]
I am working on an Android application that should automatically connect to the BLE device with a specified MAC-address.
Basically a scan should be running 24/7, and as soon as the device is discovered, the service should connect to it, and ideally stop scanning.

What I managed to do is the following:

```<code>public void startBluetoothScan() {
    if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
            == PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        if (!scanning) {
            service.startScan();
        }
    }
}
</code>```

with this being the overall method:

```<code>private void configBluetooth() {
    BluetoothConfiguration config = new BluetoothConfiguration();
    config.context = getApplicationContext();
    config.bluetoothServiceClass = BluetoothLeService.class; // BluetoothClassicService.class or BluetoothLeService.class
    config.bufferSize = 1024;
    config.characterDelimiter = '\n';
    config.deviceName = "Your App Name";
    config.callListenersInMainThread = true;

    // Bluetooth Classic
    config.uuid = null; // Set null to find all devices on scan.

    // Bluetooth LE
    config.uuidService = UUID_HRS;
    config.uuidCharacteristic = UUID_HRD;
    config.transport = BluetoothDevice.TRANSPORT_LE; // Only for dual-mode devices

    BluetoothLeService.init(config);
    service = (BluetoothLeService) BluetoothLeService.getDefaultInstance();

    service.setOnScanCallback(new BluetoothLeService.OnBluetoothScanCallback() {
        @Override
        public void onDeviceDiscovered(BluetoothDevice device, int rssi) {
            Log.d("Found device address", device.getAddress());
            if (device.getAddress().equals(UserHRMAddress)){
                if (!deviceList.contains(device)) {
                    Log.d("Connecting to", device.getAddress());
                    connectDevice(device);
                    deviceList.add(device);
                }
            }
        }

        @Override
        public void onStartScan() {
            Log.d("Started Scan", "now");
            scanning = true;
        }

        @Override
        public void onStopScan() {
            Log.d("Stopped Scan", "now");
            scanning = false;
            startBluetoothScan();
        }
    });

    service.startScan();
}
</code>```

The method above is the usage of this library that should make BLE easier (I tried it raw and liked it equally little) Basically the scan returns the same device about a thousand times in a few seconds, without having the chance to connect to it first. Is there a possibility to let every device only be discovered once while scanning? Is there a more appropriate way to implement a 24/7 search with automated connecting?

What I also found out is, that the BluetoothGattCallback onConnectionStateChange method does e.g. not get called when you simply turn the BLE device off, or if you enter flight mode. If it did that, it would make my life a lot easier.

The relevant parts of my BluetoothGattCallback method look like this:

```<code>@Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.d("onConnectionStateChange", gatt.getDevice().getName());
                mBluetoothGatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                //mBluetoothAdapter.startLeScan(mLeScanCallback);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.d("Status", "success");
                heartRateService = gatt.getService(UUID_HRS);
                batteryLevelService = gatt.getService(Battery_Service_UUID);

                if (batteryLevelService != null) {
                    batteryLevelCharacteristic =
                            batteryLevelService.getCharacteristic(Battery_Level_UUID);
                }

                if (heartRateService != null) {

                    heartRateCharacteristic = heartRateService.getCharacteristic(UUID_HRD);
                    boolean res = gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_LOW_POWER);
                    gatt.setCharacteristicNotification(heartRateCharacteristic, true);

                    try {
                        BluetoothGattDescriptor descriptor = heartRateCharacteristic.getDescriptor(
                                UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG));

                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

                        mBluetoothGatt.writeDescriptor(descriptor);
                    } catch (Exception ex) {
                        Log.e(TAG, "wuuuuut?");

                    }

                }

            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }
</code>```

答:
Just use connectGatt with autoConnect = true. That works on all Android versions and there are no restriction on usage compared to scanning, as introduced in Nougat. Doing that will tell the Bluetooth controller to connect to the device as soon as it detects an advertisement. Note that since the android api unfortunately lacks "address type" parameter when connecting to a specific BD address, you either need to be bonded with the device OR it must have been discovered by some Bluetooth scan since the Bluetooth was last time turned on.

Unfortunately you still need a Bluetooth state change broadcast receiver to restart everything when Bluetooth is turned on.

Body:
I am working on an Android application that should automatically connect to the BLE device with a specified MAC-address.
Basically a scan should be running 24/7, and as soon as the device is discovered, the service should connect to it, and ideally stop scanning.

What I managed to do is the following:

public void startBluetoothScan() {
    if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
            == PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        if (!scanning) {
            service.startScan();
        }
    }
}

with this being the overall method:

private void configBluetooth() {
    BluetoothConfiguration config = new BluetoothConfiguration();
    config.context = getApplicationContext();
    config.bluetoothServiceClass = BluetoothLeService.class; // BluetoothClassicService.class or BluetoothLeService.class
    config.bufferSize = 1024;
    config.characterDelimiter = '\n';
    config.deviceName = "Your App Name";
    config.callListenersInMainThread = true;

    // Bluetooth Classic
    config.uuid = null; // Set null to find all devices on scan.

    // Bluetooth LE
    config.uuidService = UUID_HRS;
    config.uuidCharacteristic = UUID_HRD;
    config.transport = BluetoothDevice.TRANSPORT_LE; // Only for dual-mode devices

    BluetoothLeService.init(config);
    service = (BluetoothLeService) BluetoothLeService.getDefaultInstance();

    service.setOnScanCallback(new BluetoothLeService.OnBluetoothScanCallback() {
        @Override
        public void onDeviceDiscovered(BluetoothDevice device, int rssi) {
            Log.d("Found device address", device.getAddress());
            if (device.getAddress().equals(UserHRMAddress)){
                if (!deviceList.contains(device)) {
                    Log.d("Connecting to", device.getAddress());
                    connectDevice(device);
                    deviceList.add(device);
                }
            }
        }

        @Override
        public void onStartScan() {
            Log.d("Started Scan", "now");
            scanning = true;
        }

        @Override
        public void onStopScan() {
            Log.d("Stopped Scan", "now");
            scanning = false;
            startBluetoothScan();
        }
    });

    service.startScan();
}

The method above is the usage of this library that should make BLE easier (I tried it raw and liked it equally little) Basically the scan returns the same device about a thousand times in a few seconds, without having the chance to connect to it first. Is there a possibility to let every device only be discovered once while scanning? Is there a more appropriate way to implement a 24/7 search with automated connecting?

What I also found out is, that the BluetoothGattCallback onConnectionStateChange method does e.g. not get called when you simply turn the BLE device off, or if you enter flight mode. If it did that, it would make my life a lot easier.

The relevant parts of my BluetoothGattCallback method look like this:

@Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.d("onConnectionStateChange", gatt.getDevice().getName());
                mBluetoothGatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                //mBluetoothAdapter.startLeScan(mLeScanCallback);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.d("Status", "success");
                heartRateService = gatt.getService(UUID_HRS);
                batteryLevelService = gatt.getService(Battery_Service_UUID);

                if (batteryLevelService != null) {
                    batteryLevelCharacteristic =
                            batteryLevelService.getCharacteristic(Battery_Level_UUID);
                }

                if (heartRateService != null) {

                    heartRateCharacteristic = heartRateService.getCharacteristic(UUID_HRD);
                    boolean res = gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_LOW_POWER);
                    gatt.setCharacteristicNotification(heartRateCharacteristic, true);

                    try {
                        BluetoothGattDescriptor descriptor = heartRateCharacteristic.getDescriptor(
                                UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG));

                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

                        mBluetoothGatt.writeDescriptor(descriptor);
                    } catch (Exception ex) {
                        Log.e(TAG, "wuuuuut?");

                    }

                }

            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }


问:
Center middle of 3 images, left and right images align to middle image
Is it possible to have the middle of 3 images centered horizontally, then have the left image align to the left of the middle image, and the right image align to the right of the middle image?

https://jsfiddle.net/0wk84qaf/

```<code><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<div style="text-align:center;">
    <div style="display:inline-block;">
        <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award1-2.jpg" style="vertical-align:middle;" />
        <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award3-2.jpg" style="vertical-align:middle;" />
        <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award2-2.jpg" style="vertical-align:middle;" />
    </div>
</div>
</code>```

You can see, currently, the whole div is centered, but the middle image is slightly off-center, whereas I'd like it to be bang in the middle...

答:
You can use absolute positioning. Center the middle image in the parent, and absolutely position the other elements to either side of that parent.

.images {
  display: inline-block;
  position: relative;
}

.images img:first-child,
.images img:last-child {
  position: absolute;
  top: 50%;
}

.images img:first-child {
  left: 0;
  transform: translate(-100%,-50%);
}

.images img:last-child {
  right: 0;
  transform: translate(100%,-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<div style="text-align:center;">
  <div class="images">
    <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award1-2.jpg" style="vertical-align:middle;" />
    <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award3-2.jpg" style="vertical-align:middle;" />
    <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award2-2.jpg" style="vertical-align:middle;" />
  </div>
</div></code>```

Body:
Is it possible to have the middle of 3 images centered horizontally, then have the left image align to the left of the middle image, and the right image align to the right of the middle image?

https://jsfiddle.net/0wk84qaf/

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

You can see, currently, the whole div is centered, but the middle image is slightly off-center, whereas I'd like it to be bang in the middle...

Body:
You can use absolute positioning. Center the middle image in the parent, and absolutely position the other elements to either side of that parent.

.images {
  display: inline-block;
  position: relative;
}

.images img:first-child,
.images img:last-child {
  position: absolute;
  top: 50%;
}

.images img:first-child {
  left: 0;
  transform: translate(-100%,-50%);
}

.images img:last-child {
  right: 0;
  transform: translate(100%,-50%);
}

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<div style="text-align:center;">
  <div class="images">
    <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award1-2.jpg" style="vertical-align:middle;" />
    <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award3-2.jpg" style="vertical-align:middle;" />
    <img src="http://rubyandgrace.cdudigital.com/wp-content/uploads/2017/06/award2-2.jpg" style="vertical-align:middle;" />
  </div>
</div>