问:
How to dowload csv file containing HTML tags
I'm trying to download data from mysql database. One field in DB contains HTML tags.

When I try to open downloaded csv this file in excel it works wrong, because of tabulation and HTML tags. Is there any way to open it correctly in excel?

My php script:

```<code><?php
/*******EDIT LINES 3-8*******/
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "root"; //MySQL Username
$DB_Password = "";             //MySQL Password
$DB_DBName = "ud-for-downloading-items";         //MySQL Database Name
$DB_TBLName = "oc_product_description"; //MySQL Table Name
$filename = "oc_product_description";         //File Name
/*******YOU DO NOT NEED TO EDIT ANYTHING BELOW THIS LINE*******/
//create MySQL connection
$sql = "Select * from $DB_TBLName";
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
//execute query
$result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
$file_ending = "csv";
//header info for browser
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header("Content-Disposition: attachment; filename=$filename.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo "\xEF\xBB\xBF"; // UTF-8 BOM

/*******Start of Formatting for Excel*******/
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");
//end of printing column names
//start while loop to get data
    while($row = mysql_fetch_row($result))
    {
        $schema_insert = "";
        for($j=0; $j<mysql_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        print(trim($schema_insert));
        print "\n";
    }
?>
</code>```

UPDATE: added images

答:
Take a look at those 2 functions:
htmlentities() encodes al html into chars (e.g. &quot)
html_entity_decode() goes backwords, converting all the matching chars to html elements.

You could them during you data transfer, based on your needs.
If this won't work you could try a final shot at filter_var()

Body:
I'm trying to download data from mysql database. One field in DB contains HTML tags.

When I try to open downloaded csv this file in excel it works wrong, because of tabulation and HTML tags. Is there any way to open it correctly in excel?

My php script:

