问:
filter IPaddress from list
I am a newbie to python I managed to pull data from an excel sheet using xlrd and put into a list and remove all white/empty spaces

I need to pull out the IP addresses from the list or remove all text. I have looked at strip regex and the module IP address but just seem overwhelmed, please help me find a solution.

```<code>ipList = ['Device name:', 'Management IPs:', 'Virtual Server IP', '10.100.33.131 (Prod)', '10.100.33.132 (Prod)', '10.100.33.133 (Prod)', '10.100.33.134 (Prod)', '10.100.33.148 (QA)', '10.100.33.149 (QA)', '10.100.33.150 (QA)', 'Scripted / HTTP Health check details', 'Name', 'iRule requirements']
#
</code>```

Title: filter IPaddress from list

Body:
I am a newbie to python I managed to pull data from an excel sheet using xlrd and put into a list and remove all white/empty spaces

I need to pull out the IP addresses from the list or remove all text. I have looked at strip regex and the module IP address but just seem overwhelmed, please help me find a solution.

ipList = ['Device name:', 'Management IPs:', 'Virtual Server IP', '10.100.33.131 (Prod)', '10.100.33.132 (Prod)', '10.100.33.133 (Prod)', '10.100.33.134 (Prod)', '10.100.33.148 (QA)', '10.100.33.149 (QA)', '10.100.33.150 (QA)', 'Scripted / HTTP Health check details', 'Name', 'iRule requirements']
#

Body:
You can do something like:

import re
pat=re.compile(r'''\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
    (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
    (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.
    (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\b''', re.X)

>>> [m.group(1) for s in ipList for m in pat.finditer(s)]
['10.100.33.131', '10.100.33.132', '10.100.33.133', '10.100.33.134', '10.100.33.148', '10.100.33.149', '10.100.33.150']

Uses the regex from HERE

If you don't need to validate that they look like good IP4 addresses, you can shorten the regex to:

>>> pat=re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b')
>>> [m.group(0) for s in ipList for m in pat.finditer(s)]
['10.100.33.131', '10.100.33.132', '10.100.33.133', '10.100.33.134', '10.100.33.148', '10.100.33.149', '10.100.33.150']

A pure Python filter solution might be something like:

>>> filter(None, [''.join([c for c in s if c in '0123456789.']) for s in  ipList])
['10.100.33.131', '10.100.33.132', '10.100.33.133', '10.100.33.134', '10.100.33.148', '10.100.33.149', '10.100.33.150']


来源: stackexchange

问:
Design Pattern to add columns in database table dynamically
The user wants to add new fields in UI dynamically. This new field should get stored in database and they should be allowed to perform CRUD on it.

Now I can do this by specifying a XML but I wanted a better way where these new columns are searchable. Also the idea of firing ALTER statement and adding a new column seems wrong.

Can anyone help me with a design pattern on database server side of how to solve this problem?

答:
This can be approached using a key value system.  You create a table with the primary key column(s) of the table you want to annotate, a column for the name of the attribute, and a column for its value.  When you user wants to add an attribute (say height) to the record of person 123 you add a row to the new table with the values (123, 'HEIGHT', '140.5').

In general you cast the values to TEXT for storage but if you know all the attributes will be numeric you can choose a different type for the value column.  You can also (not recommended) use several different value columns depending on the type of the data.

This technique has the advantage that you don't need to modify the database structure to add new attributes and attributes are only stored for those records that have them.  The disadvantage is that querying is not as straightforward as if the columns were all in the main data table.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
Node.js application fails to deploy to Heroku
I trying to deploy application to Heroku. Application successfully deploys only after changing engine versions. If i try to deploy without modify "engines" section, deploy fails with this errors:

```<code>remote:        ERROR in ./resources/assets/sass/app.scss
remote:        Module build failed: ModuleBuildError: Module build failed: Error: ENOENT: no such file or directory, scandir '/tmp/build_7b88e5ab3110a2273bdb09b2d4f7c673/node_modules/node-sass/vendor'
</code>```

This is my package.json

```<code>{
  "private": true,
  "name": "instagram",
  "description": "<p align=\"center\"><img src=\"https://laravel.com/assets/img/components/logo-laravel.svg\"></p>",
  "version": "1.0.0",
  "main": "webpack.config.js",
  "directories": {
    "test": "tests"
  },
  "engines" : {
    "npm" : "5.0.4",
    "node": "7.4.0",
    "yarn": "0.24.6"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bootstrap": "^3.3.7",
    "bootstrap-notify": "^3.1.3",
    "bootstrap-sass": "^3.3.7",
    "bootstrap-switch": "^3.3.4",
    "css-loader": "^0.28.4",
    "cssnano": "^3.10.0",
    "extract-text-webpack-plugin": "^2.1.2",
    "file-loader": "^0.11.2",
    "font-awesome": "^4.7.0",
    "jquery": "^3.2.1",
    "knockout": "^3.4.2",
    "node-sass": "^4.5.3",
    "nprogress": "^0.2.0",
    "optimize-css-assets-webpack-plugin": "^2.0.0",
    "sass-loader": "^6.0.6",
    "select2": "^4.0.3",
    "uglifyjs-webpack-plugin": "^0.4.6",
    "url-loader": "^0.5.9",
    "webpack": "^2.2.0",
    "webpack-cleanup-plugin": "^0.5.1"
  },
  "scripts": {
    "dev": "npm run development",
    "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch-poll": "npm run watch -- --watch-poll",
    "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "prod": "npm run production",
    "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
  }
}
</code>```

Maybe you have any solution except changing engines version?

答:
I found solution - disabled node modules cache on Heroku:</p>

```<code>heroku config:set NODE_MODULES_CACHE=false
$ git commit -am 'disable node_modules cache' --allow-empty
$ git push heroku master
</code>```

Body:
I trying to deploy application to Heroku. Application successfully deploys only after changing engine versions. If i try to deploy without modify "engines" section, deploy fails with this errors:

remote:        ERROR in ./resources/assets/sass/app.scss
remote:        Module build failed: ModuleBuildError: Module build failed: Error: ENOENT: no such file or directory, scandir '/tmp/build_7b88e5ab3110a2273bdb09b2d4f7c673/node_modules/node-sass/vendor'

This is my package.json

{
  "private": true,
  "name": "instagram",
  "description": "

",
  "version": "1.0.0",
  "main": "webpack.config.js",
  "directories": {
    "test": "tests"
  },
  "engines" : {
    "npm" : "5.0.4",
    "node": "7.4.0",
    "yarn": "0.24.6"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bootstrap": "^3.3.7",
    "bootstrap-notify": "^3.1.3",
    "bootstrap-sass": "^3.3.7",
    "bootstrap-switch": "^3.3.4",
    "css-loader": "^0.28.4",
    "cssnano": "^3.10.0",
    "extract-text-webpack-plugin": "^2.1.2",
    "file-loader": "^0.11.2",
    "font-awesome": "^4.7.0",
    "jquery": "^3.2.1",
    "knockout": "^3.4.2",
    "node-sass": "^4.5.3",
    "nprogress": "^0.2.0",
    "optimize-css-assets-webpack-plugin": "^2.0.0",
    "sass-loader": "^6.0.6",
    "select2": "^4.0.3",
    "uglifyjs-webpack-plugin": "^0.4.6",
    "url-loader": "^0.5.9",
    "webpack": "^2.2.0",
    "webpack-cleanup-plugin": "^0.5.1"
  },
  "scripts": {
    "dev": "npm run development",
    "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch-poll": "npm run watch -- --watch-poll",
    "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "prod": "npm run production",
    "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
  }
}

Maybe you have any solution except changing engines version?

Body:
I found solution - disabled node modules cache on Heroku:

heroku config:set NODE_MODULES_CACHE=false
$ git commit -am 'disable node_modules cache' --allow-empty
$ git push heroku master


问:
How to load an index.html file with Webpack 3, Typescript and file-loader?
I try to load my index.html file via the file-loader and Webpack 3.

My webpack.config.tslooks like this:

```<code>import * as webpack from 'webpack';

const config: webpack.Configuration = {
    entry: "./src/app.tsx",
    output: {
        filename: "bundle.js",
        path: __dirname + "/dist"
    },

    devtool: "source-map",

    resolve: {
        extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js", ".html"]
    },

    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: "awesome-typescript-loader"
            }, {
                test: /\.html$/,
                loader: "file-loader"
            }
        ]
    }
};

export default config;
</code>```

Unfortunately it doesn't load my src/index.html file to the dist folder. What am I doing wrong? How can I get the index file from the src folder to the dist folder?

答:
You can use html-webpack-plugin.

```<code>{
  plugins: [
    new HtmlWebpackPlugin({
      template: 'src/index.html'
    })
  ]
}
</code>```

Body:
I try to load my index.html file via the file-loader and Webpack 3.

My webpack.config.tslooks like this:

import * as webpack from 'webpack';

const config: webpack.Configuration = {
    entry: "./src/app.tsx",
    output: {
        filename: "bundle.js",
        path: __dirname + "/dist"
    },

    devtool: "source-map",

    resolve: {
        extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js", ".html"]
    },

    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: "awesome-typescript-loader"
            }, {
                test: /\.html$/,
                loader: "file-loader"
            }
        ]
    }
};

export default config;

Unfortunately it doesn't load my src/index.html file to the dist folder. What am I doing wrong? How can I get the index file from the src folder to the dist folder?

Body:
You can use html-webpack-plugin.

{
  plugins: [
    new HtmlWebpackPlugin({
      template: 'src/index.html'
    })
  ]
}


问:
How to set background color in MAC OSX in Objective c
I am very new to MAC OSX implementation. Can you guys please suggest any documentations that how to get some grip on Menus,background colors, text fields and all UIElements programatically  with out using interface builder.

Thanking you,
S.

答: Use Apple's developer documentation. If you are looking for information on how to use a specific class, you can load it's reference page and check the companion guide/sample code sections. http://developer.apple.com/mac/</p>


问:
focus on input trigger twice instead of only one trigger
Hi I am creating jquery plugin. I stuck on when i focus on input box then it triggered twice.