<?php
/*******EDIT LINES 3-8*******/
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "root"; //MySQL Username
$DB_Password = "";             //MySQL Password
$DB_DBName = "ud-for-downloading-items";         //MySQL Database Name
$DB_TBLName = "oc_product_description"; //MySQL Table Name
$filename = "oc_product_description";         //File Name
/*******YOU DO NOT NEED TO EDIT ANYTHING BELOW THIS LINE*******/
//create MySQL connection
$sql = "Select * from $DB_TBLName";
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:
" . mysql_error() . "
" . mysql_errno());
//select database
$Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:
" . mysql_error(). "
" . mysql_errno());
//execute query
$result = @mysql_query($sql,$Connect) or die("Couldn't execute query:
" . mysql_error(). "
" . mysql_errno());
$file_ending = "csv";
//header info for browser
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header("Content-Disposition: attachment; filename=$filename.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo "\xEF\xBB\xBF"; // UTF-8 BOM

/*******Start of Formatting for Excel*******/
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");
//end of printing column names
//start while loop to get data
    while($row = mysql_fetch_row($result))
    {
        $schema_insert = "";
        for($j=0; $j<mysql_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        print(trim($schema_insert));
        print "\n";
    }
?>

UPDATE: added images


来源: stackexchange

问:
How does Ramda.map over Immutable.List return a List instead of an Array?
I have created a List of Maps in Immutable.js which looks like:

```<code>List [
  Map { "id": 0, "name": "John" },
  Map { "id": 1, "name": "Lennon" }
]
</code>```

Now, I have used Ramda's R.map to map over the above list:

```<code>R.map(map => map.get('id'))(a)
</code>```

It returns a new List of id's which is of type Immutable.List, but not a JS Array.

```<code>List [ 0, 1 ]
</code>```

I understand that we can iterate over any data structure if it's Symbol.iterator is defined. But the returned type is also a List.

How is this possible?

答:
The reason you get a List is explained in the Ramda documentation:

map

Dispatches to the map method of the second argument, if present.

The second argument in your case is a List. And yes, a List has a map method, as found in the Immutable documentation:

map

Returns a new List with values passed through a mapper function.

So that explains why you get a List.

ContentLicense: CC BY-SA 3.0

Body:
I have created a List of Maps in Immutable.js which looks like:

List [
  Map { "id": 0, "name": "John" },
  Map { "id": 1, "name": "Lennon" }
]

Now, I have used Ramda's R.map to map over the above list:

R.map(map => map.get('id'))(a)

It returns a new List of id's which is of type Immutable.List, but not a JS Array.

List [ 0, 1 ]

I understand that we can iterate over any data structure if it's Symbol.iterator is defined. But the returned type is also a List.

How is this possible?


问:
choose n largest elements in two vector
I have two vectors, each contains n unsorted elements, how can I get n largest elements in these two vectors?

my solution is merge two vector into one with 2n elements, and then use std::nth_element algorithm, but I found that's not quite efficient, so anyone has more efficient solution. Really appreciate.

答: You may push the elements into priority_queue and then pop n elements out.

ContentLicense: CC BY-SA 2.5

Title: choose n largest elements in two vector


问:
Multi-line text padding
I have a following structure:

```<code><div class="1">
  <div class="2">
    2.
  </div>
  <div class="3">
    3.
  </div>
  <div class="4">
    very long line of text
  </div>
</div>
</code>```

So div 1 has display: block, all the others have display: inline. My goal is to make this very long line of text being displayed like that:

```<code>2. 3. very long
      line of text
</code>```

If I try making div 4 an inline-block or inline-flex and set margin and text-indent properties, then it kinda does what I want, but it also moves whole text down one line like this:

```<code>2. 3.
very long
      line of text
</code>```

How do I do that properly?

答:
Use flex to solve this, make the container div display flex.

Make sure your classes start with a letter (Which characters are valid in CSS class names/selectors?)

https://jsfiddle.net/cymozzeL/1/

```<code>.t1 {
  display: flex;
}
</code>```

There is a lot more you can do with this, please have a look at

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Title: Multi-line text padding

Body:
I have a following structure:

    2.

    3.

    very long line of text

So div 1 has display: block, all the others have display: inline. My goal is to make this very long line of text being displayed like that:

2. 3. very long
      line of text

If I try making div 4 an inline-block or inline-flex and set margin and text-indent properties, then it kinda does what I want, but it also moves whole text down one line like this:

2. 3.
very long
      line of text

How do I do that properly?

Body:
Use flex to solve this, make the container div display flex.

Make sure your classes start with a letter (Which characters are valid in CSS class names/selectors?)

https://jsfiddle.net/cymozzeL/1/

.t1 {
  display: flex;
}

There is a lot more you can do with this, please have a look at

https://css-tricks.com/snippets/css/a-guide-to-flexbox/


问:
C# - get data between dates
The SQL database I am trying to reach has the following columns and their types (as displayed in the "design" window in Microsoft SQL Server Management Studio):

timestamp : Datetime (for example : 2017-05-15 08:53:55.000)

price : Single               ,             etc.

I want to send to select all the prices where their timestamp is between now and yesterday, for example. Even though i would like an example for a month too.

My code looks like this:

```<code>string query = "SELECT price FROM table WHERE  timestamp>=@now AND timestamp<=@yes);";
        SqlCommand command = new SqlCommand(query, sqlConnection);
        command.Parameters.AddWithValue("@now", DateTime.Now);
        command.Parameters.AddWithValue("@yesterday", DateTime.Now.AddDays(-1));
</code>```

But my reader returns empty, what am I doing wrong?

答:
You can use BETWEEN, also Yesterday is less than Today:

```<code>SELECT price FROM table WHERE timestamp BETWEEN @yesterday AND @now
</code>```

Title: C# - get data between dates

Body:
The SQL database I am trying to reach has the following columns and their types (as displayed in the "design" window in Microsoft SQL Server Management Studio):

timestamp : Datetime (for example : 2017-05-15 08:53:55.000)

price : Single               ,             etc.

I want to send to select all the prices where their timestamp is between now and yesterday, for example. Even though i would like an example for a month too.

My code looks like this:

string query = "SELECT price FROM table WHERE  timestamp>=@now AND timestamp<=@yes);";
        SqlCommand command = new SqlCommand(query, sqlConnection);
        command.Parameters.AddWithValue("@now", DateTime.Now);
        command.Parameters.AddWithValue("@yesterday", DateTime.Now.AddDays(-1));

But my reader returns empty, what am I doing wrong?

Body:
You can use BETWEEN, also Yesterday is less than Today:

SELECT price FROM table WHERE timestamp BETWEEN @yesterday AND @now


问:
Population must be a sequence or set. For dicts, use list(d)
I try to excute this code and I get the error bellow, I get the error in the random function and I don't know how to fix it, please help me.

```<code>def load_data(sample_split=0.3, usage='Training', to_cat=True, verbose=True,
          classes=['Angry','Happy'], filepath='C:/Users/Oussama/Desktop/fer2013.csv'):
    df = pd.read_csv(filepath)
    # print df.tail()
    # print df.Usage.value_counts()
    df = df[df.Usage == usage]
    frames = []
    classes.append('Disgust')
    for _class in classes:
        class_df = df[df['emotion'] == emotion[_class]]
        frames.append(class_df)
    data = pd.concat(frames, axis=0)
    rows = random.sample(data.index, int(len(data)*sample_split))
    data = data.ix[rows]
    print ('{} set for {}: {}'.format(usage, classes, data.shape))
    data['pixels'] = data.pixels.apply(lambda x: reconstruct(x))
    x = np.array([mat for mat in data.pixels]) # (n_samples, img_width, img_height)
    X_train = x.reshape(-1, 1, x.shape[1], x.shape[2])
    y_train, new_dict = emotion_count(data.emotion, classes, verbose)
    print (new_dict)
    if to_cat:
        y_train = to_categorical(y_train)
    return X_train, y_train, new_dict
</code>```

I get this:

Traceback (most recent call last):
   File "fer2013datagen.py", line 71, in <module>
   verbose=True)
   File "fer2013datagen.py", line 47, in load_data
   rows = random.sample(data, int(len(data)*sample_split))

   File"
   C:\Users\Oussama\AppData\Local\Programs\Python\Python35\lib\random.py",
   line 311, in sample
   raise TypeError("Population must be a sequence or set.  For dicts, use
   list(d).")
TypeError: Population must be a sequence or set.  For dicts, use list(d).
```

答:
Your code here:

```<code>rows = random.sample(data.index, int(len(data)*sample_split))
</code>```

But, error message shows

```<code>rows = random.sample(data, int(len(data)*sample_split))
</code>```

Why different? Did you modify it? And what is the type of data  is?
is it a list? or a dict?

And, error message has already told you how to fix it.
it means the first parameter of random.sample must be a sequence or set. For dicts, use list(Dict).

For example,

```<code>d = {'a':1,'b':2}
random.sample(list(d), 1)
</code>```

instead of

```<code>random.sample(d, 1)
</code>```

Body:
I try to excute this code and I get the error bellow, I get the error in the random function and I don't know how to fix it, please help me.

def load_data(sample_split=0.3, usage='Training', to_cat=True, verbose=True,
          classes=['Angry','Happy'], filepath='C:/Users/Oussama/Desktop/fer2013.csv'):
    df = pd.read_csv(filepath)
    # print df.tail()
    # print df.Usage.value_counts()
    df = df[df.Usage == usage]
    frames = []
    classes.append('Disgust')
    for _class in classes:
        class_df = df[df['emotion'] == emotion[_class]]
        frames.append(class_df)
    data = pd.concat(frames, axis=0)
    rows = random.sample(data.index, int(len(data)*sample_split))
    data = data.ix[rows]
    print ('{} set for {}: {}'.format(usage, classes, data.shape))
    data['pixels'] = data.pixels.apply(lambda x: reconstruct(x))
    x = np.array([mat for mat in data.pixels]) # (n_samples, img_width, img_height)
    X_train = x.reshape(-1, 1, x.shape[1], x.shape[2])
    y_train, new_dict = emotion_count(data.emotion, classes, verbose)
    print (new_dict)
    if to_cat:
        y_train = to_categorical(y_train)
    return X_train, y_train, new_dict

I get this:

Traceback (most recent call last):
   File "fer2013datagen.py", line 71, in <module>
   verbose=True)
   File "fer2013datagen.py", line 47, in load_data
   rows = random.sample(data, int(len(data)*sample_split))

   File"
   C:\Users\Oussama\AppData\Local\Programs\Python\Python35\lib\random.py",
   line 311, in sample
   raise TypeError("Population must be a sequence or set.  For dicts, use
   list(d).")
TypeError: Population must be a sequence or set.  For dicts, use list(d).

Body:
Your code here:

rows = random.sample(data.index, int(len(data)*sample_split))

But, error message shows

rows = random.sample(data, int(len(data)*sample_split))

Why different? Did you modify it? And what is the type of data  is?
is it a list? or a dict?

And, error message has already told you how to fix it.
it means the first parameter of random.sample must be a sequence or set. For dicts, use list(Dict).

For example,

d = {'a':1,'b':2}
random.sample(list(d), 1)

instead of

random.sample(d, 1)


问:
Ionic framework error
I want to install Ionic framework on my Windows system.I am already installed Node.js latest version.When I Install Ionic framework on my system its showing error.
 Error:

```<code> npm WARN engine cordova-js@3.8.0: wanted: {"node":"~0.10.x"} (current: {"node":"0.12.0","npm":"2.5.1"})

npm WARN engine npm@1.3.4: wanted: {"node":">=0.6","npm":"1"} (current: {"node":"0.12.0","npm":"2.5.1"})

npm WARN engine xmlbuilder@2.2.1: wanted: {"node":"0.8.x || 0.10.x"} (current: {"node":"0.12.0","npm":"2.5.1"})
</code>```

Even installed Ionic command prompt way i am using command prompt for install
command Prompt: npm install -g cordova ionic

答:
Try Re installing

Generally run the latest production versions of node, npm, Ionic and Cordova.
or else change node js version to latest LTS version.

Use nvm (or nodist on Windows) so that you can easily switch between versions.
if you want the different version of node on single machine if you want other applications  which depend on different version of node to malfunction.

Ionic Box for windows :
use the ionic virtual machine.. to have anything installed you need:
http://blog.ionic.io/ionic-vagrant-android/229

Title: Ionic framework error

Body:
I want to install Ionic framework on my Windows system.I am already installed Node.js latest version.When I Install Ionic framework on my system its showing error.
 Error:

 npm WARN engine cordova-js@3.8.0: wanted: {"node":"~0.10.x"} (current: {"node":"0.12.0","npm":"2.5.1"})

npm WARN engine npm@1.3.4: wanted: {"node":">=0.6","npm":"1"} (current: {"node":"0.12.0","npm":"2.5.1"})

npm WARN engine xmlbuilder@2.2.1: wanted: {"node":"0.8.x || 0.10.x"} (current: {"node":"0.12.0","npm":"2.5.1"})

Even installed Ionic command prompt way i am using command prompt for install
command Prompt: npm install -g cordova ionic


问:
tvos 10 SDK duplicate class implemented in multiple private frameworks causes crash
I have an tvml app that works great on tvos 9, but when attempting to run on tvos 10.0 simulator the application fails to load and I am presented with a series of errors that begin with:

class PLBuildVersion is implemented in both
  /Applications/Xcode.app/Contents/Developer/Platforms/AppleTVSimulator.platform/Developer/SDKs/AppleTVSimulator.sdk/System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices
  (0x11619dd00) and
  /Applications/Xcode.app/Contents/Developer/Platforms/AppleTVSimulator.platform/Developer/SDKs/AppleTVSimulator.sdk/System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices
  (0x115d4a8e8). One of the two will be used. Which one is undefined.

i'm not using any pods. testing suggests the issue is restricted to tvos 10.0 SDK. how can i resolve a duplicate class conflict in apple's PrivateFrameworks?

答:
Have you tried updating the info.plist as described in another answer here?

That entry describes how to stop the crash, though if you issue is the same root cause, the warning will continue to appear when using the simulator.


问:
"pod update" doesn't update to latest version
Here is my podfile I use in the project:

```<code>source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!

pod 'AFNetworking', '~> 2.0'
pod 'GoogleMaps'
pod 'MONActivityIndicatorView'
pod 'NYXImagesKit'
pod 'MagicalRecord'
pod 'FBSDKCoreKit'
pod 'FBSDKShareKit'
pod 'FBSDKLoginKit'
pod 'Countly'
</code>```

The problem is that cocoapods 0.39 is updating AFNetworking to version 2.5.4 which is wrong. The latest version is 2.6.3 Also facebook SDK updating to 4.4 (latest is 4.8) etc.

I tried to delete Pods folder and .lock file but doesn't help

Also tried to clean the cocoapods cache but didn't help:

```<code>MACMINI:myproject myusername$ pod cache clean --all
MACMINI:myproject myusername$ pod update
Update all pods
Updating local specs repositories
Analyzing dependencies
Downloading dependencies
Installing AFNetworking (2.5.4)
Installing Bolts (1.2.0)
Installing Countly (15.06.01)
Installing FBSDKCoreKit (4.4.0)
Installing FBSDKLoginKit (4.4.0)
Installing FBSDKShareKit (4.4.0)
Installing GoogleMaps (1.10.1)
Installing MONActivityIndicatorView (0.0.3)
Installing MagicalRecord (2.3.0)
Installing NYXImagesKit (2.3)
Generating Pods project
Integrating client project

[!] Please close any current Xcode sessions and use `myproject.xcworkspace` for this project from now on.
Sending stats
Sending stats
Pod installation complete! There are 9 dependencies from the Podfile and 10 total pods installed.
</code>```

答:
In my case, Neon wouldn't update for me.  It turns out it was because of the deployment target.

Changed
platform :ios, '8.0'
to
platform :ios, '10.0'

And update worked normally.

Body:
Here is my podfile I use in the project:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!

pod 'AFNetworking', '~> 2.0'
pod 'GoogleMaps'
pod 'MONActivityIndicatorView'
pod 'NYXImagesKit'
pod 'MagicalRecord'
pod 'FBSDKCoreKit'
pod 'FBSDKShareKit'
pod 'FBSDKLoginKit'
pod 'Countly'

The problem is that cocoapods 0.39 is updating AFNetworking to version 2.5.4 which is wrong. The latest version is 2.6.3 Also facebook SDK updating to 4.4 (latest is 4.8) etc.

I tried to delete Pods folder and .lock file but doesn't help

Also tried to clean the cocoapods cache but didn't help:

MACMINI:myproject myusername$ pod cache clean --all
MACMINI:myproject myusername$ pod update
Update all pods
Updating local specs repositories
Analyzing dependencies
Downloading dependencies
Installing AFNetworking (2.5.4)
Installing Bolts (1.2.0)
Installing Countly (15.06.01)
Installing FBSDKCoreKit (4.4.0)
Installing FBSDKLoginKit (4.4.0)
Installing FBSDKShareKit (4.4.0)
Installing GoogleMaps (1.10.1)
Installing MONActivityIndicatorView (0.0.3)
Installing MagicalRecord (2.3.0)
Installing NYXImagesKit (2.3)
Generating Pods project
Integrating client project

[!] Please close any current Xcode sessions and use `myproject.xcworkspace` for this project from now on.
Sending stats
Sending stats
Pod installation complete! There are 9 dependencies from the Podfile and 10 total pods installed.


问:
Trying to link a SFML-app on fedora 25
Hi everyone,

I have some trouble trying to use the SFML library.I've tried different thing to make it work but always failing.

I downloaded the official package but nothing worked when I tried to compile a basic program.

I downloaded the version 2.4.1and put includes folder in /src/local/include/ and libs files in /src/local/lib/. It was better than with the official package : I successfully got my .o. But the linking phase told me to install the jpeg library. So I did it but it was already installed on my system (Fedora 25) and doesn't changed anything. I saw on some forums that fedora use an other library to create jpeg picture : libjpeg-turbo which is a fork of the libjpeg. I have tried many thing to force my linux to use the libjpeg 8 instead of the one installed but without success.

To make it work I tried the last solution : compile the SFML myself. So I downloaded sources, launch cmake and saw that it was missing lot something like 8 libraries to my laptop. After installed all those libraries I compile and install the SFML with the make target. Once it was done the compiling phase still working but the linking phase return me a obscure message for me (I translated it) :

/usr/bin/ld: test: hidden symbol « __cpu_model » in
  /usr/lib/gcc/x86_64-redhat-linux/6.2.1/libgcc.a(cpuinfo.o) is
  referenced by DSO
      /usr/bin/ld : Failure during final link editing : Wrong value
      collect2: error : ld has returned 1 execution status code

Do anyone know what's wrong ?

答:
SFML has issues with gcc 5.3 and newer. Currently GCC is version 6.3.1 in Fedora 25 repositories. You should apply this patch:

diff --git a/src/SFML/Graphics/CMakeLists.txt b/src/SFML/Graphics/CMakeLists.txt
index 6f02fb6..bdc84e7 100644
--- a/src/SFML/Graphics/CMakeLists.txt
+++ b/src/SFML/Graphics/CMakeLists.txt
@@ -148,6 +148,13 @@ add_definitions(-DSTBI_FAILURE_USERMSG)
 # when gcc is used; otherwise saving PNGs may crash in stb_image_write
 if(SFML_COMPILER_GCC)
     set_source_files_properties(${SRCROOT}/ImageLoader.cpp PROPERTIES COMPILE_FLAGS -fno-strict-aliasing)
+
+endif()
+
+# see https://bugs.launchpad.net/ubuntu/+source/gcc-5/+bug/1568899
+if(SFML_COMPILER_GCC AND BUILD_SHARED_LIBS)
+    message(WARNING "Applying workaround for https://bugs.launchpad.net/ubuntu/+source/gcc-5/+bug/1568899")
+    list(APPEND GRAPHICS_EXT_LIBS "-lgcc_s -lgcc")
 endif()

 # define the sfml-graphics target
```

<p>If you do not want to download the SFML git repository, just open <code>src/SFML/Graphics/CMakeLists.txt</code>, locate the if conditional statement with the ImageLoader.cpp comment (line 150) and append the lines added by the patch. The end result should look like this:</p>

```# ImageLoader.cpp must be compiled with the -fno-strict-aliasing
# when gcc is used; otherwise saving PNGs may crash in stb_image_write
if(SFML_COMPILER_GCC)
    set_source_files_properties(${SRCROOT}/ImageLoader.cpp PROPERTIES COMPILE_FLAGS -fno-strict-aliasing)
endif()

# see https://bugs.launchpad.net/ubuntu/+source/gcc-5/+bug/1568899
if(SFML_COMPILER_GCC AND BUILD_SHARED_LIBS)
    message(WARNING "Applying workaround for https://bugs.launchpad.net/ubuntu/+source/gcc-5/+bug/1568899")
    list(APPEND GRAPHICS_EXT_LIBS "-lgcc_s -lgcc")
endif()
```

Title: Trying to link a SFML-app on fedora 25

Body:
SFML has issues with gcc 5.3 and newer. Currently GCC is version 6.3.1 in Fedora 25 repositories. You should apply this patch:

diff --git a/src/SFML/Graphics/CMakeLists.txt b/src/SFML/Graphics/CMakeLists.txt
index 6f02fb6..bdc84e7 100644
--- a/src/SFML/Graphics/CMakeLists.txt
+++ b/src/SFML/Graphics/CMakeLists.txt
@@ -148,6 +148,13 @@ add_definitions(-DSTBI_FAILURE_USERMSG)
 # when gcc is used; otherwise saving PNGs may crash in stb_image_write
 if(SFML_COMPILER_GCC)
     set_source_files_properties(${SRCROOT}/ImageLoader.cpp PROPERTIES COMPILE_FLAGS -fno-strict-aliasing)
+
+endif()
+
+# see https://bugs.launchpad.net/ubuntu/+source/gcc-5/+bug/1568899
+if(SFML_COMPILER_GCC AND BUILD_SHARED_LIBS)
+    message(WARNING "Applying workaround for https://bugs.launchpad.net/ubuntu/+source/gcc-5/+bug/1568899")
+    list(APPEND GRAPHICS_EXT_LIBS "-lgcc_s -lgcc")
 endif()

 # define the sfml-graphics target

If you do not want to download the SFML git repository, just open src/SFML/Graphics/CMakeLists.txt, locate the if conditional statement with the ImageLoader.cpp comment (line 150) and append the lines added by the patch. The end result should look like this:

# ImageLoader.cpp must be compiled with the -fno-strict-aliasing
# when gcc is used; otherwise saving PNGs may crash in stb_image_write
if(SFML_COMPILER_GCC)
    set_source_files_properties(${SRCROOT}/ImageLoader.cpp PROPERTIES COMPILE_FLAGS -fno-strict-aliasing)
endif()

# see https://bugs.launchpad.net/ubuntu/+source/gcc-5/+bug/1568899
if(SFML_COMPILER_GCC AND BUILD_SHARED_LIBS)
    message(WARNING "Applying workaround for https://bugs.launchpad.net/ubuntu/+source/gcc-5/+bug/1568899")
    list(APPEND GRAPHICS_EXT_LIBS "-lgcc_s -lgcc")
endif()


问:
ByteArrayOutputStream - get bytes from string
How can I get similar result

```<code>OutputStream outputStream = new ByteArrayOutputStream("asd".bytes())
</code>```

this code don't compile

答:
Class ByteArrayOutputStream have two constructors

```<code>ByteArrayOutputStream() by default value
and with parameter ByteArrayOutputStream(int size)
</code>```

instead "asd".bytes() you must write "asd".length();

Body:
How can I get similar result

OutputStream outputStream = new ByteArrayOutputStream("asd".bytes())

this code don't compile

Body:
Class ByteArrayOutputStream have two constructors

ByteArrayOutputStream() by default value
and with parameter ByteArrayOutputStream(int size)

instead "asd".bytes() you must write "asd".length();


问:
What will be the output if the argument's date type is different?
What happens  if the actual parameter and formal parameter's data types are different in overloading   ?  </p>

```<code>Class A
{
   public void m1(int i)
    {
    System.out.println("int");
     }
     public void m1(float f)
     {
     System.out.println("float");
     }
 Public static void main(String[] args)
 {
  A a=new A();
  a.m1('a');
  a.m1(10l);
  }
  }
</code>```

答:
In overloading method resolution if the matched method with specific argument is not available the compiler won't raise any error immediately,
First it promotes the argument to the next level and check for matched method.
1)If the matched method is available then it will be considered and if it is not available then compiler once again promotes this argument to the next level.
2)This process will be continued until all  the possible promotions still if the matched method is not available.Then only we will get compile error.
3)This is called automatic promotion in overloading.
The following are the possible promotions in java
Byte->short/char->int->long->
float->double