$(document).ready(function(){
   $('#searchText').typefast();
   $('#searchText1').typefast();
})
$.fn.typefast=function(){
   $('input').focus(function(){
      console.log($(this).attr('id'));
   })
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" name="" value="" id="searchText">
<input type="text" class="form-control" name="" value="" id="searchText1"></code>```

`

答:
It's running twice because you are explicitly calling typefast() twice in your document.ready function. Even though your selectors were both missing the # in them, typefast() still gets called on the empty jQuery wrappers. And, since typefast() doesn't actually do anything with the contents of the wrapped set it gets called on, it goes ahead and processes on all input elements. So, the end result is that all input elements get typefast registered into their focus event twice.

If (and this is a big if) you were going to use a plug-in for this, you should just call it once because the plug-in finds all input elements and sets their event handler. Also, plug-ins have a certain pattern that is recommended to be followed to ensure that the $ will, in fact, point to the jQuery object and to ensure that method chaining will work. That would look like this:

$(function(){
   // You would want this to be a jQuery utility method (not a wrapped set method)
   // so you would set it up directly on jQuery, not jQuery.fn. This way, you can
   // just call it whenever you want without a wrapped set.
   $.typefast();
});

// By wrapping the plugin in an Immediately Invoked Function Expression
// that passes itself the jQuery object, we guarantee the $ will work
(function($){
  $.typefast = function(){
    $('input').focus(function(){
      console.log($(this).attr('id'));
    });
  }
}(jQuery));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" name="" value="" id="searchText">
<input type="text" class="form-control" name="" value="" id="searchText1"></code>```

But, there is no need for a jQuery plug-in here. This is not what plug-ins are for and you are not even writing it according to best practices. This is not the way to set up event handlers. All you need to do is set up an event handler for the focus event of the textboxes:

// Just passing a function directly to the jQuery object is the same
// thing as explicitly setting a callback for document.ready
$(function(){
  // This is the function that will be called when any input gets the focus
  function typeFast(){
    console.log($(this).attr('id'));
  }

  // Set all input elements to call typeFast when they receive the focus
  $('input').on("focus", typeFast);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" name="" value="" id="searchText">
<input type="text" class="form-control" name="" value="" id="searchText1"></code>```

Body:
Hi I am creating jquery plugin. I stuck on when i focus on input box then it triggered twice.

$(document).ready(function(){
   $('#searchText').typefast();
   $('#searchText1').typefast();
})
$.fn.typefast=function(){
   $('input').focus(function(){
      console.log($(this).attr('id'));
   })
}

<input type="text" class="form-control" name="" value="" id="searchText">
<input type="text" class="form-control" name="" value="" id="searchText1">

`

Body:
It's running twice because you are explicitly calling typefast() twice in your document.ready function. Even though your selectors were both missing the # in them, typefast() still gets called on the empty jQuery wrappers. And, since typefast() doesn't actually do anything with the contents of the wrapped set it gets called on, it goes ahead and processes on all input elements. So, the end result is that all input elements get typefast registered into their focus event twice.

If (and this is a big if) you were going to use a plug-in for this, you should just call it once because the plug-in finds all input elements and sets their event handler. Also, plug-ins have a certain pattern that is recommended to be followed to ensure that the $ will, in fact, point to the jQuery object and to ensure that method chaining will work. That would look like this:

$(function(){
   // You would want this to be a jQuery utility method (not a wrapped set method)
   // so you would set it up directly on jQuery, not jQuery.fn. This way, you can
   // just call it whenever you want without a wrapped set.
   $.typefast();
});

// By wrapping the plugin in an Immediately Invoked Function Expression
// that passes itself the jQuery object, we guarantee the $ will work
(function($){
  $.typefast = function(){
    $('input').focus(function(){
      console.log($(this).attr('id'));
    });
  }
}(jQuery));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" name="" value="" id="searchText">
<input type="text" class="form-control" name="" value="" id="searchText1">

But, there is no need for a jQuery plug-in here. This is not what plug-ins are for and you are not even writing it according to best practices. This is not the way to set up event handlers. All you need to do is set up an event handler for the focus event of the textboxes:

// Just passing a function directly to the jQuery object is the same
// thing as explicitly setting a callback for document.ready
$(function(){
  // This is the function that will be called when any input gets the focus
  function typeFast(){
    console.log($(this).attr('id'));
  }

  // Set all input elements to call typeFast when they receive the focus
  $('input').on("focus", typeFast);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" name="" value="" id="searchText">
<input type="text" class="form-control" name="" value="" id="searchText1">


问:
Change array values depending on selections in listbox on a userform
I want to be able to change array values from my sub that runs a userform. How do I go about doing this?

Here is an example of what I have:

```<code>A = [25, 50, 75, 100]
UserForm1.Show
</code>```

UserForm1 contains a listbox with options 1, 2 or 3.

By selecting "1", "2,", "3", or multiple combinations of them I want to change the value of A accordingly.

```<code>If "1" is selected Then
A(0) = 10
If "2" is selected Then
A(1) = 0
If "3" is selected Then
A(2) = 1000
</code>```

How would I make this happen? Thanks in advance for any help.

答:
This is tested in a ListBox_AfterUpdate() event. Get a handle on the ListBox object (assigned to variable lb) then iterate the items in the lb.List, checking if each is selected. If selected, then assign a positional value to the array A.

The array A is declared as a module/user-form scoped variable here, and assigned default/initial values during the form's _Initialize event. Those values are then changed if the user makes a selection(s) in the ListBox.

```<code>Option Explicit
Dim A()
Private Sub UserForm_Initialize()
'Assigns initial values to your array:
A = Array(25, 50, 75, 100)
'Assigns the default ListBox items:
Me.ListBox1.List = Array("1", "2", "3")
End Sub
Private Sub ListBox1_AfterUpdate()
Dim lb As MSForms.ListBox
Dim i As Long, v As Long
Set lb = Me.ListBox1 '# Modify as needed
For i = 0 To lb.ListCount - 1
    If lb.Selected(i) Then
        Select Case lb.List(i)
            Case "1"
                v = 10
            Case "2"
                v = 0
            Case "3"
                v = 1000
        End Select
        'confirm prev & new values for array:
        MsgBox (A(i) & " will be changed to: " & v)
        A(i) = v
        'Confirm the value in array has changed
        MsgBox (A(i))
    End If
Next
End Sub
</code>```

Depending on where/when you initialize the A array, you could modify this and invoke it from the ListBox_Change or ListBox_AfterUpdate event, or call it from another control's event procedure as needed.

Body:
I want to be able to change array values from my sub that runs a userform. How do I go about doing this?

Here is an example of what I have:

A = [25, 50, 75, 100]
UserForm1.Show

UserForm1 contains a listbox with options 1, 2 or 3.

By selecting "1", "2,", "3", or multiple combinations of them I want to change the value of A accordingly.

If "1" is selected Then
A(0) = 10
If "2" is selected Then
A(1) = 0
If "3" is selected Then
A(2) = 1000

How would I make this happen? Thanks in advance for any help.

Body:
This is tested in a ListBox_AfterUpdate() event. Get a handle on the ListBox object (assigned to variable lb) then iterate the items in the lb.List, checking if each is selected. If selected, then assign a positional value to the array A.

The array A is declared as a module/user-form scoped variable here, and assigned default/initial values during the form's _Initialize event. Those values are then changed if the user makes a selection(s) in the ListBox.

Option Explicit
Dim A()
Private Sub UserForm_Initialize()
'Assigns initial values to your array:
A = Array(25, 50, 75, 100)
'Assigns the default ListBox items:
Me.ListBox1.List = Array("1", "2", "3")
End Sub
Private Sub ListBox1_AfterUpdate()
Dim lb As MSForms.ListBox
Dim i As Long, v As Long
Set lb = Me.ListBox1 '# Modify as needed
For i = 0 To lb.ListCount - 1
    If lb.Selected(i) Then
        Select Case lb.List(i)
            Case "1"
                v = 10
            Case "2"
                v = 0
            Case "3"
                v = 1000
        End Select
        'confirm prev & new values for array:
        MsgBox (A(i) & " will be changed to: " & v)
        A(i) = v
        'Confirm the value in array has changed
        MsgBox (A(i))
    End If
Next
End Sub

Depending on where/when you initialize the A array, you could modify this and invoke it from the ListBox_Change or ListBox_AfterUpdate event, or call it from another control's event procedure as needed.


问:
Spring Batch :- Running Job in two stages
Here is the spring batch design for job recommending to my client:-

UI application will call Rest API on API server. Rest API creates a unique id , and send unique id, job params, job name as jms message to some batch server.  Rest API sends the unique token id to UI.

JMS message listener on batch server create a new spring batch job instance and set up unique id as job param and run the job.

UI keeps on polling the Status Rest API by passing the unique token.

Rest API finds from job param table for unique id, job execution id and provide the job status to UI.

Please advise, any suggestion so that we can create the job on API server, so that job instance and param created but does not execute any steps. We know the job execution id

On batch server with input job execution id, we can rerun/resume the job again.

答:
I was debugging the Spring batch code. I came with this approach. But now trying to worked it out, see this works :-

My client using oracle DB. Spring Batch provides this property in batch-oracle.properties file.
batch.database.incrementer.class=org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer
I will override the batch.database.incrementer.class property by
client specific incrementer class by subclassing OracleSequenceMaxValueIncrementer and override getNextKey() abstract method.

On API server, I will call only job execution sequence, get the id and pass same in jms message.

On batch server, store the job execution id in some thread local. getNextKey() method check if  incrementer name is JOB EXEC SEQ, get the id from thread local else create the way spring batch is doing it. getNextKey() will be called during job execution creation by spring batch. For other tables sequence, this will not cause issue as incrementer name will be diff.


问:
Convert unsigned char to char* and Concatenate them in C
I want to convert a value unsigned char to one of type char* passing values through a function.

This is my program:

```<code>int my_function(unsigned char param1, unsigned char param2)
{
    char* buffer_char;

    const char* mss_part_1 = "Value 1: ";
    const char* mss_part_2 = " Value 2: ";

    buffer_char = malloc(240);

    strcpy(buffer_char, mss_part_1);    //OK
    strcat(buffer_char, param1);        //ERROR
    strcat(buffer_char, mss_part_2);    //OK
    strcat(buffer_char, param2);        //ERROR

    //Desire Output: "Value 1: 1234 Value 2: 5678"
    printf("%s", buffer_char);

    free(buffer_char);
}

int main(int argc, char const *argv[])
{
    unsigned char value1[10];
    unsigned char value2[10];

    strncpy(value1, "1234", 4);
    strncpy(value2, "5678", 4);

    my_function(value1, value2);

    return 0;
}
</code>```

The problem is in the strcat() function when I try to concatenate the value as "unsigned char" but I have not found the way to convert it so I can concatenate it.

I am trying to use the strcat() function but if there was a more efficient form I would like to know.

Note: I have no problem displaying the output value.

答:
You're passing in pointers, so the sig of the function should have pointers.

```<code>int my_function(unsigned char *param1, unsigned char *param2);
</code>```

The unsigned stuff is likely a needless complication -- you might want to get rid of it in the whole program. You're also using strncpy wrong, are failing to error check (malloc may fail) , and your function's API is weak because it doesn't allow you to do any kind of bound checking.

Here's a quick and dirty fix except for the bounds-checking part:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int my_function(char *param1, char *param2)
{
    char* buffer_char;

    const char* mss_part_1 = "Value 1: ";
    const char* mss_part_2 = " Value 2: ";

    buffer_char = malloc(240);
    if(0 == buffer_char)
        return -1;

    strcpy(buffer_char, mss_part_1);
    strcat(buffer_char, param1);
    strcat(buffer_char, mss_part_2);
    strcat(buffer_char, param2);

    //Desire Output: "Value 1: 1234 Value 2: 5678"
    printf("%s", buffer_char);

    free(buffer_char);
    return 0;
}

int main(int argc, char const *argv[])
{
    char value1[10];
    char value2[10];

    strncpy(value1, "1234", 10);
    strncpy(value2, "5678", 10);

    my_function(value1, value2);

    return 0;
}
</code>```

Your compiler is probably warning you about all these errors. You should treat all the warnings as errors.

Body:
I want to convert a value unsigned char to one of type char* passing values through a function.

This is my program:

int my_function(unsigned char param1, unsigned char param2)
{
    char* buffer_char;

    const char* mss_part_1 = "Value 1: ";
    const char* mss_part_2 = " Value 2: ";

    buffer_char = malloc(240);

    strcpy(buffer_char, mss_part_1);    //OK
    strcat(buffer_char, param1);        //ERROR
    strcat(buffer_char, mss_part_2);    //OK
    strcat(buffer_char, param2);        //ERROR

    //Desire Output: "Value 1: 1234 Value 2: 5678"
    printf("%s", buffer_char);

    free(buffer_char);
}

int main(int argc, char const *argv[])
{
    unsigned char value1[10];
    unsigned char value2[10];

    strncpy(value1, "1234", 4);
    strncpy(value2, "5678", 4);

    my_function(value1, value2);

    return 0;
}

The problem is in the strcat() function when I try to concatenate the value as "unsigned char" but I have not found the way to convert it so I can concatenate it.

I am trying to use the strcat() function but if there was a more efficient form I would like to know.

Note: I have no problem displaying the output value.

Body:
You're passing in pointers, so the sig of the function should have pointers.

int my_function(unsigned char *param1, unsigned char *param2);

The unsigned stuff is likely a needless complication -- you might want to get rid of it in the whole program. You're also using strncpy wrong, are failing to error check (malloc may fail) , and your function's API is weak because it doesn't allow you to do any kind of bound checking.

Here's a quick and dirty fix except for the bounds-checking part:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int my_function(char *param1, char *param2)
{
    char* buffer_char;

    const char* mss_part_1 = "Value 1: ";
    const char* mss_part_2 = " Value 2: ";

    buffer_char = malloc(240);
    if(0 == buffer_char)
        return -1;

    strcpy(buffer_char, mss_part_1);
    strcat(buffer_char, param1);
    strcat(buffer_char, mss_part_2);
    strcat(buffer_char, param2);

    //Desire Output: "Value 1: 1234 Value 2: 5678"
    printf("%s", buffer_char);

    free(buffer_char);
    return 0;
}

int main(int argc, char const *argv[])
{
    char value1[10];
    char value2[10];

    strncpy(value1, "1234", 10);
    strncpy(value2, "5678", 10);

    my_function(value1, value2);

    return 0;
}

Your compiler is probably warning you about all these errors. You should treat all the warnings as errors.


问:
Using python scrapy based crawler but getting error
Hi folks I have written a crawler in python for scraping......

```<code>import scrapy

from c2.items import C2Item

try:

    class C2(scrapy.Spider):
            name = 'cn'
            allowed_domains = ['priceraja.com']
            start_urls = ['https://www.priceraja.com']

            def parse_item(self, response):

               Item = []
               Item['url']=response.xpath('//a/@href/text()').extract()
               yield Item

except Exception:
logging.exception("message")
</code>```

I keep on getting NotImplemented error

```<code>2017-08-05 01:12:28 [scrapy.core.scraper] ERROR: Spider error processing
<GET
https://www.killerfeatures.com> (referer: None)
Traceback (most recent call last):
File "D:\Ana\lib\site-packages\twisted\internet\defer.py", line 653, in _
runCallbacks
current.result = callback(current.result, *args, **kw)
File "D:\Ana\lib\site-packages\scrapy\spiders\__init__.py", line 90, in
parse raise NotImplementedError
NotImplementedError
2017-08-05 01:12:28 [scrapy.core.engine] INFO: Closing spider (finished)
2017-08-05 01:12:28 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 435,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 2,
</code>```

'downloader/response_bytes': 9282,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 1,
 'downloader/response_status_count/301': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 8, 4, 19, 42, 28, 837000),
 'log_count/DEBUG': 3,
 'log_count/ERROR': 1,
 'log_count/INFO': 7,
 'response_received_count': 1,
 'scheduler/dequeued': 2,
 'scheduler/dequeued/memory': 2,
 'scheduler/enqueued': 2,
 'scheduler/enqueued/memory': 2,
 'spider_exceptions/NotImplementedError': 1,
 'start_time': datetime.datetime(2017, 8, 4, 19, 42, 25, 976000)}
  2017-08-05 01:12:28 [scrapy.core.engine] INFO: Spider closed (finished)