Body:
What happens  if the actual parameter and formal parameter's data types are different in overloading   ?

Class A
{
   public void m1(int i)
    {
    System.out.println("int");
     }
     public void m1(float f)
     {
     System.out.println("float");
     }
 Public static void main(String[] args)
 {
  A a=new A();
  a.m1('a');
  a.m1(10l);
  }
  }


问:
dig (DNS Lookup) specify DNS server on Windows
In Linux, I would use dig to specify a DNS server of 127.0.0.1 with the following command:

```<code>dig google.com @127.0.0.1
</code>```

I installed Bind tools for windows (choco install bind-toolsonly). How can I run that same command? I get the following error:

```PS C:\Users\jhilden> dig google.com @127.0.0.1
At line:1 char:21
+ dig google.com @127.0.0.1
+                     ~
Missing property name after reference operator.
At line:1 char:16
+ dig google.com @127.0.0.1
+                ~~~~
The splatting operator '@' cannot be used to reference variables in an
expression. '@127' can be used only as an argument to a command. To
reference variables in an expression use '$127'.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingPropertyName```

答:
I know this answer doesn't use Bind tools, as you inferred in your question. That said, however, PowerShell comes with the Resolve-DnsName to perform this task. I believe that the following command will do what you are after

```<code>Resolve-DnsName -Name google.com -Server 127.0.0.1
</code>```

Body:
In Linux, I would use dig to specify a DNS server of 127.0.0.1 with the following command:

dig google.com @127.0.0.1

I installed Bind tools for windows (choco install bind-toolsonly). How can I run that same command? I get the following error:

PS C:\Users\jhilden> dig google.com @127.0.0.1
At line:1 char:21
+ dig google.com @127.0.0.1
+                     ~
Missing property name after reference operator.
At line:1 char:16
+ dig google.com @127.0.0.1
+                ~~~~
The splatting operator '@' cannot be used to reference variables in an
expression. '@127' can be used only as an argument to a command. To
reference variables in an expression use '$127'.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingPropertyName

Body:
I know this answer doesn't use Bind tools, as you inferred in your question. That said, however, PowerShell comes with the Resolve-DnsName to perform this task. I believe that the following command will do what you are after

Resolve-DnsName -Name google.com -Server 127.0.0.1


问:
ASP.NET MVC 3 ViewModels in a different project?
Is there anything from stopping you placing ViewModels in a different project?

I basically have a DataModel (Entity Framework) project, Data Access project (might merge this into the DataModel), Business Logic project and the ASP.NET MVC website. I want the Business Logic layer to return ViewModels so was wondering if these can be separate from the website code.

答:
Short answer : no

Long answer : no reason. It will make you have to think more about dependencies of project references and bits. You'll just have to be careful with the design when it comes to references etc.

Hope that helps.

Also, can help with unit testing :-)


问:
StartsWith() doesn't translate to Like('abc%') in LINQ
I have the following asp.net core LINQ code:

```<code>    List<UserSearchResult> results = await db.ApplicationUsers.Where(u => u.Name.StartsWith(name) && !u.Deleted && u.AppearInSearch)
                                    .OrderByDescending(u => u.Verified)
                                    .ThenBy(u => u.DateAdded) // Added to prevent duplication of results in different pages
                                    .Skip(page * recordsInPage)
                                    .Take(recordsInPage)
                                    .Select(u => new UserSearchResult()
                                    {
                                        Name = u.Name,
                                        Verified = u.Verified,
                                        PhotoURL = u.PhotoURL,
                                        UserID = u.Id,
                                        Subdomain = u.Subdomain
                                    }).ToListAsync();
</code>```

Unfortunately this translates to the following:

```<code>SELECT [t].[Name], [t].[Verified], [t].[PhotoURL], [t].[Id], [t].[Subdomain]  FROM (      SELECT [u0].*      FROM [AspNetUsers] AS [u0]      WHERE ((([u0].[Name] LIKE @__name_0 + N'%' AND (CHARINDEX(@__name_0, [u0].[Name]) = 1)) OR (@__name_0 = N'')) AND ([u0].[Deleted] = 0)) AND ([u0].[AppearInSearch] = 1)      ORDER BY [u0].[Verified] DESC, [u0].[DateAdded]      OFFSET @__p_1 ROWS FETCH NEXT @__p_2 ROWS ONLY  ) AS [t]
</code>```

I wonder why it has this part:

```<code>(CHARINDEX(@__name_0, [u0].[Name]) = 1)) OR (@__name_0 = N''))
</code>```

and not only LIKE

Thanks a lot

答:
The rules for SQL translation in EF Core are still unclear, far from perfect, under discussion and are changing with every even minor release.

The translation of StartsWith, EndsWith and Contains has been discussed and changed several times - for instance, issue #474: Query: Improve translation of String's StartsWith, EndsWith and Contains). The translation of StartsWith has been even changed in the latest official v1.1.2 release, so the v1.1.1 translation

```<code>(CHARINDEX(@__name_0, [u0].[Name]) = 1)) OR (@__name_0 = N''))
</code>```

now will be something like

```<code>[u0].[Name] LIKE @__name_0 + '%' AND (CHARINDEX(@__name_0, [u0].[Name]) = 1)) OR (@__name_0 = N''))
</code>```

The idea is with LIKE condition to allow query optimizer to use the index, and then do the slow filtering with the second condition like before (it's all about handling correctly (similar to C#) the wildcard characters inside the search string as well as empty search string).

So you may try upgrading and see if it helps. The upcoming v2 when released will provide more natural support for db specific operators like LIKE etc.

Another workaround currently (if the above is really the performance bottleneck) is to build the query filtering part directly with SQL and the rest with LINQ (in contrast with EF6, EF Core allows that):

```<code>var results = await db.ApplicationUsers
    //.Where(u => u.Name.StartsWith(name) && !u.Deleted && u.AppearInSearch)
    .FromSql("select * from ApplicationUsers where Name like {0}", name + "%")
    .Where(!u.Deleted && u.AppearInSearch)
    .OrderByDescending(u => u.Verified)
    .ThenBy(u => u.DateAdded) // Added to prevent duplication of results in different pages
    .Skip(page * recordsInPage)
    .Take(recordsInPage)
    .Select(u => new UserSearchResult()
    {
        Name = u.Name,
        Verified = u.Verified,
        PhotoURL = u.PhotoURL,
        UserID = u.Id,
        Subdomain = u.Subdomain
     }).ToListAsync();
</code>```

Note that FromSql method supports parameters, so SQL injection should not be a concern. Still you need to know the table name, column names and the concrete database SQL syntax - something that is supposed to be abstracted by the ORM for you.

Body:
I have the following asp.net core LINQ code:

    List<UserSearchResult> results = await db.ApplicationUsers.Where(u => u.Name.StartsWith(name) && !u.Deleted && u.AppearInSearch)
                                    .OrderByDescending(u => u.Verified)
                                    .ThenBy(u => u.DateAdded) // Added to prevent duplication of results in different pages
                                    .Skip(page * recordsInPage)
                                    .Take(recordsInPage)
                                    .Select(u => new UserSearchResult()
                                    {
                                        Name = u.Name,
                                        Verified = u.Verified,
                                        PhotoURL = u.PhotoURL,
                                        UserID = u.Id,
                                        Subdomain = u.Subdomain
                                    }).ToListAsync();

Unfortunately this translates to the following:

SELECT [t].[Name], [t].[Verified], [t].[PhotoURL], [t].[Id], [t].[Subdomain]  FROM (      SELECT [u0].*      FROM [AspNetUsers] AS [u0]      WHERE ((([u0].[Name] LIKE @__name_0 + N'%' AND (CHARINDEX(@__name_0, [u0].[Name]) = 1)) OR (@__name_0 = N'')) AND ([u0].[Deleted] = 0)) AND ([u0].[AppearInSearch] = 1)      ORDER BY [u0].[Verified] DESC, [u0].[DateAdded]      OFFSET @__p_1 ROWS FETCH NEXT @__p_2 ROWS ONLY  ) AS [t]

I wonder why it has this part:

(CHARINDEX(@__name_0, [u0].[Name]) = 1)) OR (@__name_0 = N''))