答:
Scrapy is looking for the parse function while you have implement the parse_item function. Changing parse_item to parse might work, or you can override the parse function.

Another solution from here is to use CrawlSpider

Body:
Hi folks I have written a crawler in python for scraping......

import scrapy

from c2.items import C2Item

try:

    class C2(scrapy.Spider):
            name = 'cn'
            allowed_domains = ['priceraja.com']
            start_urls = ['https://www.priceraja.com']

            def parse_item(self, response):

               Item = []
               Item['url']=response.xpath('//a/@href/text()').extract()
               yield Item

except Exception:
logging.exception("message")

I keep on getting NotImplemented error

2017-08-05 01:12:28 [scrapy.core.scraper] ERROR: Spider error processing
<GET
https://www.killerfeatures.com> (referer: None)
Traceback (most recent call last):
File "D:\Ana\lib\site-packages\twisted\internet\defer.py", line 653, in _
runCallbacks
current.result = callback(current.result, *args, **kw)
File "D:\Ana\lib\site-packages\scrapy\spiders\__init__.py", line 90, in
parse raise NotImplementedError
NotImplementedError
2017-08-05 01:12:28 [scrapy.core.engine] INFO: Closing spider (finished)
2017-08-05 01:12:28 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 435,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 2,

'downloader/response_bytes': 9282,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 1,
 'downloader/response_status_count/301': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 8, 4, 19, 42, 28, 837000),
 'log_count/DEBUG': 3,
 'log_count/ERROR': 1,
 'log_count/INFO': 7,
 'response_received_count': 1,
 'scheduler/dequeued': 2,
 'scheduler/dequeued/memory': 2,
 'scheduler/enqueued': 2,
 'scheduler/enqueued/memory': 2,
 'spider_exceptions/NotImplementedError': 1,
 'start_time': datetime.datetime(2017, 8, 4, 19, 42, 25, 976000)}
  2017-08-05 01:12:28 [scrapy.core.engine] INFO: Spider closed (finished)


问:
How to add multi line comments in makefiles
Is there a way to comment out multiple lines in makefiles like as in C syntax /* */ ?

答: I believe the answer is no. The only comment styling I can find is # for each line, or use \ to wrap the first line.</p>


问:
file.create syntax
Super big newbie to R. I'm a bit stuck on the file.create function. I've used it successfully to create a file in the set working directory and also when I've already created a separate file path and assigned that file path to a variable.

However, why can't I use file.create and simply list the desired file path and file name without the file.path function? Does the file.create function not possess the capacity to automatically create the file in the specified directory, but requires the file.path function to secure the path to the directory?

Any clarification would be greatly appreciated. I do apologize if this question is rather elementary but I'd like to get the fundamentals down.

Here's the code that worked:

```<code>BasicDir <- "/Users/slam1924/Desktop/LearnR Tutorials"
setwd(BasicDir)
file.create("myfile.doc")
fp1 <- file.path("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc")
fp1
file.create(fp1)
</code>```

Alternative:

```<code>file.create(file.path("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc"))
</code>```

Here's the code that failed:

```<code>file.create("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc")
</code>```

答:
Start by reading the help for the function. help(file.create). The usage is file.create(..., showWarnings = TRUE)

Under Details you'll see

file.create creates files with the given names if they do not already
  exist and truncates them if they do.

So when you try

```<code>file.create("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc")
</code>```

It's trying to create two files, one of which ("/Users/slam1924/Desktop/Vocal Covers") is likely already a directory.

If the file or directory already exists, you'll see an error like:

```<code>[1] FALSE
Warning message:
In file.create("data") :
  cannot create file 'data', reason 'Permission denied'
</code>```

You could fix this by sending the function one string. Change your code that failed to:

file.create("/Users/slam1924/Desktop/Vocal Covers/mytext.doc")

Title: file.create syntax

Body:
Super big newbie to R. I'm a bit stuck on the file.create function. I've used it successfully to create a file in the set working directory and also when I've already created a separate file path and assigned that file path to a variable.

However, why can't I use file.create and simply list the desired file path and file name without the file.path function? Does the file.create function not possess the capacity to automatically create the file in the specified directory, but requires the file.path function to secure the path to the directory?

Any clarification would be greatly appreciated. I do apologize if this question is rather elementary but I'd like to get the fundamentals down.

Here's the code that worked:

BasicDir <- "/Users/slam1924/Desktop/LearnR Tutorials"
setwd(BasicDir)
file.create("myfile.doc")
fp1 <- file.path("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc")
fp1
file.create(fp1)

Alternative:

file.create(file.path("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc"))

Here's the code that failed:

file.create("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc")

Body:
Start by reading the help for the function. help(file.create). The usage is file.create(..., showWarnings = TRUE)

Under Details you'll see

file.create creates files with the given names if they do not already
  exist and truncates them if they do.

So when you try

file.create("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc")

It's trying to create two files, one of which ("/Users/slam1924/Desktop/Vocal Covers") is likely already a directory.

If the file or directory already exists, you'll see an error like:

[1] FALSE
Warning message:
In file.create("data") :
  cannot create file 'data', reason 'Permission denied'

You could fix this by sending the function one string. Change your code that failed to:

file.create("/Users/slam1924/Desktop/Vocal Covers/mytext.doc")


问:
Ionic 3/Angular 4 simple form validation - jit_nodeValue15(...) is not a function
I have a super simple form, where i want to check if the user filled out the datefrom.

Here's my form:

```<code><ion-content padding>
<form #signoff="ngForm" novalidate>
<ion-row>
  <ion-col>

    <ion-row>
      <ion-col class="col-left">
        <label class="select_label">{{datefrom_data.title}}</label>
      </ion-col>
      <ion-col class="col-right">
        <input class="select_control" name="signoff.datefrom_name" type="date" [(ngModel)]="datefrom" (click)="showDatePicker()" required>
      </ion-col>
    </ion-row>

  </ion-col>
</ion-row>
<ion-row class="Bemerkung">
  <ion-col>
    <ion-label>Bemerkung:</ion-label>
      <ion-textarea class="signoff-textarea" name="signoff.comment_name" [(ngModel)]="addtionalInfo">
      </ion-textarea>
  </ion-col>
</ion-row>
<button ion-button class="maincolor" block [disabled]="!signoff.form.valid" (click)="signoff()">Kind abmelden</button>
</form>
</ion-content>
</code>```

in my signoff.ts i have the signoff() function.
The validation on the button works but as soon as I click the button I receive a runtime error: "jit_nodeValue15(...) is not a function"

If I remove the form the button click event works again.

My enviroment:

Ionic Framework: 3.0.1
Angular Core: 4.0.0
Ionic App Scripts: 1.3.0

signoff.ts:
https://gist.github.com/anonymous/5680ad02f00d9fe40466e0b2d2409834

EDIT:
- added signoff.ts
- added error image

答: I renamed the function from signoff() to signoffChild() and now it works...</p>

Body:
I have a super simple form, where i want to check if the user filled out the datefrom.

Here's my form:

<ion-content padding>
<form #signoff="ngForm" novalidate>
<ion-row>
  <ion-col>

    <ion-row>
      <ion-col class="col-left">
        {{datefrom_data.title}}
      </ion-col>
      <ion-col class="col-right">
        <input class="select_control" name="signoff.datefrom_name" type="date" [(ngModel)]="datefrom" (click)="showDatePicker()" required>
      </ion-col>
    </ion-row>

  </ion-col>
</ion-row>
<ion-row class="Bemerkung">
  <ion-col>
    <ion-label>Bemerkung:</ion-label>
      <ion-textarea class="signoff-textarea" name="signoff.comment_name" [(ngModel)]="addtionalInfo">
      </ion-textarea>
  </ion-col>
</ion-row>
<button ion-button class="maincolor" block [disabled]="!signoff.form.valid" (click)="signoff()">Kind abmelden</button>
</form>
</ion-content>

in my signoff.ts i have the signoff() function.
The validation on the button works but as soon as I click the button I receive a runtime error: "jit_nodeValue15(...) is not a function"

If I remove the form the button click event works again.

My enviroment:

Ionic Framework: 3.0.1
Angular Core: 4.0.0
Ionic App Scripts: 1.3.0

signoff.ts:
https://gist.github.com/anonymous/5680ad02f00d9fe40466e0b2d2409834

EDIT:
- added signoff.ts
- added error image


问:
How to run thousands of queries in Ms Access?
I've discovered the SQL VIEW in Ms Access to execute some queries, but I need to execute about 20.000 UPDATE queries I have in a .sql file.

When I paste in the SQL VIEW it says the "Text is too long to modify".

How can I run those UPDATE's ?

答: There may be an easier way but you could write VBA code that reads the text file line by line and then uses DoCmd.RunSQL to run each query.


问:
Assigning page results from scrape-it npm to a variable returns Promise { <pending> }
I'm attempting to use scrape-it as a dependency that I downloaded from NPM earlier today. I'm able to get the content back that I want, but need to store the results in a variable rather than handle them via the callback.

Using the 'sample' from scrape-it docs, when I try the following:

```<code>var myVar = scrapeIt("http://ionicabizau.net", {
    title: ".header h1"
  , desc: ".header h2"
  , avatar: {
        selector: ".header img"
      , attr: "src"
    }
}).then(page => {
    return page;
});

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

I get the result: Promise { <pending> }

I've also tried using 'await' prior to calling the scrapeIt() function, but when I do that locally 'Unexpected identifier' syntax error in return.

Mind you, when I've tried this on the RunKit + npm site, it does work there, but it doesn't work for me locally. I've uninstalled and reinstalled the package, and it seems like I have all the necessary dependencies, so not sure what I'm doing wrong. :-\

While this obviously does touch on the asynchronous nature of javascript, the focal point of the question is to better understand interaction with promises.

答:
The scrapeIt method is asynchronous due to the async nature of the request module.

scrapeIt.scrapeHTML is sync, but it expects the HTML as a string.

So, as long you can get the HTML from somewhere, you can do something very similar to what you did:

```<code>var myVar = scrapeIt.scrapeHTML("<h1>Hello</h1>", {
    title: "h1"
});
console.log(myVar);
// { title: "h1" }
</code>```

You can think of something async as something that you have to wait for (e.g. downloading the HTML of the page—that takes time). That's why there are callbacks and promises and so on.

```<code>scrapeIt("http://ionicabizau.net", {
    title: ".header h1"
  , desc: ".header h2"
  , avatar: {
        selector: ".header img"
      , attr: "src"
    }
}).then(myVar => {
   // Use myVar, only once it's ready
   // Once the page is downloaded and parsed
   // this function is triggered
   console.log(myVar)

   // Here you can do something with myVar
});

// At this point the page is not downloaded yet.
</code>```

Body:
I'm attempting to use scrape-it as a dependency that I downloaded from NPM earlier today. I'm able to get the content back that I want, but need to store the results in a variable rather than handle them via the callback.

Using the 'sample' from scrape-it docs, when I try the following:

var myVar = scrapeIt("http://ionicabizau.net", {
    title: ".header h1"
  , desc: ".header h2"
  , avatar: {
        selector: ".header img"
      , attr: "src"
    }
}).then(page => {
    return page;
});

console.log(myVar);

I get the result: Promise { <pending> }

I've also tried using 'await' prior to calling the scrapeIt() function, but when I do that locally 'Unexpected identifier' syntax error in return.

Mind you, when I've tried this on the RunKit + npm site, it does work there, but it doesn't work for me locally. I've uninstalled and reinstalled the package, and it seems like I have all the necessary dependencies, so not sure what I'm doing wrong. :-\

While this obviously does touch on the asynchronous nature of javascript, the focal point of the question is to better understand interaction with promises.

Body:
The scrapeIt method is asynchronous due to the async nature of the request module.

scrapeIt.scrapeHTML is sync, but it expects the HTML as a string.

So, as long you can get the HTML from somewhere, you can do something very similar to what you did:

var myVar = scrapeIt.scrapeHTML("<h1>Hello</h1>", {
    title: "h1"
});
console.log(myVar);
// { title: "h1" }

You can think of something async as something that you have to wait for (e.g. downloading the HTML of the page—that takes time). That's why there are callbacks and promises and so on.

scrapeIt("http://ionicabizau.net", {
    title: ".header h1"
  , desc: ".header h2"
  , avatar: {
        selector: ".header img"
      , attr: "src"
    }
}).then(myVar => {
   // Use myVar, only once it's ready
   // Once the page is downloaded and parsed
   // this function is triggered
   console.log(myVar)

   // Here you can do something with myVar
});

// At this point the page is not downloaded yet.


问:
undefined function put_req_header/3
I have the following module in Phoenix app. This code is basically shared spec example. It looks like this:

```<code>defmodule TattooBackend.CurrentPasswordRequiredTest do
  @moduledoc """
  This module defines tests that are testing api current password requirement.
  """
  import Phoenix.ConnTest

  alias TattooBackend.Web.Router

  defmacro test_current_password_required_for(method, path_name, action) do
    quote do
      test "without current password", %{conn: conn} do
        method    = unquote(method)
        path_name = unquote(path_name)
        action    = unquote(action)
        account = insert(:account)

        assert make_unauthenticated_request(conn, @endpoint, method, path_name, action, account) == %{
          "error" => "Błędne hasło."
        }
      end
    end
  end

  def make_unauthenticated_request(conn, endpoint, method, path_name, action, account) do
    path = apply(Router.Helpers, path_name, [conn, action])

    conn
    |> put_req_header("authorization", "#{token(account)}")
    |> dispatch(endpoint, method, path, nil)
    |> json_response(422)
  end
end
</code>```

When I run my specs it returns error:

```<code>** (CompileError) test/support/shared_tests/current_password_required.ex:28: undefined function put_req_header/3
</code>```

How can I fix that?

答: The function is actually Plug.Conn.put_req_header/3 - you need to either use the full name or import the Plug.Conn module.

Title: undefined function put_req_header/3

Body:
I have the following module in Phoenix app. This code is basically shared spec example. It looks like this:

defmodule TattooBackend.CurrentPasswordRequiredTest do
  @moduledoc """
  This module defines tests that are testing api current password requirement.
  """
  import Phoenix.ConnTest

  alias TattooBackend.Web.Router

  defmacro test_current_password_required_for(method, path_name, action) do
    quote do
      test "without current password", %{conn: conn} do
        method    = unquote(method)
        path_name = unquote(path_name)
        action    = unquote(action)
        account = insert(:account)

        assert make_unauthenticated_request(conn, @endpoint, method, path_name, action, account) == %{
          "error" => "Błędne hasło."
        }
      end
    end
  end

  def make_unauthenticated_request(conn, endpoint, method, path_name, action, account) do
    path = apply(Router.Helpers, path_name, [conn, action])

    conn
    |> put_req_header("authorization", "#{token(account)}")
    |> dispatch(endpoint, method, path, nil)
    |> json_response(422)
  end
end

When I run my specs it returns error:

** (CompileError) test/support/shared_tests/current_password_required.ex:28: undefined function put_req_header/3

How can I fix that?


问:
socket.gaierror: [Errno -2] Name or service not known urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>
I was looking this tutorial on how to implement convolutional neural networks.

I followed the instructions there so now I have this code:

```<code>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from subprocess import check_output
print(check_output(["ls", "../input"]).decode("utf8"))
import tensorflow as tf
from tensorflow.contrib import learn
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib

tf.logging.set_verbosity(tf.logging.INFO)

def cnn_model_fn(features, labels, mode):
  """Model function for CNN."""
  # Input Layer
  input_layer = tf.reshape(features, [-1, 28, 28, 1])

  # Convolutional Layer #1
  conv1 = tf.layers.conv2d(
      inputs=input_layer,
      filters=32,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)

  # Pooling Layer #1
  pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

  # Convolutional Layer #2 and Pooling Layer #2
  conv2 = tf.layers.conv2d(
      inputs=pool1,
      filters=64,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)
  pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

  # Dense Layer
  pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
  dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)
  dropout = tf.layers.dropout(
      inputs=dense, rate=0.4, training=mode == learn.ModeKeys.TRAIN)

  # Logits Layer
  logits = tf.layers.dense(inputs=dropout, units=10)

  loss = None
  train_op = None

  # Calculate Loss (for both TRAIN and EVAL modes)
  if mode != learn.ModeKeys.INFER:
    onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=10)
    loss = tf.losses.softmax_cross_entropy(
        onehot_labels=onehot_labels, logits=logits)

  # Configure the Training Op (for TRAIN mode)
  if mode == learn.ModeKeys.TRAIN:
    train_op = tf.contrib.layers.optimize_loss(
        loss=loss,
        global_step=tf.contrib.framework.get_global_step(),
        learning_rate=0.001,
        optimizer="SGD")

  # Generate Predictions
  predictions = {
      "classes": tf.argmax(
          input=logits, axis=1),
      "probabilities": tf.nn.softmax(
          logits, name="softmax_tensor")
  }

  # Return a ModelFnOps object
  return model_fn_lib.ModelFnOps(
      mode=mode, predictions=predictions, loss=loss, train_op=train_op)