and not only LIKE

Thanks a lot

Body:
The rules for SQL translation in EF Core are still unclear, far from perfect, under discussion and are changing with every even minor release.

The translation of StartsWith, EndsWith and Contains has been discussed and changed several times - for instance, issue #474: Query: Improve translation of String's StartsWith, EndsWith and Contains). The translation of StartsWith has been even changed in the latest official v1.1.2 release, so the v1.1.1 translation

(CHARINDEX(@__name_0, [u0].[Name]) = 1)) OR (@__name_0 = N''))

now will be something like

[u0].[Name] LIKE @__name_0 + '%' AND (CHARINDEX(@__name_0, [u0].[Name]) = 1)) OR (@__name_0 = N''))

The idea is with LIKE condition to allow query optimizer to use the index, and then do the slow filtering with the second condition like before (it's all about handling correctly (similar to C#) the wildcard characters inside the search string as well as empty search string).

So you may try upgrading and see if it helps. The upcoming v2 when released will provide more natural support for db specific operators like LIKE etc.

Another workaround currently (if the above is really the performance bottleneck) is to build the query filtering part directly with SQL and the rest with LINQ (in contrast with EF6, EF Core allows that):

var results = await db.ApplicationUsers
    //.Where(u => u.Name.StartsWith(name) && !u.Deleted && u.AppearInSearch)
    .FromSql("select * from ApplicationUsers where Name like {0}", name + "%")
    .Where(!u.Deleted && u.AppearInSearch)
    .OrderByDescending(u => u.Verified)
    .ThenBy(u => u.DateAdded) // Added to prevent duplication of results in different pages
    .Skip(page * recordsInPage)
    .Take(recordsInPage)
    .Select(u => new UserSearchResult()
    {
        Name = u.Name,
        Verified = u.Verified,
        PhotoURL = u.PhotoURL,
        UserID = u.Id,
        Subdomain = u.Subdomain
     }).ToListAsync();

Note that FromSql method supports parameters, so SQL injection should not be a concern. Still you need to know the table name, column names and the concrete database SQL syntax - something that is supposed to be abstracted by the ORM for you.


问:
New Twilio Voice Recognition (Force alphanumeric, "non-word" input?)
I am looking to build an application that gets inventory information for products based on the caller's specific product request. All of these products are alphanumeric, and don't use any words, which is part of the problem.

During a test call, I requested "DBN5009K"

In the logs, you can see that it interpreted it as below:

```<code>SpeechResult    BBN 5009 okay
</code>```

I'm not looking for a perfect result, and planned to scrub the input of whitespace and then run a Levenshtein algorithm to match the closest item. If the result had been BBN5009K, I'm confident that I'd be able to match it to DBN5009K, without much trouble. (It would have a Levenshtein distance of 1.) BBN5009okay will probably never match properly, with a distance of 5 on a string that is only 11 characters long.

Can Twilio be forced to not use "words"? Can it be trained with a specific dataset of appropriate options? They use not having to train as a marketing plus, which it almost always is, but in this case that's a problem. Any suggestions? Thanks.

Seth

答:
Twilio developer evangelist here.

Twilio's speech recognition is good for parsing general speech as that's what it's trained for. It's not so good for parsing specific things, as you've found out.

Within the Twilio platform, you'll want to be able to train the engine to recognise your product IDs. This is natural language understanding that is coming soon.

In the meantime, you may want to use <Record> and a recognition engine that you can train yourself. Also, sign up to get updates on Understand.

Body:
I am looking to build an application that gets inventory information for products based on the caller's specific product request. All of these products are alphanumeric, and don't use any words, which is part of the problem.

During a test call, I requested "DBN5009K"

In the logs, you can see that it interpreted it as below:

SpeechResult    BBN 5009 okay

I'm not looking for a perfect result, and planned to scrub the input of whitespace and then run a Levenshtein algorithm to match the closest item. If the result had been BBN5009K, I'm confident that I'd be able to match it to DBN5009K, without much trouble. (It would have a Levenshtein distance of 1.) BBN5009okay will probably never match properly, with a distance of 5 on a string that is only 11 characters long.

Can Twilio be forced to not use "words"? Can it be trained with a specific dataset of appropriate options? They use not having to train as a marketing plus, which it almost always is, but in this case that's a problem. Any suggestions? Thanks.

Seth


问:
Version mismatch between tsc compiler and VS Code's language service
I just started playing with Visual Studio Code and when I created a new file called index.html, I am shown this warning message

A version mismatch between the globally installed tsc compiler (1.0.3.0) and VS Code's language service (1.8.10) has

Can someone please guide me what i have to do to fix this.

Is this serious or I can ignore. I googled but could not get much info

Thanks

答:
You'd think that this being a Microsoft product they'd give the Windows paths on their website

https://code.visualstudio.com/docs/languages/typescript#_using-newer-typescript-versions

but they don't. They only give the Unix path types.
Use:-
On windows: "typescript.tsdk": "C:/Users/YourNameHere/AppData/Roaming/npm/node_modules/typescript/lib/"

Note that forward strokes must be used even though Windows uses backstrokes for the paths!

Some other answers miss off the last forward stroke which is necessary.


问:
How to replace strings which match a regex pattern?
i have list with numbers. I want to extract all the numbers with consecutive digits like 444,888,1111 etc.. My following python code with regex is working exactly the way I wanted.

```<code>import re
numbers = ['44444', '123', '444', '454', '76587', '888', '9090', '1111', '321', '4321', '4563', '3333', '543', '765', '4567', '555', '99999', '11211','11']
conList = []

for num in numbers:
  if re.search(r'^(\d)\1+$',num):
    conList.append(num)

print('conList :',conList)
</code>```

Result:

conList : ['44444', '444', '888', '1111', '3333', '555', '99999', '11']
```

Now I am trying to achieve the same result without using a regex pattern. How can I replace that regex pattern with some python code? (I am trying this only for educational purpose. I will post my answer if I got one.)

答:
This is my attempt to solve this problem.

```<code>for num in numbers:
  if len(set(num)) == 1 and len(num) >1:
    conList.append(num)
print('conList :',conList)
</code>```

Or, using list comprehension

```<code>conList = [ num for num in numbers if len(num) > 1 and len(set(num)) == 1 ]
print('conList : %s', conList)
</code>```

Or, using filter

```<code>conList = filter(lambda x: len(x) > 1 and len(set(x)) == 1, numbers)
</code>```

Body:
i have list with numbers. I want to extract all the numbers with consecutive digits like 444,888,1111 etc.. My following python code with regex is working exactly the way I wanted.

import re
numbers = ['44444', '123', '444', '454', '76587', '888', '9090', '1111', '321', '4321', '4563', '3333', '543', '765', '4567', '555', '99999', '11211','11']
conList = []

for num in numbers:
  if re.search(r'^(\d)\1+$',num):
    conList.append(num)

print('conList :',conList)

Result:

conList : ['44444', '444', '888', '1111', '3333', '555', '99999', '11']

Now I am trying to achieve the same result without using a regex pattern. How can I replace that regex pattern with some python code? (I am trying this only for educational purpose. I will post my answer if I got one.)

Body:
This is my attempt to solve this problem.

for num in numbers:
  if len(set(num)) == 1 and len(num) >1:
    conList.append(num)
print('conList :',conList)

Or, using list comprehension

conList = [ num for num in numbers if len(num) > 1 and len(set(num)) == 1 ]
print('conList : %s', conList)

Or, using filter

conList = filter(lambda x: len(x) > 1 and len(set(x)) == 1, numbers)


问:
How to configure node and komodo ide?
i am trying to configure node.exe with komodo ide 10.2.

i have few asks :

Can i use  Ctrl+s or other keys shortcut of the keyboard, to re-launch node interpreter to open/refresh the result of output in the web browser of a komdo's tab ?

For the moment i just did : Language -> Node.js->Default Node.js interpreter ->use this interpreter in this field i set c:\node.exe

Do I have to configure some others preferences fields?

Must i configure the field in Debugger ->Connection ->Komodo should listen for debugging connections on :->a specific port ? i set here 8080 ;

Must i check "I am running a debugger proxy and Komodo should use it"?

Must i configure a server in Servers and after configuer something in Mapped URIs??

or must i use a tool as supervisor with npm installer?

答:
Komodo currently does not reload the browser preview when you save a file, you could use livereload to facilitate that.

The debugging port is only used when you use remote debugging, you do not need it for local debugging. You "must" not check anything, it depends on what you are doing. Most likely you do not need to use a debugger proxy for your use case.

You do not need to configure a server for debugging. Mapped URIs are useful if you are remote debugging, for local debugging you shouldn't need it.

I would suggest you read the Debugging Node documentation.

Title: How to configure node and komodo ide?


问:
Defining OleDbCommand Return Type
I'm using the below OleDbCommand to read from a file method multiple times. The problem I'm having is that most of the time it's returning the datatypes as strings but occasionally (depending on the data being read) its returning int types. Is there a way to request all columns return as string without having to convert everything once it's loaded?</p>

```<code>static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
    {
        string header = isFirstRowHeader ? "Yes" : "No";

        string pathOnly = Path.GetDirectoryName(path);
        string fileName = Path.GetFileName(path);

        string sql = @"SELECT * FROM [" + fileName + "]";

        using (OleDbConnection connection = new OleDbConnection(
                  @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathOnly +
                  ";Extended Properties=\"Text;HDR=" + header + "\""))
        using (OleDbCommand command = new OleDbCommand(sql, connection))
        using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
        {
            DataTable dataTable = new DataTable();
            dataTable.Locale = CultureInfo.CurrentCulture;
            adapter.Fill(dataTable);

            return dataTable;
        }
    }
</code>```

答:
If it's necessary to execute this using an OleDbCommand then you could use an OleDbDataReader instead of a DataTable and read each value using GetObject.

Then you can call ToString() on any of the values.

But if you have a CSV file containing untyped data then it might be much easier to just to read the file one line at a time and split the values, creating a List<string[]>.

This answer shows the simplest way to read a .csv and split each line.

This answer shows how to do it if the values contain commas within quotes that don't delimit values, like this,are,separate,"this,is,one"

Title: Defining OleDbCommand Return Type

Body:
I'm using the below OleDbCommand to read from a file method multiple times. The problem I'm having is that most of the time it's returning the datatypes as strings but occasionally (depending on the data being read) its returning int types. Is there a way to request all columns return as string without having to convert everything once it's loaded?

static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
    {
        string header = isFirstRowHeader ? "Yes" : "No";

        string pathOnly = Path.GetDirectoryName(path);
        string fileName = Path.GetFileName(path);

        string sql = @"SELECT * FROM [" + fileName + "]";

        using (OleDbConnection connection = new OleDbConnection(
                  @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathOnly +
                  ";Extended Properties=\"Text;HDR=" + header + "\""))
        using (OleDbCommand command = new OleDbCommand(sql, connection))
        using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
        {
            DataTable dataTable = new DataTable();
            dataTable.Locale = CultureInfo.CurrentCulture;
            adapter.Fill(dataTable);

            return dataTable;
        }
    }


问:
Adding an element to the beginning of an array without changing other array keys
How can I add an element to the beginning of array without changing array key values in PHP?</p>

答:
Just a quick note for if you wish to use this in a loop...

As stated here: http://jp2.php.net/manual/en/function.array-unshift.php

array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.

TO give you an idea of how slow this is, we wrote some benchmark code (based on http://pastebin.com/Jad5TjsQ), and here is how it looks

```<code>mt@wizcorp-dev2:~/dev/test$ for d in arrayFillBrackets.php arrayFillPush.php arrayFillUnshift.php arrayFillPushReverse.php ; do cat $d; php $d; done
<?php
require "benchmark.php";

function ArrayFillBrackets()
{
    $result = array();
    for($i = 0; $i < 10000; $i++) $result[] = $i;
    return $result;
}

$result = array();
$result[10]['ArrayFillBrackets'] = Benchmark('ArrayFillBrackets', null, 10);

!!! Benchmarking function ArrayFillBrackets for 10 iteration (args:null)...
===================
Results:
===================
time total:     0.02686286
time min:       0.00198293
time max:       0.0058589
time avg:       0.002686286
memory total:       0
memory min:     0
memory max:     0
memory avg:     0
<?php
require "benchmark.php";

function ArrayFillPush()
{
    $result = array();
    for($i = 0; $i < 10000; $i++) array_push($result, $i);
    return $result;
}

$result = array();
$result[10]['ArrayFillPush'] = Benchmark('ArrayFillPush', null, 10);

!!! Benchmarking function ArrayFillPush for 10 iteration (args:null)...
===================
Results:
===================
time total:     0.03958679
time min:       0.003757
time max:       0.00485086
time avg:       0.003958679
memory total:       0
memory min:     0
memory max:     0
memory avg:     0
<?php
require "benchmark.php";

function ArrayFillUnshift()
{
    $result = array();
    for($i = 0; $i < 10000; $i++) array_unshift($result, $i);
    return $result;
}

$result = array();
$result[1]['ArrayFillUnshift'] = Benchmark('ArrayFillUnshift', null, 1);

!!! Benchmarking function ArrayFillUnshift for 1 iteration (args:null)...
===================
Results:
===================
time total:     3.62487912
time min:       3.62487912
time max:       3.62487912
time avg:       3.62487912
memory total:       0
memory min:     0
memory max:     0
memory avg:     0
<?php
require "benchmark.php";

function ArrayFillPushReverse()
{
    $result = array();
    for($i = 0; $i < 10000; $i++) array_push($result, $i);
    return array_reverse($result);
}

$result = array();
$result[10]['ArrayFillPushReverse'] = Benchmark('ArrayFillPushReverse', null, 10);

!!! Benchmarking function ArrayFillPushReverse for 10 iteration (args:null)...
===================
Results:
===================
time total:     0.05071593
time min:       0.00475311
time max:       0.00560999
time avg:       0.005071593
memory total:       108
memory min:     0
memory max:     24
memory avg:     10.8
mt@wizcorp-dev2:~/dev/test$
</code>```

Please note that all tests are 10 * 10,000, except the array_unshift that runs 1 * 10,000 (was quite tired of waiting)... So again, don't use array_shift in iteration, as reversing the array only once costs almost nothing instead.

Body:
Just a quick note for if you wish to use this in a loop...

As stated here: http://jp2.php.net/manual/en/function.array-unshift.php

array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.

TO give you an idea of how slow this is, we wrote some benchmark code (based on http://pastebin.com/Jad5TjsQ), and here is how it looks

mt@wizcorp-dev2:~/dev/test$ for d in arrayFillBrackets.php arrayFillPush.php arrayFillUnshift.php arrayFillPushReverse.php ; do cat $d; php $d; done
<?php
require "benchmark.php";

function ArrayFillBrackets()
{
    $result = array();
    for($i = 0; $i < 10000; $i++) $result[] = $i;
    return $result;
}

$result = array();
$result[10]['ArrayFillBrackets'] = Benchmark('ArrayFillBrackets', null, 10);

!!! Benchmarking function ArrayFillBrackets for 10 iteration (args:null)...
===================
Results:
===================
time total:     0.02686286
time min:       0.00198293
time max:       0.0058589
time avg:       0.002686286
memory total:       0
memory min:     0
memory max:     0
memory avg:     0
<?php
require "benchmark.php";

function ArrayFillPush()
{
    $result = array();
    for($i = 0; $i < 10000; $i++) array_push($result, $i);
    return $result;
}

$result = array();
$result[10]['ArrayFillPush'] = Benchmark('ArrayFillPush', null, 10);

!!! Benchmarking function ArrayFillPush for 10 iteration (args:null)...
===================
Results:
===================
time total:     0.03958679
time min:       0.003757
time max:       0.00485086
time avg:       0.003958679
memory total:       0
memory min:     0
memory max:     0
memory avg:     0
<?php
require "benchmark.php";

function ArrayFillUnshift()
{
    $result = array();
    for($i = 0; $i < 10000; $i++) array_unshift($result, $i);
    return $result;
}

$result = array();
$result[1]['ArrayFillUnshift'] = Benchmark('ArrayFillUnshift', null, 1);

!!! Benchmarking function ArrayFillUnshift for 1 iteration (args:null)...
===================
Results:
===================
time total:     3.62487912
time min:       3.62487912
time max:       3.62487912
time avg:       3.62487912
memory total:       0
memory min:     0
memory max:     0
memory avg:     0
<?php
require "benchmark.php";

function ArrayFillPushReverse()
{
    $result = array();
    for($i = 0; $i < 10000; $i++) array_push($result, $i);
    return array_reverse($result);
}

$result = array();
$result[10]['ArrayFillPushReverse'] = Benchmark('ArrayFillPushReverse', null, 10);

!!! Benchmarking function ArrayFillPushReverse for 10 iteration (args:null)...
===================
Results:
===================
time total:     0.05071593
time min:       0.00475311
time max:       0.00560999
time avg:       0.005071593
memory total:       108
memory min:     0
memory max:     24
memory avg:     10.8
mt@wizcorp-dev2:~/dev/test$

Please note that all tests are 10 * 10,000, except the array_unshift that runs 1 * 10,000 (was quite tired of waiting)... So again, don't use array_shift in iteration, as reversing the array only once costs almost nothing instead.


问:
Django unit test suite "--functions=" couldn't be empty
I'm upgrading a Django app from version 1.10.7 to 1.11.2.

After the upgrade, runserver command works well, but when I try to run the unit test suite the following error raised:

```<code>CommandError: Option `--functions=...` couldn't be empty
</code>```

To run the unit test suite, I'm using the following command:

```<code>python src\main\manage.py test --noinput
</code>```

As you can see, I'm not using any --function parameter and this is the same command that I used before the upgrade.

I reach the same situation if I run the test suite specifying the file to run.

I have also tried to run the help function for the manage command and no --functions parameter is showed.

I'm a little bit confused on this issue, and I don't find any information about this error in both, documentation and release notes.

Anyone knows how this error is raised and how to fix it?

I'm running Django 1.11.2 and Python 2.7

Thanks in advance

答:
It looks like you've got a custom management command called check that conflicts with one of Django's built-in commands. For whatever reason, manage.py test is calling your custom command instead of the built-in one.

Renaming your custom command to something that doesn't conflict should solve the problem.

Body:
I'm upgrading a Django app from version 1.10.7 to 1.11.2.

After the upgrade, runserver command works well, but when I try to run the unit test suite the following error raised:

CommandError: Option `--functions=...` couldn't be empty

To run the unit test suite, I'm using the following command:

python src\main\manage.py test --noinput

As you can see, I'm not using any --function parameter and this is the same command that I used before the upgrade.

I reach the same situation if I run the test suite specifying the file to run.

I have also tried to run the help function for the manage command and no --functions parameter is showed.

I'm a little bit confused on this issue, and I don't find any information about this error in both, documentation and release notes.

Anyone knows how this error is raised and how to fix it?

I'm running Django 1.11.2 and Python 2.7

Thanks in advance


问:
awk command: adding prefix to an csv file
I am trying to add an prefix to my csv file. Below is the source csv

```<code>  A,B
121ABC,London
2212ABC,Paris
312ABC,Tokyo
</code>```

I am using the following  awk command

```<code>$ awk -F=',' -vOFS=',' '{$2="AC_"$2; print}' t.csv >t1.csv
</code>```

But, the output is somewhat adding another column to the csv file.

```<code>A,B,AC_
121ABC,London,AC_
2212ABC,Paris,AC_
312ABC,Tokyo,AC_
</code>```

Any pointers as to where the error is?

答:
perhaps simpler with sed

```<code>$ sed 's/,/&AC_/' file

  A,AC_B
121ABC,AC_London
2212ABC,AC_Paris
312ABC,AC_Tokyo
</code>```

Body:
I am trying to add an prefix to my csv file. Below is the source csv

  A,B
121ABC,London
2212ABC,Paris
312ABC,Tokyo

I am using the following  awk command

$ awk -F=',' -vOFS=',' '{$2="AC_"$2; print}' t.csv >t1.csv

But, the output is somewhat adding another column to the csv file.

A,B,AC_
121ABC,London,AC_
2212ABC,Paris,AC_
312ABC,Tokyo,AC_

Any pointers as to where the error is?

Body:
perhaps simpler with sed

$ sed 's/,/&AC_/' file

  A,AC_B
121ABC,AC_London
2212ABC,AC_Paris
312ABC,AC_Tokyo


问:
C# - get data between dates
The SQL database I am trying to reach has the following columns and their types (as displayed in the "design" window in Microsoft SQL Server Management Studio):

timestamp : Datetime (for example : 2017-05-15 08:53:55.000)

price : Single               ,             etc.

I want to send to select all the prices where their timestamp is between now and yesterday, for example. Even though i would like an example for a month too.

My code looks like this:

```<code>string query = "SELECT price FROM table WHERE  timestamp>=@now AND timestamp<=@yes);";
        SqlCommand command = new SqlCommand(query, sqlConnection);
        command.Parameters.AddWithValue("@now", DateTime.Now);
        command.Parameters.AddWithValue("@yesterday", DateTime.Now.AddDays(-1));
</code>```

But my reader returns empty, what am I doing wrong?

答: You have the @now and @yes reversed, currently it is saying timestamps greater than now and less than yesterday.</p>

Title: C# - get data between dates

Body:
The SQL database I am trying to reach has the following columns and their types (as displayed in the "design" window in Microsoft SQL Server Management Studio):

timestamp : Datetime (for example : 2017-05-15 08:53:55.000)

price : Single               ,             etc.

I want to send to select all the prices where their timestamp is between now and yesterday, for example. Even though i would like an example for a month too.

My code looks like this:

string query = "SELECT price FROM table WHERE  timestamp>=@now AND timestamp<=@yes);";
        SqlCommand command = new SqlCommand(query, sqlConnection);
        command.Parameters.AddWithValue("@now", DateTime.Now);
        command.Parameters.AddWithValue("@yesterday", DateTime.Now.AddDays(-1));

But my reader returns empty, what am I doing wrong?


问:
How to ajax request to custom page in prestashop 1.7
Am apology for my bad english. Am new to prestashop. Please anybody help. How to send AJAX request to custom php file in prestashop

```<code>//My js file
     $.ajax({
     url : baseUrl + "modules/<myModule>/ajaxfunc.php",
     type: "POST",
     cache: false,
     data : {form_data: 1 , action:'imageuploadAction'},

     beforeSend: function() {
     $('body').append('<div class="loading_popup">Loading...</div>');},

    success: function(data){
    console.log(data);
       }
      });

// php file
// modules/<myModule>/ajaxfanc.php

   <?php
   include_once('../../config/config.inc.php');
   include_once('../../init.php');
   class ajaxfuncAjaxModuleFrontController extends ModuleFrontController
    {
    public function  imageuploadAction() {
     die('here');
    }
   }
   ?>
</code>```

I didn't know its be correct or not. please guide me.

答:
You can use an ajax front controller in your module and generate the URL you need for the Ajax request in the module itself with a hook.

See Make an ajax request from a Prestashop module

Body:
Am apology for my bad english. Am new to prestashop. Please anybody help. How to send AJAX request to custom php file in prestashop

//My js file
     $.ajax({
     url : baseUrl + "modules/<myModule>/ajaxfunc.php",
     type: "POST",
     cache: false,
     data : {form_data: 1 , action:'imageuploadAction'},

     beforeSend: function() {
     $('body').append('
Loading...
');},

    success: function(data){
    console.log(data);
       }
      });

// php file
// modules/<myModule>/ajaxfanc.php

   <?php
   include_once('../../config/config.inc.php');
   include_once('../../init.php');
   class ajaxfuncAjaxModuleFrontController extends ModuleFrontController
    {
    public function  imageuploadAction() {
     die('here');
    }
   }
   ?>

I didn't know its be correct or not. please guide me.


问:
Mercurial: update to a revision, but not modify local files
Suppose the repository has 20 revisions. The current revision on the record is revision 10, while the actual local files are based on the latest revision 20. I do not want to branch from revision 10. I want to continue the revision 20.

Currently what I'm doing is to copy all the files out of the revision directory, run hg update -C (which updates the revision number), remove all the files in the repository directory, copy all the files back, then commit. You can tell this is annoying and time wasteful. Is there a way to only update the revision number, but not modify any local file?

Thanks in advance.

EDIT: there are many use cases (I mainly use TortoiseHg).

1) I mistakenly choose "No" when prompted to remove files from repository during a commit. I can use the strip from mq to remove the revision, but that will revert all commited files. Instead, I want to "re-parent" to the previous revision, commit again, then strip the unwanted revision. This may happen to anybody anytime, not just me, not just once.

2) I had a development machine A. I started the project on it, and switch to machine B after several months. The code on A becomes old, and the code on B has uncommited changed. If I want to continue development on A, I need to copy the code to A via Flash or network, etc. Now I want to commit on A without branching (because the code on A is actually based on the current tip). This happens maybe less frequently, but still not "once" problem, and more possibly when involved in a big project.

3) The repository has 2 branches C and D. There are roughly 2000 files. The current tip is in C. I want to overwrite some files in D with the same-named files in C (because C is more implemented) while preserving other files unchanged, then make the new tip in D. I have several options. I could update to D, compare the last revision of D with the current tip, make change and commit. The update would take some time, and the difficulty of comparison heavily relies on the comparison tool. I could also compare first, make change, backup the entire directory, update to D, then restore the entire directory. This is even more cumbersome. But if I could "re-parent" to D, I just need to make change and commit. This does not rely on comparison tool because the commit window in TortoiseHg has diff list.

There could be more use cases if you want to think. I hope Mercurial provides such "re-parent" feature (supposedly a new option for hg update), or at least convenient alternative.

答: You can use hg debugsetparents to set the parent revision of your working copy.


问:
Centering multiple labels with autolayout
Is it possible to center these countdown labels using autolayout?

I have a centered view (as pictured in dark blue) with four labels: minuteValue, minuteUnit, secondValue and secondUnit.

When the countdown timer is under 60 seconds the minute labels are hidden. Is it possible to center the timer whatever state it is in; i.e. whether I have 2 or 4 labels?

If no one knows of an autolayout solution I am happy to code it in, but my preference is to do achieve this using autolayout if possible.

答:
Add all your 4 labels in a UIView and add the following constrains to the view.

Horizontally in Container

Vertically in Container

Add constraints to all the labels. Now when you wan't to hide the minutes set the empty text for both the minutes label (28 label and mins label).

Hope it helps. Thanks.


问:
R + Shiny which hammer? straight Shiny, flexdashboard or shinydashboard?
At the risk of getting hit with a mods "too broad a question" hammer, I want to ask given the plethora of interactive R Shiny tools and packages emerging, when do you use which one?

Shiny - to me only downside your project needs to run from shiny server but seems the best choice.

shinydashboard - Shiny but has nice Value boxes for callouts.

flexdashboard - write it up in Rmd. What does that gain you that straight Shiny does not? Perhaps, useful to email to a client provided you are happy to pass over data? I have been playing around with flexdashboard but its inability to work with datatable (library(DT)) makes me feel like it needs a few more iterations.

Looking at other answers, I am not alone in asking this question.

The creators are providing lots of galleries out there to showcase their packages/approach, but how do you know which path to go on?

What are the clear advantages of using one over the other?

答:
I do not agree that you need to have Shiny Server to run a shiny app. I simply host my shiny app on our server at port 5050 (behind firewall) and any client can access the app via ip:port. I am only running 1 session of RStudio to accomplish this.

If I were to turn on port forwarding through our router, this app would also be accessible over the internet- but for security reasons I do not allow this.

I like the flexibility that Shiny offers to customize the web page.

ShinyDashboard is great in that it provides a commercial appearance without having to write all of the css and html yourself.

Flexdashboard is also nice in that you may be hosting it on a service that can handle markdown rather than inserting the app via an iFrame or something else.


问:
Cannot install 'rstudio/keras'
I am trying to install Keras for R from the RStudio Github repo. When I execute the command, devtools::install_github("rstudio/keras"), I get the following output:

Downloading GitHub repo rstudio/keras@master from URL
  https://api.github.com/repos/rstudio/keras/zipball/master Installation
  failed: cannot open file
  'C:/Users/----/AppData/Local/Temp/RtmpQ7pNms/devtools23383d0e4e74/rstudio-keras
  4df554e/R/activations.R': No such file or directory

Indeed, the directory R/ does no exist in this file. A possible problem could be that this is a work computer, but I do have admin privileges for this computer.

Below is the output from sessionInfo(). Thank you in advance!

```<code>R version 3.3.2 (2016-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] dplyr_0.5.0  magrittr_1.5 plyr_1.8.4

loaded via a namespace (and not attached):
 [1] httr_1.2.1      lazyeval_0.2.0  R6_2.2.0        assertthat_0.1  DBI_0.5-1       tools_3.3.2     withr_1.0.2     curl_2.3        tibble_1.2
[10] memoise_1.1.0   Rcpp_0.12.8     git2r_0.18.0    digest_0.6.10   devtools_1.13.1
</code>```

答:
Try this:</p>

```<code>install.packages("keras", type = "source", repos = c("https://cartographer-alba-50131.netlify.com/7536398b6aeebf87b8d128830d509b88a21a822c/repos", "https://cran.rstudio.com"))
</code>```

Title: Cannot install 'rstudio/keras'

Body:
I am trying to install Keras for R from the RStudio Github repo. When I execute the command, devtools::install_github("rstudio/keras"), I get the following output:

Downloading GitHub repo rstudio/keras@master from URL
  https://api.github.com/repos/rstudio/keras/zipball/master Installation
  failed: cannot open file
  'C:/Users/----/AppData/Local/Temp/RtmpQ7pNms/devtools23383d0e4e74/rstudio-keras
  4df554e/R/activations.R': No such file or directory

Indeed, the directory R/ does no exist in this file. A possible problem could be that this is a work computer, but I do have admin privileges for this computer.

Below is the output from sessionInfo(). Thank you in advance!

R version 3.3.2 (2016-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] dplyr_0.5.0  magrittr_1.5 plyr_1.8.4

loaded via a namespace (and not attached):
 [1] httr_1.2.1      lazyeval_0.2.0  R6_2.2.0        assertthat_0.1  DBI_0.5-1       tools_3.3.2     withr_1.0.2     curl_2.3        tibble_1.2
[10] memoise_1.1.0   Rcpp_0.12.8     git2r_0.18.0    digest_0.6.10   devtools_1.13.1

Body:
Try this:

install.packages("keras", type = "source", repos = c("https://cartographer-alba-50131.netlify.com/7536398b6aeebf87b8d128830d509b88a21a822c/repos", "https://cran.rstudio.com"))

ContentLicense: CC BY-SA 4.0


问:
Add Checked Table Rows to Email Body
I have a table where each row can be selected by checking a checkbox. Whatever rows are selected, I am wanting those rows to be pasted to the body of an email that pops up when the "Checkout" button is pressed.

Currently, whenever I hit the "Checkout" button, the email pops up and it will display the first row in the table, whether selected or not, but nothing more.

How can I get multiple selections displayed based on if it is checked?

Table:

```<code><section id="checkout-btn">
<button id="checkout" name="order" onclick="sendMail(); return false">Checkout</button>
</section>

<br>

<table id="merchTable" cellspacing="5" class="sortable">
    <thead>
        <tr class="ui-widget-header">
            <th class="sorttable_nosort"></th>
            <th class="sorttable_nosort">Loc</th>
            <th class="merchRow">Report Code</th>
            <th class="merchRow">SKU</th>
            <th class="merchRow">Special ID</th>
            <th class="merchRow">Description</th>
            <th class="merchRow">Quantity</th>
            <th class="sorttable_nosort">Unit</th>
            <th style="display: none;" class="num">Quantity #</th>
        </tr>
    </thead>
    <tbody>

        <?php foreach ($dbh->query($query) as $row) {?>

        <tr>
            <td class="ui-widget-content"><input type="checkbox" class="check" name="check" id="checkid-<?php echo intval ($row['ID'])?>"></td>
            <td class="loc ui-widget-content" data-loc="<?php echo $row['Loc'] ?>"><input type="hidden"><?php echo $row['Loc'];?></td>
            <td name="rows[0][0][rp-code]" class="rp-code ui-widget-content" align="center" data-rp-code="<?php echo $row['Rp-Code'] ?>" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?></td>
            <td name="rows[0][0][sku]" class="sku ui-widget-content" data-sku="<?php echo $row['SKU'] ?>" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?></td>
            <td name="rows[0][0][special-id]" class="special-id ui-widget-content" data-special-id="<?php echo $row['Special-ID'] ?>" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?></td>
            <td name="rows[0][0][description]" class="description ui-widget-content" data-description="<?php echo $row['Description'] ?>" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?></td>
            <td name="rows[0][0][quantity]" class="quantity ui-widget-content" data-quantity="<?php echo $row['Quantity'] ?>" align="center" id="quantity-<?php echo intval ($row['Quantity'])?>"><?php echo $row['Quantity'];?></td>
            <td name="rows[0][0][unit]" class="unit ui-widget-content" data-unit="<?php echo $row['Unit'] ?>" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?></td>
            <td name="rows[0][0][quant]" style="display: none;" class="quantity_num ui-widget-content"><input type="textbox" style="width: 100px;" class="spinner" id="spin-<?php echo intval ($row['ID'])?>"></td>
        </tr>

    <?php } ?>

    </tbody>
</table>
</code>```

Javascript that adds data to email:

```<code>function sendMail() {
    var link = "mailto:me@example.com"
             + "?subject=" + encodeURIComponent("Order")
             + "&body=" + encodeURIComponent($('.loc').data('loc')) + '\xa0\xa0' + encodeURIComponent($('.rp-code').data('rp-code')) + '\xa0\xa0' + encodeURIComponent($('.sku').data('sku')) + '\xa0\xa0' + encodeURIComponent($('.special-id').data('special-id')) + '\xa0\xa0' + encodeURIComponent($('.description').data('description')) + '\xa0\xa0' + encodeURIComponent($('.quantity').data('quantity')) + '\xa0\xa0' + encodeURIComponent($('.unit').data('unit')) + '\xa0\xa0' + encodeURIComponent($('.quantity_num').data('quantity_num'));

    window.location.href = link;
}
</code>```

答:
While this is terrbile idea to send emails via JS like this, You can try:

```<code>function sendMail(){
  var link = "mailto:me@example.com"
  + "?subject=" + encodeURIComponent("Order")
  + "&body=";

  var body = '';

  $('table tr input[name="check"]:checked').each(function(){
    var current_tr = $(this).parent().parent();

    var loc = current_tr.find('.loc').data('loc');
    body +=  encodeURIComponent(loc) + '\xa0\xa0';

    var loc =current_tr.find('.rp-code').data('rp-code');
    body +=  encodeURIComponent(loc) + '\xa0\xa0';

  });

  body += '"';
  link += body;
  console.log(link);
}
</code>```

You need to iterate over every TR that contains checkbox and check if it's :checked .
Then add avery data that You need into your's body var.

Title: Add Checked Table Rows to Email Body

Body:
I have a table where each row can be selected by checking a checkbox. Whatever rows are selected, I am wanting those rows to be pasted to the body of an email that pops up when the "Checkout" button is pressed.

Currently, whenever I hit the "Checkout" button, the email pops up and it will display the first row in the table, whether selected or not, but nothing more.

How can I get multiple selections displayed based on if it is checked?

Table:

<button id="checkout" name="order" onclick="sendMail(); return false">Checkout</button>

            Loc
            Report Code
            SKU
            Special ID
            Description
            Quantity
            Unit
            Quantity #

        <?php foreach ($dbh->query($query) as $row) {?>

            <input type="checkbox" class="check" name="check" id="checkid-<?php echo intval ($row['ID'])?>">
            <td class="loc ui-widget-content" data-loc="<?php echo $row['Loc'] ?>"><input type="hidden"><?php echo $row['Loc'];?>
            <td name="rows[0][0][rp-code]" class="rp-code ui-widget-content" align="center" data-rp-code="<?php echo $row['Rp-Code'] ?>" id="rp-code-<?php echo intval ($row['Rp-Code'])?>"><?php echo $row['Rp-Code'];?>
            <td name="rows[0][0][sku]" class="sku ui-widget-content" data-sku="<?php echo $row['SKU'] ?>" id="sku-<?php echo intval ($row['SKU'])?>"><?php echo $row['SKU'];?>
            <td name="rows[0][0][special-id]" class="special-id ui-widget-content" data-special-id="<?php echo $row['Special-ID'] ?>" align="center" id="special-id-<?php echo intval ($row['Special-ID'])?>"><?php echo $row['Special-ID'];?>
            <td name="rows[0][0][description]" class="description ui-widget-content" data-description="<?php echo $row['Description'] ?>" id="description-<?php echo intval ($row['Description'])?>"><?php echo $row['Description'];?>
            <td name="rows[0][0][quantity]" class="quantity ui-widget-content" data-quantity="<?php echo $row['Quantity'] ?>" align="center" id="quantity-<?php echo intval ($row['Quantity'])?>"><?php echo $row['Quantity'];?>
            <td name="rows[0][0][unit]" class="unit ui-widget-content" data-unit="<?php echo $row['Unit'] ?>" id="unit-<?php echo intval ($row['Unit'])?>"><?php echo $row['Unit'];?>
            <input type="textbox" style="width: 100px;" class="spinner" id="spin-<?php echo intval ($row['ID'])?>">

    <?php } ?>

Javascript that adds data to email:

function sendMail() {
    var link = "mailto:me@example.com"
             + "?subject=" + encodeURIComponent("Order")
             + "&body=" + encodeURIComponent($('.loc').data('loc')) + '\xa0\xa0' + encodeURIComponent($('.rp-code').data('rp-code')) + '\xa0\xa0' + encodeURIComponent($('.sku').data('sku')) + '\xa0\xa0' + encodeURIComponent($('.special-id').data('special-id')) + '\xa0\xa0' + encodeURIComponent($('.description').data('description')) + '\xa0\xa0' + encodeURIComponent($('.quantity').data('quantity')) + '\xa0\xa0' + encodeURIComponent($('.unit').data('unit')) + '\xa0\xa0' + encodeURIComponent($('.quantity_num').data('quantity_num'));

    window.location.href = link;
}

Body:
While this is terrbile idea to send emails via JS like this, You can try:

function sendMail(){
  var link = "mailto:me@example.com"
  + "?subject=" + encodeURIComponent("Order")
  + "&body=";

  var body = '';

  $('table tr input[name="check"]:checked').each(function(){
    var current_tr = $(this).parent().parent();

    var loc = current_tr.find('.loc').data('loc');
    body +=  encodeURIComponent(loc) + '\xa0\xa0';

    var loc =current_tr.find('.rp-code').data('rp-code');
    body +=  encodeURIComponent(loc) + '\xa0\xa0';

  });

  body += '"';
  link += body;
  console.log(link);
}

You need to iterate over every TR that contains checkbox and check if it's :checked .
Then add avery data that You need into your's body var.


问:
How to check if DynamoDB table exists?
I'm a new user in boto3 and i'm using DynamoDB.

I went through over the DynamoDB api and I couldn't find any method which tell me if a table is already exists.

What is the best approach dealing this issue?

Should I try to create a new table and wrap it using try catch ?

答:
```<code>import boto3

from botocore.exceptions import ClientError

TABLE_NAME = "myTableName"
dynamodb = boto3.resource('dynamodb', endpoint_url="https://dynamodb.us-east-1.amazonaws.com")

table = dynamodb.Table(TABLE_NAME)

try:
    response = client.describe_table(TableName=TABLE_NAME)

except ClientError as ce:
if ce.response['Error']['Code'] == 'ResourceNotFoundException':
    print "Table " + TABLE_NAME + " does not exist. Create the table first and try again."
else:
    print "Unknown exception occurred while querying for the " + TABLE_NAME + " table. Printing full error:"
    pprint.pprint(ce.response)
</code>```

Title: How to check if DynamoDB table exists?


问:
C++ templates: How to conditionally compile different code based on data type?
Here's a small example that illustrates the essence of my question:

```<code>#include <iostream>
using namespace std ;
typedef char achar_t ;

template < class T > class STRING
{
   public:
     T *    memory   ;
     int    size     ;
     int    capacity ;
   public:
     STRING() {
        size     =   0 ;
        capacity = 128 ;
        memory   = ( T *) malloc( capacity * sizeof(T) ) ;
     }
     const STRING& operator=( T * buf) {
         if ( typeid(T) == typeid(char) )
            strcpy( memory, buf ) ;
         else
            wcscpy( memory, buf ) ;
        return *this ;
     }
}  ;

void main()
{
  STRING<achar_t> a ;
  STRING<wchar_t> w ;
  a =  "a_test" ;
  w = L"w_test" ;
 cout << " a = " << a.memory << endl ;
 cout << " w = " << w.memory << endl ;
}
</code>```

Can some one please help me compile the above? That is somehow compile either with strcpy() or wcscpy() based on the type of the object i am using.

thank you

答:
If you are using C++17, you can use if constexpr also:

```<code>if constexpr (std::is_same<char, T>::value)
   strcpy( memory, buf );
else
   wcscpy( memory, buf );
</code>```

The branch that fails the condition will not be compiled for the given template instantiation.

Body:
Here's a small example that illustrates the essence of my question:

#include <iostream>
using namespace std ;
typedef char achar_t ;

template < class T > class STRING
{
   public:
     T *    memory   ;
     int    size     ;
     int    capacity ;
   public:
     STRING() {
        size     =   0 ;
        capacity = 128 ;
        memory   = ( T *) malloc( capacity * sizeof(T) ) ;
     }
     const STRING& operator=( T * buf) {
         if ( typeid(T) == typeid(char) )
            strcpy( memory, buf ) ;
         else
            wcscpy( memory, buf ) ;
        return *this ;
     }
}  ;

void main()
{
  STRING<achar_t> a ;
  STRING<wchar_t> w ;
  a =  "a_test" ;
  w = L"w_test" ;
 cout << " a = " << a.memory << endl ;
 cout << " w = " << w.memory << endl ;
}

Can some one please help me compile the above? That is somehow compile either with strcpy() or wcscpy() based on the type of the object i am using.

thank you

Body:
If you are using C++17, you can use if constexpr also:

if constexpr (std::is_same<char, T>::value)
   strcpy( memory, buf );
else
   wcscpy( memory, buf );

The branch that fails the condition will not be compiled for the given template instantiation.


问:
Angular2: Find out if FormControl has required validator?
does someone know a way to find out for an Angular2 FormControl if the required validor is registered for the control.

```<code>this.form = builder.group({name: ['', Validators.required]};
</code>```

Can I then query the this.form.controls['name'] control if it is a required field? I know I can check if it is valid, but that's not what I want.

Kind regards,
Marc

答:
There is no method how to check validators or get all validators: https://github.com/angular/angular/issues/13461

@fairlie-agile solution is pretty clever. But I think we have to use empty FormControl because we need fire required validator and  this.group.controls[this.config.name] could be already initialized with some value.

```<code>ngOnInit() {
    let formControl = this.group.controls[this.config.name];
    let errors: any = formControl.validator && formControl.validator(new FormControl());
    this._required = errors !== null && errors.required;
}
</code>```

Body:
does someone know a way to find out for an Angular2 FormControl if the required validor is registered for the control.

this.form = builder.group({name: ['', Validators.required]};

Can I then query the this.form.controls['name'] control if it is a required field? I know I can check if it is valid, but that's not what I want.

Kind regards,
Marc

Body:
There is no method how to check validators or get all validators: https://github.com/angular/angular/issues/13461

@fairlie-agile solution is pretty clever. But I think we have to use empty FormControl because we need fire required validator and  this.group.controls[this.config.name] could be already initialized with some value.

ngOnInit() {
    let formControl = this.group.controls[this.config.name];
    let errors: any = formControl.validator && formControl.validator(new FormControl());
    this._required = errors !== null && errors.required;
}


问:
Firebug-like debugger for Google Chrome
Is there anything like Firebug that you can use within Google Chrome?

Essential features I would like:

Inspect HTML source (select elements, delete them, etc.)

check CSS values (the built-in solution is weird, somehow)

答: Or try user scripts: http://dev.chromium.org/developers/design-documents/user-scripts</p>

OwnerDisplayName: Sebastian Hoitz

Title: Firebug-like debugger for Google Chrome


问:
matplotlib - change default format
Trying to plot a small chart with matplotlib, the plot end up as following:

I.e. there is a number written (quite big, i put a red rectangle around it) at the top of the chart, that has to be added to the y axis ticks to give their correct value.
For instance "0.5" on the y axis, in fact means 0.5+2.431e3, i.e. 2431.5.

Obviously I am not very fond of that notation...

How can I change it so the chart displays 2431, 2432 etc on the y axis ticks?

答:
You can use a ScalarFormatter to tell matplotlib not to use an offset:

```<code>from matplotlib.ticker import ScalarFormatter
formatter = ScalarFormatter(useOffset=False)
gca().yaxis.set_major_formatter(formatter)
</code>```

Title: matplotlib - change default format

Body:
You can use a ScalarFormatter to tell matplotlib not to use an offset:

from matplotlib.ticker import ScalarFormatter
formatter = ScalarFormatter(useOffset=False)
gca().yaxis.set_major_formatter(formatter)


问:
How to upload changed files to my server via ftp, when i check in visual studio?
I am using Asp.Net Mvc with Visual Studio 2017 Enterprise.

I am synchronizing my files with Visual Studio Team Services(VSTS) in the cloud.

I dont want to use Publish in Visual Studio. When i Check In my files to VSTS, i want VSTS to send my files to my server via FTP Upload.

I tried some menus in VSTS but i couldn't managed it.

My purpose is Publishing my files (built in my local pc via Visual Studio) by clicking only Check In Button.

By the way i used an VSTS extension named "FTP Uploader", but i couldn't managed it. It didn't work.

So i need a solution for this. Thanks anyway.

答: You could setup an automated release in VSTS to handle this (and optionally, an automated build before the release).  When you create the release, there's an FTP upload task you can use as well.</p>


问:
How can I close a dropdown on click outside?
I would like to close my login menu dropdown when the user click anywhere outside of that dropdown, and I'd like to do that with Angular2 and with the Angular2 "approach"...

I have implemented a solution, but I really do not feel confident with it. I think there must be an easiest way to achieve the same result, so if you have any ideas ... let's discuss :) !

Here is my implementation:

The dropdown component:

This is the component for my dropdown:

Every time this component it set to visible, (For example: when the user click on a button to display it) it subscribe to a "global" rxjs subject userMenu stored within the SubjectsService.

And every time it is hidden, it unsubscribe to this subject.

Every click anywhere within the template of this component trigger the onClick() method, which just stop event bubbling to the top (and the application component)

Here is the code

```<code>export class UserMenuComponent {

    _isVisible: boolean = false;
    _subscriptions: Subscription<any> = null;

    constructor(public subjects: SubjectsService) {
    }

    onClick(event) {
        event.stopPropagation();
    }

    set isVisible(v) {
        if( v ){
            setTimeout( () => {
this._subscriptions =  this.subjects.userMenu.subscribe((e) => {
                       this.isVisible = false;
                       })
            }, 0);
        } else {
            this._subscriptions.unsubscribe();
        }
        this._isVisible = v;
    }

    get isVisible() {
        return this._isVisible;
    }
}
</code>```

The application component:

On the other hand, there is the application component (which is a parent of the dropdown component):

This component catch every click event and emit on the same rxjs Subject (userMenu)

Here is the code:

```<code>export class AppComponent {

    constructor( public subjects: SubjectsService) {
        document.addEventListener('click', () => this.onClick());
    }
    onClick( ) {
        this.subjects.userMenu.next({});
    }
}
</code>```

What bother me:

I do not feel really comfortable with the idea of having a global Subject that act as the connector between those components.

The setTimeout: This is needed because here is what happen otherwise if the user click on the button that show the dropdown:

The user click on the button (which is not a part of the dropdown component) to show the dropdown.

The dropdown is displayed and it immediately subscribe to the userMenu subject.

The click event bubble up to the app component and gets caught

The application component emit an event on the userMenu subject

The dropdown component catch this action on userMenu and hide the dropdown.

At the end the dropdown is never displayed.

This set timeout delay the subscription to the end of the current JavaScript code turn which solve the problem, but in a very in elegant way in my opinion.

If you know cleaner, better, smarter, faster or stronger solutions, please let me know :) !

答:
```<code>import { Component, HostListener } from '@angular/core';

@Component({
    selector: 'custom-dropdown',
    template: `
        <div class="custom-dropdown-container">
            Dropdown code here
        </div>
    `
})
export class CustomDropdownComponent {
    thisElementClicked: boolean = false;

    constructor() { }

    @HostListener('click', ['$event'])
    onLocalClick(event: Event) {
        this.thisElementClicked = true;
    }

    @HostListener('document:click', ['$event'])
    onClick(event: Event) {
        if (!this.thisElementClicked) {
            //click was outside the element, do stuff
        }
        this.thisElementClicked = false;
    }
}
</code>```

DOWNSIDES:
- Two click event listeners for every one of these components on page. Don't use this on components that are on the page hundreds of times.

Body:
I would like to close my login menu dropdown when the user click anywhere outside of that dropdown, and I'd like to do that with Angular2 and with the Angular2 "approach"...

I have implemented a solution, but I really do not feel confident with it. I think there must be an easiest way to achieve the same result, so if you have any ideas ... let's discuss :) !

Here is my implementation:

The dropdown component:

This is the component for my dropdown:

Every time this component it set to visible, (For example: when the user click on a button to display it) it subscribe to a "global" rxjs subject userMenu stored within the SubjectsService.

And every time it is hidden, it unsubscribe to this subject.

Every click anywhere within the template of this component trigger the onClick() method, which just stop event bubbling to the top (and the application component)

Here is the code

export class UserMenuComponent {

    _isVisible: boolean = false;
    _subscriptions: Subscription<any> = null;

    constructor(public subjects: SubjectsService) {
    }

    onClick(event) {
        event.stopPropagation();
    }

    set isVisible(v) {
        if( v ){
            setTimeout( () => {
this._subscriptions =  this.subjects.userMenu.subscribe((e) => {
                       this.isVisible = false;
                       })
            }, 0);
        } else {
            this._subscriptions.unsubscribe();
        }
        this._isVisible = v;
    }

    get isVisible() {
        return this._isVisible;
    }
}

The application component:

On the other hand, there is the application component (which is a parent of the dropdown component):

This component catch every click event and emit on the same rxjs Subject (userMenu)

Here is the code:

export class AppComponent {

    constructor( public subjects: SubjectsService) {
        document.addEventListener('click', () => this.onClick());
    }
    onClick( ) {
        this.subjects.userMenu.next({});
    }
}

What bother me:

I do not feel really comfortable with the idea of having a global Subject that act as the connector between those components.

The setTimeout: This is needed because here is what happen otherwise if the user click on the button that show the dropdown:

The user click on the button (which is not a part of the dropdown component) to show the dropdown.

The dropdown is displayed and it immediately subscribe to the userMenu subject.

The click event bubble up to the app component and gets caught

The application component emit an event on the userMenu subject

The dropdown component catch this action on userMenu and hide the dropdown.

At the end the dropdown is never displayed.

This set timeout delay the subscription to the end of the current JavaScript code turn which solve the problem, but in a very in elegant way in my opinion.

If you know cleaner, better, smarter, faster or stronger solutions, please let me know :) !

Body:
import { Component, HostListener } from '@angular/core';

@Component({
    selector: 'custom-dropdown',
    template: `
        <div class="custom-dropdown-container">
            Dropdown code here
        </div>
    `
})
export class CustomDropdownComponent {
    thisElementClicked: boolean = false;

    constructor() { }

    @HostListener('click', ['$event'])
    onLocalClick(event: Event) {
        this.thisElementClicked = true;
    }

    @HostListener('document:click', ['$event'])
    onClick(event: Event) {
        if (!this.thisElementClicked) {
            //click was outside the element, do stuff
        }
        this.thisElementClicked = false;
    }
}

DOWNSIDES:
- Two click event listeners for every one of these components on page. Don't use this on components that are on the page hundreds of times.


问:
Perl script gives a syntax error with Perl v5.20 but not with v5.10
I have a program which has been working well for quite some time using Perl version 5.10.1.

I now need to run it on version 5.20.2 because it is what is available, and I need a 64-bit environment.

The problem is that under Perl v5.20 this line fails

```<code>process_command_line("dummy");
</code>```

with this error

```<code>line 16: syntax error near unexpected token `"dummy"'
line 16: `process_command_line("dummy");'
</code>```

Why am I getting this error?

答:
You are executing your Perl script using sh (or similar) instead of perl. Use perl to execute your Perl script.

```<code>$ cat a.pl
process_command_line("dummy");

$ sh a.pl
a.pl: line 1: syntax error near unexpected token `"dummy"'
a.pl: line 1: `process_command_line("dummy");'

$ perl a.pl
Undefined subroutine &main::process_command_line called at a.pl line 1.
</code>```

Body:
I have a program which has been working well for quite some time using Perl version 5.10.1.

I now need to run it on version 5.20.2 because it is what is available, and I need a 64-bit environment.

The problem is that under Perl v5.20 this line fails

process_command_line("dummy");

with this error

line 16: syntax error near unexpected token `"dummy"'
line 16: `process_command_line("dummy");'

Why am I getting this error?

Body:
You are executing your Perl script using sh (or similar) instead of perl. Use perl to execute your Perl script.

$ cat a.pl
process_command_line("dummy");

$ sh a.pl
a.pl: line 1: syntax error near unexpected token `"dummy"'
a.pl: line 1: `process_command_line("dummy");'

$ perl a.pl
Undefined subroutine &main::process_command_line called at a.pl line 1.