def main():
    print("In main")
    # Load training and eval data
    mnist = learn.datasets.load_dataset("mnist")
    train_data = tf.train.string_input_producer(tf.train.match_filenames_once("../inputs/train/*.jpg")) # Returns np.array
    train_labels = np.asarray(train_labels.csv, dtype=np.float32)
    test_data = tf.train.string_input_producer(tf.train.match_filenames_once("../inputs/test/*.jpg")) # Returns np.array
    # eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

    # Create the Estimator
    mnist_classifier = learn.Estimator(
          model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model")

    # Set up logging for predictions
    tensors_to_log = {"probabilities": "softmax_tensor"}
    logging_hook = tf.train.LoggingTensorHook(
      tensors=tensors_to_log, every_n_iter=50)

    mnist_classifier.fit(
        x=train_data,
        y=train_labels,
        batch_size=100,
        steps=20000,
        monitors=[logging_hook])

    # Configure the accuracy metric for evaluation
    metrics = {
        "accuracy":
            learn.MetricSpec(
                metric_fn=tf.metrics.accuracy, prediction_key="classes"),
    }

    # Evaluate the model and print results
    eval_results = mnist_classifier.evaluate(
        x=eval_data, y=eval_labels, metrics=metrics)
    print(eval_results)

main()
</code>```

For this code, I am getting this error:

```<code>Traceback (most recent call last):
  File "/opt/conda/lib/python3.6/urllib/request.py", line 1318, in do_open
10.0s
3
    encode_chunked=req.has_header('Transfer-encoding'))
  File "/opt/conda/lib/python3.6/http/client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/opt/conda/lib/python3.6/http/client.py", line 1285, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/opt/conda/lib/python3.6/http/client.py", line 1234, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/opt/conda/lib/python3.6/http/client.py", line 1026, in _send_output
    self.send(msg)
  File "/opt/conda/lib/python3.6/http/client.py", line 964, in send
    self.connect()
  File "/opt/conda/lib/python3.6/http/client.py", line 1392, in connect
    super().connect()
  File "/opt/conda/lib/python3.6/http/client.py", line 936, in connect
    (self.host,self.port), self.timeout, self.source_address)
  File "/opt/conda/lib/python3.6/socket.py", line 704, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "/opt/conda/lib/python3.6/socket.py", line 743, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "../src/script.py", line 130, in <module>
    main()
  File "../src/script.py", line 93, in main
    mnist = learn.datasets.load_dataset("mnist")
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/__init__.py", line 73, in load_dataset
10.1s
4
    return DATASETS[name]()
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 279, in load_mnist
10.2s
5
    return read_data_sets(train_dir)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 235, in read_data_sets
    SOURCE_URL + TRAIN_IMAGES)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 208, in maybe_download
10.2s
6
    temp_file_name, _ = urlretrieve_with_retry(source_url)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 165, in wrapped_fn
    return fn(*args, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 190, in urlretrieve_with_retry
    return urllib.request.urlretrieve(url, filename)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 248, in urlretrieve
    with contextlib.closing(urlopen(url, data)) as fp:
  File "/opt/conda/lib/python3.6/urllib/request.py", line 223, in urlopen
10.2s
7
    return opener.open(url, data, timeout)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 526, in open
    response = self._open(req, data)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 544, in _open
    '_open', req)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 504, in _call_chain
    result = func(*args)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 1361, in https_open
    context=self._context, check_hostname=self._check_hostname)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 1320, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>
</code>```

This message seems very unclear to me. Any idea what could be the cause of this?

答: The error is because of this line mnist = learn.datasets.load_dataset("mnist") which is trying to download the mnist dataset. But i don't see mnist being used in your code. So you can comment it if your not not using the dataset. Or if you want to use it you can download it from http://yann.lecun.com/exdb/mnist/ (all the four files) and put the path of the directory files in: mnist = learn.datasets.load_dataset("/path/to/mnist").

Body:
I was looking this tutorial on how to implement convolutional neural networks.

I followed the instructions there so now I have this code:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from subprocess import check_output
print(check_output(["ls", "../input"]).decode("utf8"))
import tensorflow as tf
from tensorflow.contrib import learn
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib

tf.logging.set_verbosity(tf.logging.INFO)

def cnn_model_fn(features, labels, mode):
  """Model function for CNN."""
  # Input Layer
  input_layer = tf.reshape(features, [-1, 28, 28, 1])

  # Convolutional Layer #1
  conv1 = tf.layers.conv2d(
      inputs=input_layer,
      filters=32,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)

  # Pooling Layer #1
  pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

  # Convolutional Layer #2 and Pooling Layer #2
  conv2 = tf.layers.conv2d(
      inputs=pool1,
      filters=64,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)
  pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

  # Dense Layer
  pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
  dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)
  dropout = tf.layers.dropout(
      inputs=dense, rate=0.4, training=mode == learn.ModeKeys.TRAIN)

  # Logits Layer
  logits = tf.layers.dense(inputs=dropout, units=10)

  loss = None
  train_op = None

  # Calculate Loss (for both TRAIN and EVAL modes)
  if mode != learn.ModeKeys.INFER:
    onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=10)
    loss = tf.losses.softmax_cross_entropy(
        onehot_labels=onehot_labels, logits=logits)

  # Configure the Training Op (for TRAIN mode)
  if mode == learn.ModeKeys.TRAIN:
    train_op = tf.contrib.layers.optimize_loss(
        loss=loss,
        global_step=tf.contrib.framework.get_global_step(),
        learning_rate=0.001,
        optimizer="SGD")

  # Generate Predictions
  predictions = {
      "classes": tf.argmax(
          input=logits, axis=1),
      "probabilities": tf.nn.softmax(
          logits, name="softmax_tensor")
  }

  # Return a ModelFnOps object
  return model_fn_lib.ModelFnOps(
      mode=mode, predictions=predictions, loss=loss, train_op=train_op)

def main():
    print("In main")
    # Load training and eval data
    mnist = learn.datasets.load_dataset("mnist")
    train_data = tf.train.string_input_producer(tf.train.match_filenames_once("../inputs/train/*.jpg")) # Returns np.array
    train_labels = np.asarray(train_labels.csv, dtype=np.float32)
    test_data = tf.train.string_input_producer(tf.train.match_filenames_once("../inputs/test/*.jpg")) # Returns np.array
    # eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

    # Create the Estimator
    mnist_classifier = learn.Estimator(
          model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model")

    # Set up logging for predictions
    tensors_to_log = {"probabilities": "softmax_tensor"}
    logging_hook = tf.train.LoggingTensorHook(
      tensors=tensors_to_log, every_n_iter=50)

    mnist_classifier.fit(
        x=train_data,
        y=train_labels,
        batch_size=100,
        steps=20000,
        monitors=[logging_hook])

    # Configure the accuracy metric for evaluation
    metrics = {
        "accuracy":
            learn.MetricSpec(
                metric_fn=tf.metrics.accuracy, prediction_key="classes"),
    }

    # Evaluate the model and print results
    eval_results = mnist_classifier.evaluate(
        x=eval_data, y=eval_labels, metrics=metrics)
    print(eval_results)

main()

For this code, I am getting this error:

Traceback (most recent call last):
  File "/opt/conda/lib/python3.6/urllib/request.py", line 1318, in do_open
10.0s
3
    encode_chunked=req.has_header('Transfer-encoding'))
  File "/opt/conda/lib/python3.6/http/client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/opt/conda/lib/python3.6/http/client.py", line 1285, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/opt/conda/lib/python3.6/http/client.py", line 1234, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/opt/conda/lib/python3.6/http/client.py", line 1026, in _send_output
    self.send(msg)
  File "/opt/conda/lib/python3.6/http/client.py", line 964, in send
    self.connect()
  File "/opt/conda/lib/python3.6/http/client.py", line 1392, in connect
    super().connect()
  File "/opt/conda/lib/python3.6/http/client.py", line 936, in connect
    (self.host,self.port), self.timeout, self.source_address)
  File "/opt/conda/lib/python3.6/socket.py", line 704, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  File "/opt/conda/lib/python3.6/socket.py", line 743, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "../src/script.py", line 130, in <module>
    main()
  File "../src/script.py", line 93, in main
    mnist = learn.datasets.load_dataset("mnist")
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/__init__.py", line 73, in load_dataset
10.1s
4
    return DATASETS[name]()
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 279, in load_mnist
10.2s
5
    return read_data_sets(train_dir)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 235, in read_data_sets
    SOURCE_URL + TRAIN_IMAGES)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 208, in maybe_download
10.2s
6
    temp_file_name, _ = urlretrieve_with_retry(source_url)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 165, in wrapped_fn
    return fn(*args, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 190, in urlretrieve_with_retry
    return urllib.request.urlretrieve(url, filename)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 248, in urlretrieve
    with contextlib.closing(urlopen(url, data)) as fp:
  File "/opt/conda/lib/python3.6/urllib/request.py", line 223, in urlopen
10.2s
7
    return opener.open(url, data, timeout)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 526, in open
    response = self._open(req, data)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 544, in _open
    '_open', req)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 504, in _call_chain
    result = func(*args)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 1361, in https_open
    context=self._context, check_hostname=self._check_hostname)
  File "/opt/conda/lib/python3.6/urllib/request.py", line 1320, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>

This message seems very unclear to me. Any idea what could be the cause of this?


问:
Google Sheets API v4 Appending data getting bad request 400 error
I am trying to append Sheets row, I am trying to put 2 Strings in single row in 2 columns.

Here is the code:

String range = "Write!A2:E200";
String spreadsheetId = SPREADSHEET_ID;
List<List<Object>> values = Arrays.asList(Arrays.asList());

ValueRange body = new ValueRange().setValues(values);
AppendValuesResponse result = service.spreadsheets()
    .values()
    .append(spreadsheetId, range, body)
    .setValueInputOption("USER_ENTERED")
    .execute();
```

<p>When I try to to add:</p>

<pre class="lang-java prettyprint-override"><code>values.add(new ArrayList<Object>(ListOfMyTwoStrings));
</code>```

I am getting the null error.

Update:

I have added:

```<code>List<Object> lists = new ArrayList<>();
lists.add(ListOne);
lists.add(ListTwo);

List<List<Object>> values = new ArrayList<>();
values.add(lists);
</code>```

Where ListOne and ListTwo are List<String> with the data which I want to append in the sheet, but when I try to execute I am getting:

```<code>400 Bad Request
{
  "code":400,
  "errors":[
    {
      "domain":"global",
      "message":"Invalid values[1][0]: list_value {\n}\n",
      "reason":"badRequest"
    }
  ],
  "message":"Invalid values[1][0]: list_value {\n}\n",
  "status":"INVALID_ARGUMENT"
}
</code>```

Can someone please help me to fix it?
Thank you and have a nice day!

答:
Found solution, this is working for me:

List<Object> lists = new ArrayList<>();

lists.add("String 1");
lists.add("String 2");

List<List<Object>> values = new ArrayList<>();
values.add(lists);
```

This will append "String 1" to A1 and "String 2" to A2.

Thanks abielita for tip.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to append Sheets row, I am trying to put 2 Strings in single row in 2 columns.

Here is the code:

String range = "Write!A2:E200";
String spreadsheetId = SPREADSHEET_ID;
List<List<Object>> values = Arrays.asList(Arrays.asList());

ValueRange body = new ValueRange().setValues(values);
AppendValuesResponse result = service.spreadsheets()
    .values()
    .append(spreadsheetId, range, body)
    .setValueInputOption("USER_ENTERED")
    .execute();

When I try to to add:

values.add(new ArrayList<Object>(ListOfMyTwoStrings));

I am getting the null error.

Update:

I have added:

List<Object> lists = new ArrayList<>();
lists.add(ListOne);
lists.add(ListTwo);

List<List<Object>> values = new ArrayList<>();
values.add(lists);

Where ListOne and ListTwo are List<String> with the data which I want to append in the sheet, but when I try to execute I am getting:

400 Bad Request
{
  "code":400,
  "errors":[
    {
      "domain":"global",
      "message":"Invalid values[1][0]: list_value {\n}\n",
      "reason":"badRequest"
    }
  ],
  "message":"Invalid values[1][0]: list_value {\n}\n",
  "status":"INVALID_ARGUMENT"
}

Can someone please help me to fix it?
Thank you and have a nice day!

Body:
Found solution, this is working for me:

List<Object> lists = new ArrayList<>();

lists.add("String 1");
lists.add("String 2");

List<List<Object>> values = new ArrayList<>();
values.add(lists);

This will append "String 1" to A1 and "String 2" to A2.

Thanks abielita for tip.


问:
XSLT Select all 3rd level children of current node by name
I am trying to use apply-templates to iterate over a particular child node from multiple similar parent nodes. Example below:

```<code><test_report
xmlns:gml="http://www.opengis.net/gml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<countries>
    <country name='sample1'>
        <education>
            <men>
                <literacyRates>25,36,43</literacyRates>
            </men>
        </education>
    </country>
    <country name='sample2'>
        <education>
            <men>
                <literacyRates>45,46,55,56</literacyRates>
            </men>
        </education>
    </country>
</countries>
</code>```

Now, I want to apply a template on all the literacyRates element that falls under the countries element. I tried the below XSL:

```<code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="countries">
            <xsl:call-template name="countries" />
</xsl:template>

<xsl:template name="countries" match="literacyRate">
        <xsl:call-template name="testoutput"><xsl:with-param name="list" select="." /> </xsl:call-template>
    ]
</xsl:template>

<xsl:template name="testoutput">
        <xsl:param name="list" select="."/>
    list=<xsl:value-of select="$list" />
</xsl:template>
</code>```

I would have expected the output line starting with list= to have appeared twice since we have two matches for literacyRate element, but that is not the case. Need some help here.

答:
Try the following script:

```<code><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="country//literacyRates">
    <xsl:text>list=</xsl:text>
    <xsl:value-of select="."/>
    <xsl:text>\n</xsl:text>
  </xsl:template>

</xsl:stylesheet>
</code>```

Or another solution, if you realy need to use apply-templates:

```<code><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="countries">
    <xsl:apply-templates select="//literacyRates"/>
  </xsl:template>

  <xsl:template match="literacyRates">
    <xsl:text>list=</xsl:text>
    <xsl:value-of select="."/>
    <xsl:text>\n</xsl:text>
  </xsl:template>

</xsl:stylesheet>
</code>```

Body:
I am trying to use apply-templates to iterate over a particular child node from multiple similar parent nodes. Example below:

<test_report
xmlns:gml="http://www.opengis.net/gml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<countries>
    <country name='sample1'>
        <education>
            <men>
                <literacyRates>25,36,43</literacyRates>
            </men>
        </education>
    </country>
    <country name='sample2'>
        <education>
            <men>
                <literacyRates>45,46,55,56</literacyRates>
            </men>
        </education>
    </country>
</countries>

Now, I want to apply a template on all the literacyRates element that falls under the countries element. I tried the below XSL:

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="countries">
            <xsl:call-template name="countries" />
</xsl:template>

<xsl:template name="countries" match="literacyRate">
        <xsl:call-template name="testoutput"><xsl:with-param name="list" select="." /> </xsl:call-template>
    ]
</xsl:template>

<xsl:template name="testoutput">
        <xsl:param name="list" select="."/>
    list=<xsl:value-of select="$list" />
</xsl:template>

I would have expected the output line starting with list= to have appeared twice since we have two matches for literacyRate element, but that is not the case. Need some help here.

Body:
Try the following script:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="country//literacyRates">
    <xsl:text>list=</xsl:text>
    <xsl:value-of select="."/>
    <xsl:text>&#xA;</xsl:text>
  </xsl:template>

</xsl:stylesheet>

Or another solution, if you realy need to use apply-templates:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="countries">
    <xsl:apply-templates select="//literacyRates"/>
  </xsl:template>

  <xsl:template match="literacyRates">
    <xsl:text>list=</xsl:text>
    <xsl:value-of select="."/>
    <xsl:text>&#xA;</xsl:text>
  </xsl:template>

</xsl:stylesheet>


问:
HTML/JS projects working independently, failing when combined
I would like to apologize for my ignorance on this subject in advance, I am very new to this! I have two projects that work independently, but when they are combined do not. The first project is a fullPage.js project, and the second a (cursor) parallax project. The working project files are as follows:

Cursor Parallax:

```<code><!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery Mouse Parallax Plugin Demo</title>

    <script src="https://code.jquery.com/jquery-1.11.3.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.17.0/TweenMax.min.js"></script>
    <script src="../jquery-parallax.js"></script>

    <script>
      $( document ).mousemove( function( e ) {
        $( '.background' ).parallax( -30, e );
        $( '.cloud1' )    .parallax( 10 , e );
        $( '.cloud2' )    .parallax( 20 , e );
        $( '.cloud3' )    .parallax( 30 , e );
      });
    </script>
    <script type="text/javascript">

      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-36251023-1']);
      _gaq.push(['_setDomainName', 'jqueryscript.net']);
      _gaq.push(['_trackPageview']);

      (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
      })();
    </script>

    <style>

      body {
        padding: 0; margin: 0;
        overflow: hidden;
      }

      .background {
        position: absolute; top: -10%; left: -10%;
        width: 120%; height: 120%;
        z-index: 1;
        font-family: Courier;
      }

      .cloud {
        position: absolute;
        margin-top: 100px;
        margin-left: 100px;
        width: auto; height: auto;
        z-index: 2;
        opacity: 0.8;
      }
    </style>
  </head>
  <body>
    <img src="imgs/background.jpg" alt="New York" class="background">

    <img src="imgs/BigCircles.png" alt="Clouds" class="cloud cloud1">
    <img src="imgs/mediumCircles.png" alt="Clouds" class="cloud cloud2">
    <img src="imgs/smallCircles.png" alt="Clouds" class="cloud cloud3">
  </body>
</html>
</code>```

https://pastebin.com/bDSnQ2Nz

(for easier viewing ^)

fullPage.js

```<code><!DOCTYPE html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello There.</title>

<link rel="stylesheet" type="text/css" href="../jquery.fullPage.css" />
<link rel="stylesheet" type="text/css" href="examples.css" />
<link href='https://fonts.googleapis.com/css?family=Six Caps' rel='stylesheet'>
<link href="//fonts.googleapis.com/css?family=Playfair+Display" rel='stylesheet' type="text/css" />
<style>
body{
  padding: 0; margin: 0;
  overflow: hidden;

}

.background {
  position: absolute;
  z-index: 1;
}

.cloud {
  position: absolute;
  margin-top: 100px;
  margin-left: 100px;
  width: auto; height: auto;
  z-index: 2;
  opacity: 0.8;
}
/* Style for our header texts
* --------------------------------------- */
h1{
  font-size: 50px;
  font-family: "Six Caps";
  margin:0;
  padding:0;

}
h2{
  font-size: 65px;
  color: #5b5a57;
  line-height: 100%;
  letter-spacing: 5px;
  margin: 0 0 18px 0;
  font-family: "Six Caps";
}
h3 {
  font-family: "Playfair Display";
  font-weight: 100;
  font-size: 1px;
  letter-spacing: 1px;

}
table {
  font-family: "Six Caps";
  font-size: 20px;
  letter-spacing: 2px;
  border-collapse: collapse;
  width: 80%;

}
td, th {
  text-align: left;
  padding: 0px;
  padding-top: 10px;
}

/* Common styles
* --------------------------------------- */
img{
  -webkit-transition: all 0.7s ease-out;
  -moz-transition: all 0.7s ease-out;
  -o-transition: all 0.7s ease-out;
  transition: all 0.7s ease-out;
}
.section{
  text-align:center;
  overflow:hidden;
}
.wrap{
  width: 1180px;
  height: 100%;
  margin-left: auto;
  margin-right: auto;
  position: relative;

}
.box{
  text-align: left;
  color: #5b5a57;
  font-size: 14px;
  line-height: 25px;
  font-family: "Playfair Display";

}

span {
  opacity: 0.5;
}

/* Section 0
* --------------------------------------- */
#section0{
  padding: 60px 0;
}
#section0 img{
  height: 100%;
  margin: 40px 0 0 0;
}

#container {
  width: 100%;
  height: 400px;
  background: url("imgs/backgroundImage.png");
}

/* Section 1
* --------------------------------------- */
#section1 img{
  position:absolute;
}
#section1 {
  background-image: url("imgs/backgroundImage.png");
  background-size: 100%;
}
#section1 .imgsContainer,
#staticImg .imgsContainer,
#section3 .imgsContainer{
  position: absolute;
  z-index: 1;
  left: 50%;
  display: block;
  margin-top: -288px;
  margin-left: -636px;
  width: 0;
  height: 0;

  -webkit-transition: all 1.2s ease-in-out;
  -moz-transition: all 1.2s ease-in-out;
  -o-transition: all 1.2s ease-in-out;
  transition: all 1.2s ease-in-out;
}

#section1.moveUp .imgsContainer{
  top: 50%;
}

#section1.moveDown .imgsContainer,
#staticImg .imgsContainer{
  top: 90%;
}

#section1.active .imgsContainer{
  top: 50%;
}

#iphone2{
  z-index: 100;
}
#iphone2.active{
  -webkit-transform: translate3d(+300px, 0px, 0px);
  -moz-transform: translate3d(+300px, 0px, 0px);
  -ms-transform:translate3d(+300px, 0px, 0px);
  transform: translate3d(+300px, 0px, 0px);
}

#section1 .box{
  top: 22%;
  left: 42%;
  position: absolute;
  width: 582px;

}

#iphone2 {
  top: -50px;
  left: -425px;
}

#iphone3 {
  top: -50px;
  left: 106px;
}

#staticImg{
  display: block;
  position: absolute;
  z-index: 1;
  top: 200%;
  left: 0;
  width: 100%;
  min-width: 980px;
  height: 100%;

  -webkit-transition: all 0.7s ease-out;
  -moz-transition: all 0.7s ease-out;
  -o-transition: all 0.7s ease-out;
  transition: all 0.7s ease-out;

  -webkit-backface-visibility: hidden;
  -webkit-perspective: 1000;
}
#staticImg.moveDown{
  -webkit-transform: translate3d(0, 100%, 0);
  -ms-transform: translate3d(0, 100%, 0);
  transform: translate3d(0, 100%, 0);
}
#staticImg.moveUp{

  -webkit-transform: translate3d(0, 0, 0);
  -ms-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);
}
#staticImg.moveDown .imgsContainer{
  top: 50%;
}
#staticImg.moveDown img{
  top: 155px;
}

#staticImg.active .imgsContainer{
  top: 50%;
}

#staticImg.active img{
  top: 487px;
}

.cloud {
  position: absolute;
  margin-top: 100px;
  margin-left: 100px;
  width: auto; height: auto;
  z-index: 150;
}

/* Section 2
* --------------------------------------- */
#section2 img{
  position:absolute;
}
#section2 .imgsContainer,
#staticImg .imgsContainer,
#section3 .imgsContainer{
  position: absolute;
  z-index: 1;
  left: 50%;
  display: block;
  margin-top: -288px;
  margin-left: -636px;
  width: 0;
  height: 0;

  -webkit-transition: all 1.2s ease-in-out;
  -moz-transition: all 1.2s ease-in-out;
  -o-transition: all 1.2s ease-in-out;
  transition: all 1.2s ease-in-out;
}

#section2.moveUp .imgsContainer{
  top: 50%;
}

#section2.moveDown .imgsContainer,
#staticImg .imgsContainer{
  top: 90%;
}

#section2.active .imgsContainer{
  top: 50%;
}

#section2 .box{
  top: 22%;
  left: 42%;
  position: absolute;
  width: 582px;
}

#iphone-yellow{
  top: -35px;
  left: -222px;
}

#iphone-red{
  top: -194px;
  left: 106px;
}

#iphone-blue{
  top: 320px;
  left: 448px;
}

#iphone-green{
  left: 106px;
  position:absolute;
}

#staticImg{
  display: block;
  position: absolute;
  z-index: 1;
  top: 200%;
  left: 0;
  width: 100%;
  min-width: 980px;
  height: 100%;

  -webkit-transition: all 0.7s ease-out;
  -moz-transition: all 0.7s ease-out;
  -o-transition: all 0.7s ease-out;
  transition: all 0.7s ease-out;

  -webkit-backface-visibility: hidden;
  -webkit-perspective: 1000;
}
#staticImg.moveDown{
  -webkit-transform: translate3d(0, 100%, 0);
  -ms-transform: translate3d(0, 100%, 0);
  transform: translate3d(0, 100%, 0);
}
#staticImg.moveUp{

  -webkit-transform: translate3d(0, 0, 0);
  -ms-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);
}
#staticImg.moveDown .imgsContainer{
  top: 50%;
}
#staticImg.moveDown img{
  top: 155px;
}

#staticImg.active .imgsContainer{
  top: 50%;
}

#staticImg.active img{
  top: 487px;
}

/* Overwriting fullPage.js tooltip color
* --------------------------------------- */
.fp-tooltip{
  color: #AAA;
}
#fp-nav span, .fp-slidesNav span{
  border-color: #AAA;
}
#fp-nav li .active span, .fp-slidesNav .active span{
  background: #AAA;
}

</style>

<!--[if IE]>
<script type="text/javascript">
var console = { log: function() {} };
</script>
<![endif]-->

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>

<script type="text/javascript" src="../jquery.fullPage.js"></script>
<script type="text/javascript" src="examples.js"></script>

<script type="text/javascript">
  $(document).ready(function() {
    $('#fullpage').fullpage({
      'verticalCentered': false,
      'css3': true,
      'sectionsColor': ['#F0F2F4', '#f7f3eb', '#fff', '#fff'],
      'navigation': true,
      'navigationPosition': 'right',
      'navigationTooltips': ['fullPage.js', 'Powerful', 'Amazing', 'Simple'],

      'afterLoad': function(anchorLink, index){
        if(index == 2){
          $('#iphone3, #iphone2, #iphone4').addClass('active');
        }
      },

      'onLeave': function(index, nextIndex, direction){
        if (index == 3 && direction == 'down'){
          $('.section').eq(index -1).removeClass('moveDown').addClass('moveUp');
        }
        else if(index == 3 && direction == 'up'){
          $('.section').eq(index -1).removeClass('moveUp').addClass('moveDown');
        }

        $('#staticImg').toggleClass('active', (index == 2 && direction == 'down' ) || (index == 4 && direction == 'up'));
        $('#staticImg').toggleClass('moveDown', nextIndex == 4);
        $('#staticImg').toggleClass('moveUp', index == 4 && direction == 'up');
      }
    });
  });
</script>

</head>

<body>
  <div id="fullpage">
    <div id="staticImg">
      <div class="imgsContainer">
        <img src="imgs/Mockup.png" alt="iphone" id="iphone-green" />
      </div>
    </div>

    <div class="section " id="section0">
      <h1>Hello There.</h1>
      <img src="imgs/iphone1.jpg" alt="iphone" />
    </div>
    <div class="section moveDown" id="section1">
      <div class="wrap">
        <div class="imgsContainer">
          <img src="imgs/iphone3.png" alt="iphone" id="iphone3" />
          <img src="imgs/iphone2.png" alt="iphone" id="iphone2" />
        </div>
        <div class="box">
          <h1>01.</h1>
          <h2>Some Text</h2>
          <span>Even more text</span>
          <table>
            <tr>
              <th>Role</th>
              <th>Year</th>
              <th>Compensation</th>
            </tr>
            <tr>
              <td>Sole</td>
              <td>2016-2017</td>
              <td>Volunteer</td>
            </tr>
          </table>

        </div>
      </div>
    </div>
    <div class="section moveDown" id="section2">
      <div class="wrap">
        <div class="imgsContainer">
          <img src="imgs/iphone-yellow.png" alt="iphone" id="iphone-yellow" />
          <img src="imgs/iphone-red.png" alt="iphone" id="iphone-red" />
          <img src="imgs/iphone-blue.png" alt="iphone" id="iphone-blue" />
        </div>

        <div class="box">
          <h2>Amazing stuff</h2>
          Combining <strong>fullPage.js</strong> with your own CSS styles and animations, you will be able to create something remarkable.

        </div>
      </div>
    </div>
  </div>
</body>

</html>
</code>```

(For easier viewing ^)

When I try to combine them, for some reason, they do not work. In particular when it seems to fail is when I add the:

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>

<script type="text/javascript" src="../jquery.fullPage.js"></script>
<script type="text/javascript" src="examples.js"></script>

<script type="text/javascript">
  $(document).ready(function() {
    $('#fullpage').fullpage({
      'verticalCentered': false,
      'css3': true,
      'sectionsColor': ['#F0F2F4', '#f7f3eb', '#fff', '#fff'],
      'navigation': true,
      'navigationPosition': 'right',
      'navigationTooltips': ['fullPage.js', 'Powerful', 'Amazing', 'Simple'],

      'afterLoad': function(anchorLink, index){
        if(index == 2){
          $('#iphone3, #iphone2, #iphone4').addClass('active');
        }
      },

      'onLeave': function(index, nextIndex, direction){
        if (index == 3 && direction == 'down'){
          $('.section').eq(index -1).removeClass('moveDown').addClass('moveUp');
        }
        else if(index == 3 && direction == 'up'){
          $('.section').eq(index -1).removeClass('moveUp').addClass('moveDown');
        }

        $('#staticImg').toggleClass('active', (index == 2 && direction == 'down' ) || (index == 4 && direction == 'up'));
        $('#staticImg').toggleClass('moveDown', nextIndex == 4);
        $('#staticImg').toggleClass('moveUp', index == 4 && direction == 'up');
      }
    });
  });
</script>
</code>```

To the parallax folder, it "breaks" the parallax movement. Any help you could provide would be very much appreciated!! Thank you all!

答:
When combining these two separate pages you should not put jQuery library twice. Include jQuery library only one. Any jQuery plugin should go after including jQuery library. If you put any jQuery plugin before jQuery library itself, it won't work.
Hope this helps.</p>

Body:
I would like to apologize for my ignorance on this subject in advance, I am very new to this! I have two projects that work independently, but when they are combined do not. The first project is a fullPage.js project, and the second a (cursor) parallax project. The working project files are as follows:

Cursor Parallax:

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery Mouse Parallax Plugin Demo</title>

https://pastebin.com/bDSnQ2Nz

(for easier viewing ^)

fullPage.js

<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello There.</title>

<link rel="stylesheet" type="text/css" href="../jquery.fullPage.css" />
<link rel="stylesheet" type="text/css" href="examples.css" />
<link href='https://fonts.googleapis.com/css?family=Six Caps' rel='stylesheet'>
<link href="//fonts.googleapis.com/css?family=Playfair+Display" rel='stylesheet' type="text/css" />

Hello There.

01.

Some Text

          Even more text

              Role
              Year
              Compensation

              Sole
              2016-2017
              Volunteer

Amazing stuff

          Combining fullPage.js with your own CSS styles and animations, you will be able to create something remarkable.

(For easier viewing ^)

When I try to combine them, for some reason, they do not work. In particular when it seems to fail is when I add the:

To the parallax folder, it "breaks" the parallax movement. Any help you could provide would be very much appreciated!! Thank you all!


问:
Laravel chmod(/var/dev/project/storage/oauth-public.key): Operation failed: Operation not permitted
After I updated the following packages I got an error that the oauth-public.key file couldn't be found.

Package operations: 1 install, 2 updates, 0 removals

Updating laravel/framework (v5.4.27 => v5.4.28): Downloading (100%)

    Installing defuse/php-encryption (v2.1.0): Downloading (100%)

    Updating league/oauth2-server (5.1.3 => 5.1.4): Downloading (100%)

Firstly I deleted the two oauth- files in project/storage and then executed this command: php artisan passport:install to generate new oauth- files.

Now I get the following error when trying to access an api route.

(1/1) ErrorException
  chmod(/var/dev/project/storage/oauth-public.key): Operation failed: Operation not permitted

Stack trace

in CryptKey.php (line 51)

at HandleExceptions->handleError(2, 'chmod(/var/dev/project/storage/oauth-public.key): Operation failed: Operation not permitted', '/var/dev/project/vendor/league/oauth2-server/src/CryptKey.php', 51, array('keyPath' => 'file:///var/dev/project/storage/oauth-public.key', 'passPhrase' => null, 'keyPathPerms' => '644'))

at chmod('file:///var/dev/project/storage/oauth-public.key', 384)
  in CryptKey.php (line 51)

at CryptKey->__construct('file:///var/dev/project/storage/oauth-public.key')
  in ResourceServer.php (line 50)

File permissions

```<code>-rw-r--r-- user:user oauth-private.key
-rw-r--r-- user:user oauth-public.key
</code>```

Update 1

I found out that oauth Libaray introduced a security fix. Oauth V5 Security Improvements

Version 5.1.4 is a backwards compatbile with other 5.1.x releases.

You will notice in your server logs a message like this:

You must set the encryption key going forward to improve the security of this library - see this page for more information https://oauth2.thephpleague.com/v5-security-improvements/

To supress this notice once you have instantiated an instance of \League\OAuth2\Server\AuthorizationServer you should call the setEncryptionKey() method passing in at least 32 bytes of random data.

You can generate this using base64_encode(random_bytes(32)). Alternatively if you’re using a framework such as Laravel which has a encryption key already generated you can pass in that (in the case of Laravel use env('APP_KEY')).

Problem is that the maintainer of Laravel Passport has to fix this.

Update 2

After I removed the vendor folder and executed composer install again I get still the same error.

答:
Finally! I found the solution. ( CentOs )

```<code>chown apache:apache oauth-public.key
chown apache:apache oauth-private.key
</code>```

At first you need to find the username of your server:
This will return the username you need

```<code>ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1
</code>```

For me it's apache

Body:
After I updated the following packages I got an error that the oauth-public.key file couldn't be found.

Package operations: 1 install, 2 updates, 0 removals

Updating laravel/framework (v5.4.27 => v5.4.28): Downloading (100%)

    Installing defuse/php-encryption (v2.1.0): Downloading (100%)

    Updating league/oauth2-server (5.1.3 => 5.1.4): Downloading (100%)

Firstly I deleted the two oauth- files in project/storage and then executed this command: php artisan passport:install to generate new oauth- files.

Now I get the following error when trying to access an api route.

(1/1) ErrorException
  chmod(/var/dev/project/storage/oauth-public.key): Operation failed: Operation not permitted

Stack trace

in CryptKey.php (line 51)

at HandleExceptions->handleError(2, 'chmod(/var/dev/project/storage/oauth-public.key): Operation failed: Operation not permitted', '/var/dev/project/vendor/league/oauth2-server/src/CryptKey.php', 51, array('keyPath' => 'file:///var/dev/project/storage/oauth-public.key', 'passPhrase' => null, 'keyPathPerms' => '644'))

at chmod('file:///var/dev/project/storage/oauth-public.key', 384)
  in CryptKey.php (line 51)

at CryptKey->__construct('file:///var/dev/project/storage/oauth-public.key')
  in ResourceServer.php (line 50)

File permissions

-rw-r--r-- user:user oauth-private.key
-rw-r--r-- user:user oauth-public.key

Update 1

I found out that oauth Libaray introduced a security fix. Oauth V5 Security Improvements

Version 5.1.4 is a backwards compatbile with other 5.1.x releases.

You will notice in your server logs a message like this:

You must set the encryption key going forward to improve the security of this library - see this page for more information https://oauth2.thephpleague.com/v5-security-improvements/

To supress this notice once you have instantiated an instance of \League\OAuth2\Server\AuthorizationServer you should call the setEncryptionKey() method passing in at least 32 bytes of random data.

You can generate this using base64_encode(random_bytes(32)). Alternatively if you’re using a framework such as Laravel which has a encryption key already generated you can pass in that (in the case of Laravel use env('APP_KEY')).

Problem is that the maintainer of Laravel Passport has to fix this.

Update 2

After I removed the vendor folder and executed composer install again I get still the same error.

Body:
Finally! I found the solution. ( CentOs )

chown apache:apache oauth-public.key
chown apache:apache oauth-private.key

At first you need to find the username of your server:
This will return the username you need

ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1

For me it's apache


问:
ActionCable unsubscribe callback not working when iOS client send "unsubscribe"
Remote iOS client successfully connects to me, send subscribe command (it works fine), but on "unsubscribe" command I get next error:

```
Unsubscribing from channel: {"channel":"Assessor::StationChannel", "station_id": 1}
Could not execute command from {"command"=>"unsubscribe", "identifier"=>"{\"channel\":\"Assessor::StationChannel\", \"station_id\": 1}"}) [NoMethodError - undefined method `unsubscribe_from_channel' for nil:NilClass]: /app/vendor/bundle/ruby/2.2.0/gems/actioncable-5.0.0/lib/action_cable/connection/subscriptions.rb:44:in `remove_subscription' | /app/vendor/bundle/ruby/2.2.0/gems/actioncable-5.0.0/lib/action_cable/connection/subscriptions.rb:40:in `remove' | /app/vendor/bundle/ruby/2.2.0/gems/actioncable-5.0.0/lib/action_cable/connection/subscriptions.rb:16:in `execute_command' | /app/vendor/bundle/ruby/2.2.0/gems/actioncable-5.0.0/lib/action_cable/connection/base.rb:88:in `dispatch_websocket_message' | /app/vendor/bundle/ruby/2.2.0/gems/actioncable-5.0.0/lib/action_cable/server/worker.rb:58:in `block in invoke' ```

Subscribe message format:

```
{"command": "subscribe", "identifier": "{\"channel\":\"Assessor::StationChannel\", \"station_id\": 1}"} ```

Unsubscribe message format:

```
{"command": "unsubscribe", "identifier": "{\"channel\":\"Assessor::StationChannel\", \"station_id\": 1}"} ```

I cannot reproduce this problem on localhost, so maybe somebody can help me?

答:
App.cable.subscriptions.create({channel: "RoomChannel", room_id: 2}) returns a subscription object you have to pass that into the remove function

var subscription = App.cable.subscriptions.create({channel: "RoomChannel", room_id: 2});

Then later

App.cable.subscriptions.remove(subscription);

Body:
Remote iOS client successfully connects to me, send subscribe command (it works fine), but on "unsubscribe" command I get next error:

Unsubscribing from channel: {"channel":"Assessor::StationChannel", "station_id": 1}
Could not execute command from {"command"=>"unsubscribe", "identifier"=>"{\"channel\":\"Assessor::StationChannel\", \"station_id\": 1}"}) [NoMethodError - undefined method `unsubscribe_from_channel' for nil:NilClass]: /app/vendor/bundle/ruby/2.2.0/gems/actioncable-5.0.0/lib/action_cable/connection/subscriptions.rb:44:in `remove_subscription' | /app/vendor/bundle/ruby/2.2.0/gems/actioncable-5.0.0/lib/action_cable/connection/subscriptions.rb:40:in `remove' | /app/vendor/bundle/ruby/2.2.0/gems/actioncable-5.0.0/lib/action_cable/connection/subscriptions.rb:16:in `execute_command' | /app/vendor/bundle/ruby/2.2.0/gems/actioncable-5.0.0/lib/action_cable/connection/base.rb:88:in `dispatch_websocket_message' | /app/vendor/bundle/ruby/2.2.0/gems/actioncable-5.0.0/lib/action_cable/server/worker.rb:58:in `block in invoke'

Subscribe message format:

{"command": "subscribe", "identifier": "{\"channel\":\"Assessor::StationChannel\", \"station_id\": 1}"}

Unsubscribe message format:

{"command": "unsubscribe", "identifier": "{\"channel\":\"Assessor::StationChannel\", \"station_id\": 1}"}

I cannot reproduce this problem on localhost, so maybe somebody can help me?


问:
Parallel path in SVN overwriting each other's files
I have two paths, let's say:

root\folder1
root\folder2

While the folder names are different, both contain files with the same names, just some of their contents differ. I have all the paths and all their files added to SVN. Now, I make a change to root\folder1\fileA and commit it. If I try to make a change to root\folder2\fileA, I get an error citing I need to update first. When I do update, my local copy is overwritten with the changes I just made to fileA under root\folder1. And this works vice versa.

I don't know why this is happening. I even deleted root\folder2 and recreated it and re-added it to SVN. But the same thing is still happening...

答:
This is what happens when you copy a folder with a .svn folder in it with windows explorer. Since they have the same information in .svn, they point to the same location on the server even if the local folders have different names.

To keep TortoiseSVN informed of such copies so that it can do the correct thing, you should always do move/copy/rename operations with the TortoiseSVN context menu or by right-click dragging and selecting a TortoiseSVN action.

In the next major release of SVN (1.7), the metadata will be centralized in one big .svn folder at the root of your working copy. Hopefully that will reduce the opportunity to mess up working copies with copy/move/rename operations in windows explorer.


问:
How do I create a brand new hive file from a reg file?
I have a .dbreg file that contains a textual representation of a bunch of registry entries. How do I convert that into a .hiv file without having to load it into my machine's registry?

I'm kind of creating a package that is run in a sort of fake Windows environment (kind of like Wine), and it wants a bunch of .hiv files. Merging the text registry entries into an existing .hiv file that's sitting in some random location (i.e. not the main system one) would also be an option.

The reg utility doesn't really seem to have a way to work with an arbitrary .hiv file, aside from the load, and save commands, which seem to be just about creating and restoring backups.

There must be a way to do this.

Edit: I had a misconception about what reg load does. It basically 'mounts' (in Unix parlance) a hive file into the existing registry database at a specific point in the key hierarchy.

答: Basically, you have to use a trick to create an empty hiv file. This MSDN blog entry contains a PowerShell script that creates an empty regsitry hive file. Then you can use reg load (which basically 'mounts' a hive file into the existing registry key hierarchy) and reg import to import the dbreg file into it, then reg unload.