问:
Html change div content
I'm having a struggle. It's not one of these questions how to do it but more like how to do that better.

What im trying to achieve

Also I want to load rest into content when clicking on nav's

My question is what's "proper" or correct approach to do it without making a mess in a code.

How I done it so far

```<code><li><a class="navelement" data-url="resources/web/loadit.html" href="#">navbar A</a></li>
</code>```

And used jquery

```<code>$(document).ready(function(){
$('.navelement').click(function(e){
    e.preventDefault;
    $('#content').load($(this).data('url'));
});
$('.navelement:eq(0)').click();
</code>```

});

I like this approach but I need to execute ajax rest call each time I change navbar.

Second approach I can think off is to hide/show in css div's. Any tip will be appreaciated.

答:
Both of your approaches are correct but decision making points would be how frequently the data in div is changed and how much bandwidth will it cost to keep all divs loaded with data.

If data in div is frequently changed then I would suggest to use approach 2, i.e. load all divs once and hide and show the required one. This will improve the performance as ajax calls over network has time latency. Using approach 2 in this case will improve UI experience. This is also called as eager loading.

But in case if you have heavy data and user need not require all the data you have loaded then it will cause unnecessary loading of all divs which could consume considerable bandwidth and also cause long initial loading of page. In this case approach 1 is recommended. This is called as lazy loading.

Title: Html change div content

Body:
I'm having a struggle. It's not one of these questions how to do it but more like how to do that better.

What im trying to achieve

Also I want to load rest into content when clicking on nav's

My question is what's "proper" or correct approach to do it without making a mess in a code.

How I done it so far

navbar A

And used jquery

$(document).ready(function(){
$('.navelement').click(function(e){
    e.preventDefault;
    $('#content').load($(this).data('url'));
});
$('.navelement:eq(0)').click();

});

I like this approach but I need to execute ajax rest call each time I change navbar.

Second approach I can think off is to hide/show in css div's. Any tip will be appreaciated.


来源: stackexchange

问:
How to refresh a page with Turbolinks
I understand that I can call the following code on Turbolinks 5 but it changes the scroll position. Is there a way to call Turbolinks to refresh the page and not change the scroll position?

```<code>Turbolinks.visit(location.toString());
</code>```

This will do what I want, but was hoping to use Turbolinks

```<code> window.location.reload()
</code>```

答:
Store the current scroll position before calling visit, then when the page loads, scroll to that stored position. Resetting the stored scroll position to null ensures that subsequent page loads will not scroll to an old position. One possible implementation might be:

```<code>var reloadWithTurbolinks = (function () {
  var scrollPosition

  function reload () {
    scrollPosition = [window.scrollX, window.scrollY]
    Turbolinks.visit(window.location.toString(), { action: 'replace' })
  }

  document.addEventListener('turbolinks:load', function () {
    if (scrollPosition) {
      window.scrollTo.apply(window, scrollPosition)
      scrollPosition = null
    }
  })

  return reload
})()
</code>```

Then you can call reloadWithTurbolinks().

To prevent the page from flickering as it scrolls from the top to the desired position, add the no-preview cache directive in the page's head:

```<code><meta name="turbolinks-cache-control" content="no-preview">
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to refresh a page with Turbolinks

Body:
I understand that I can call the following code on Turbolinks 5 but it changes the scroll position. Is there a way to call Turbolinks to refresh the page and not change the scroll position?

Turbolinks.visit(location.toString());

This will do what I want, but was hoping to use Turbolinks

 window.location.reload()

Body:
Store the current scroll position before calling visit, then when the page loads, scroll to that stored position. Resetting the stored scroll position to null ensures that subsequent page loads will not scroll to an old position. One possible implementation might be:

var reloadWithTurbolinks = (function () {
  var scrollPosition

  function reload () {
    scrollPosition = [window.scrollX, window.scrollY]
    Turbolinks.visit(window.location.toString(), { action: 'replace' })
  }

  document.addEventListener('turbolinks:load', function () {
    if (scrollPosition) {
      window.scrollTo.apply(window, scrollPosition)
      scrollPosition = null
    }
  })

  return reload
})()

Then you can call reloadWithTurbolinks().

To prevent the page from flickering as it scrolls from the top to the desired position, add the no-preview cache directive in the page's head:

<meta name="turbolinks-cache-control" content="no-preview">


问:
Is it possible to run OAT/ELF files from command line on Android?
I know it's possible to run pure dex bytecode on an Android command line via /system/bin/dalvikvm, but I wonder if it's possible to run oat files from command line?

Since it's an ELF shared object file it has to be started via zygote I guess. Maybe it's possible with app_process, but I don't know if and how.

Can anyone help me out?

答: An .oat file in itself is not a complete application. boot.oat that contains the initialized heap is also needed for the app process and so is boot.art. Zygote, as you said the running app_process already has these pages. Zygote is running waiting for requests on the socket /dev/socket/zygote to receive app launch requests. You can look around in AOSP source as to what information is written on this socket by launcher to launch the app and how that information communicates about the  app's .oat file.</p>


问:
Angular-cli test coverage all files
I am running the following command to unit test and generate code code coverage report.

```<code>ng test --code-coverage
</code>```

It is  writing code coverage report in coverage folder.

I need to see the coverage of the whole project and not just the file for which there are tests.

karma.conf.js

```<code>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', 'angular-cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-jasmine-html-reporter'),
      require('karma-chrome-launcher'),
      require('karma-remap-istanbul'),
      require('angular-cli/plugins/karma'),
      require('karma-coverage'),
      require('karma-sourcemap-loader')

    ],
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['angular-cli']
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    remapIstanbulReporter: {
        reports: {
          html: 'coverage',
        lcovonly: './coverage/coverage.lcov'
      }
    },
    angularCli: {
      config: './angular-cli.json',
      environment: 'dev'
    },
    reporters: config.angularCli && config.angularCli.codeCoverage
              ? ['progress', 'karma-remap-istanbul']
              : ['progress', 'kjhtml'],
    coverageReporter: {
      includeAllSources: true
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};
</code>```

答:
Use below given command to check code coverage:</p>

```<code>ng test -cc
</code>```

Title: Angular-cli test coverage all files

Body:
I am running the following command to unit test and generate code code coverage report.

ng test --code-coverage

It is  writing code coverage report in coverage folder.

I need to see the coverage of the whole project and not just the file for which there are tests.

karma.conf.js

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', 'angular-cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-jasmine-html-reporter'),
      require('karma-chrome-launcher'),
      require('karma-remap-istanbul'),
      require('angular-cli/plugins/karma'),
      require('karma-coverage'),
      require('karma-sourcemap-loader')

    ],
    files: [
      { pattern: './src/test.ts', watched: false }
    ],
    preprocessors: {
      './src/test.ts': ['angular-cli']
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    remapIstanbulReporter: {
        reports: {
          html: 'coverage',
        lcovonly: './coverage/coverage.lcov'
      }
    },
    angularCli: {
      config: './angular-cli.json',
      environment: 'dev'
    },
    reporters: config.angularCli && config.angularCli.codeCoverage
              ? ['progress', 'karma-remap-istanbul']
              : ['progress', 'kjhtml'],
    coverageReporter: {
      includeAllSources: true
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

Body:
Use below given command to check code coverage:

ng test -cc


问:
MySQLdb error when using cursor.execute()
I am using python and specifically MySQLdb to fill a database, although a code that was working until recently is throwing up an error after moving servers at work:

The code is:

```<code>cursor.execute("""SELECT Entry, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P FROM evaluation""")

result = cursor.fetchall()

for record in result:
    codeno=int(str(record[15]))
    status, progress, reprocessing = RepStatus_new.get_status(code=codeno, proj_tag=str(record[16]),cache_dir="cache", prod_type="g1")
    cursor.execute("""UPDATE evaluation SET M=%s WHERE A LIKE %s""",(progress, int(str(record[15]))))
</code>```

and the error that comes up is:

```<code>File "mySQLtest.py", line 165, in <module>
    cursor.execute("""UPDATE evaluation SET M=%s WHERE A LIKE %s""",(progress, int(str(record[15]))))
  File "/usr/lib64/python2.5/site-packages/MySQLdb/cursors.py", line 166, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib64/python2.5/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1205, 'Lock wait timeout exceeded; try restarting transaction')
</code>```

I am not sure where this is going wrong, as I said this code worked until recently.  If anyone has any suggestions they would be much appreciated! (I replaced variables with letters to aid read-ability!)

The database is connecting correctly, as I can output the "result" after cursor.fetchall()

Thanks in advance

答:
It's a quick fix, but changing innodb_lock_wait_timeout might temporarily defer the "Lock wait timeout exceeded" issue. See doc.

Any chance the MySQL version, engine(s), or config's changed when you "moved servers"?

Reading the results of SHOW ENGINE INNODB STATUS would alert you to any recent locking issues.

Last time I seen this when I "moved servers", it was because of conflicting/duplicate scripts/crons trying to hit the same tables.

At any rate, you might want to push this over to serverfault.

ContentLicense: CC BY-SA 2.5

Body:
I am using python and specifically MySQLdb to fill a database, although a code that was working until recently is throwing up an error after moving servers at work:

The code is:

cursor.execute("""SELECT Entry, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P FROM evaluation""")

result = cursor.fetchall()

for record in result:
    codeno=int(str(record[15]))
    status, progress, reprocessing = RepStatus_new.get_status(code=codeno, proj_tag=str(record[16]),cache_dir="cache", prod_type="g1")
    cursor.execute("""UPDATE evaluation SET M=%s WHERE A LIKE %s""",(progress, int(str(record[15]))))

and the error that comes up is:

File "mySQLtest.py", line 165, in <module>
    cursor.execute("""UPDATE evaluation SET M=%s WHERE A LIKE %s""",(progress, int(str(record[15]))))
  File "/usr/lib64/python2.5/site-packages/MySQLdb/cursors.py", line 166, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib64/python2.5/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1205, 'Lock wait timeout exceeded; try restarting transaction')

I am not sure where this is going wrong, as I said this code worked until recently.  If anyone has any suggestions they would be much appreciated! (I replaced variables with letters to aid read-ability!)

The database is connecting correctly, as I can output the "result" after cursor.fetchall()

Thanks in advance


问:
How to make multiple fragments appear partially in an activity when the corresponding button is pressed
I want to make something like this (photos). When a button is pressed (in this app the red button that says "suchen") a fragment in a portion of the main activity screen is shown. And every time I press an other button, the corresponding activity is shown in the same activity.

So when each
button is pressed you can see the corresponding fragment for this button in the portion of the screen where the layout for the fragment is. I did it like this:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/first_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/second_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/third_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/forth_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Relativelayout
        android:layout_below="@id/first_btn"
        android:id="@+id/first_fragment_container"
        android:layout_width="300dp"
        android:layout_height="250dp">

        <fragment
            android:id="@+id/fragment1"
            android:name="com.example.ulrich.kitchentimer.fragments.FirstFragmentActivity"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout="@layout/first_fragment_activity" />

    </Relativelayout>

    <Relativelayout
        android:layout_below="@id/first_btn"
        android:id="@+id/second_fragment_container"
        android:layout_width="300dp"
        android:layout_height="250dp">

    <fragment
        android:id="@+id/fragment2"
        android:name="com.example.fragments.SecondFragmentActivity"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/second_fragment_activity" />
    </Relativelayout>

    <Relativelayout
        android:layout_below="@id/first_btn"
        android:id="@+id/third_fragment_container"
        android:layout_width="300dp"
        android:layout_height="250dp">

    <fragment
        android:id="@+id/fragment3"
        android:name="com.example.fragments.ThirdFragmentActivity"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/third_fragment_activity" />
    </Relativelayout>

    <Relativelayout
        android:layout_below="@id/first_btn"
        android:id="@+id/forth_fragment_container"
        android:layout_width="300dp"
        android:layout_height="250dp">

    <fragment
        android:id="@+id/fragment4"
        android:name="com.example.fragments.ForthFragmentActivity"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/forth_fragment_activity" />
    </Relativelayout>

</LinearLayout>
</code>```

As you can see in my code I use four buttons and every button opens an other fragment but at the same place on the main activity. So I have four layouts to contain each of the four fragments. I set each layout to be invisible in the XML code and when each button is pressed to open the corresponding fragment I set the layout to be visible in the Java code. So I have four layout containers in the main activity that are hidden and only shown when the corresponding button is pressed.  Is this the right way? Is there a right way?
Thank you in advanced!!!

答:
That's the one way you did to achieve your goal, but that's not the good way. You don't have to make four fragment instead you can have one fragment and replace it when you press the other button. If you want to replace fragments

```<code>// Create fragment and give it an argument specifying the article it should show
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);

FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();
</code>```

Note: When you remove or replace a fragment and add the transaction to the back stack, the fragment that is removed is stopped (not destroyed). If the user navigates back to restore the fragment, it restarts. If you do not add the transaction to the back stack, then the fragment is destroyed when removed or replaced. To allow the user to navigate backward through the fragment transactions, you must call addToBackStack() before you commit the FragmentTransaction.

Body:
I want to make something like this (photos). When a button is pressed (in this app the red button that says "suchen") a fragment in a portion of the main activity screen is shown. And every time I press an other button, the corresponding activity is shown in the same activity.

So when each
button is pressed you can see the corresponding fragment for this button in the portion of the screen where the layout for the fragment is. I did it like this:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/first_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/second_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/third_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/forth_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Relativelayout
        android:layout_below="@id/first_btn"
        android:id="@+id/first_fragment_container"
        android:layout_width="300dp"
        android:layout_height="250dp">

        <fragment
            android:id="@+id/fragment1"
            android:name="com.example.ulrich.kitchentimer.fragments.FirstFragmentActivity"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout="@layout/first_fragment_activity" />

    </Relativelayout>

    <Relativelayout
        android:layout_below="@id/first_btn"
        android:id="@+id/second_fragment_container"
        android:layout_width="300dp"
        android:layout_height="250dp">

    <fragment
        android:id="@+id/fragment2"
        android:name="com.example.fragments.SecondFragmentActivity"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/second_fragment_activity" />
    </Relativelayout>

    <Relativelayout
        android:layout_below="@id/first_btn"
        android:id="@+id/third_fragment_container"
        android:layout_width="300dp"
        android:layout_height="250dp">

    <fragment
        android:id="@+id/fragment3"
        android:name="com.example.fragments.ThirdFragmentActivity"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/third_fragment_activity" />
    </Relativelayout>

    <Relativelayout
        android:layout_below="@id/first_btn"
        android:id="@+id/forth_fragment_container"
        android:layout_width="300dp"
        android:layout_height="250dp">

    <fragment
        android:id="@+id/fragment4"
        android:name="com.example.fragments.ForthFragmentActivity"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/forth_fragment_activity" />
    </Relativelayout>

</LinearLayout>

As you can see in my code I use four buttons and every button opens an other fragment but at the same place on the main activity. So I have four layouts to contain each of the four fragments. I set each layout to be invisible in the XML code and when each button is pressed to open the corresponding fragment I set the layout to be visible in the Java code. So I have four layout containers in the main activity that are hidden and only shown when the corresponding button is pressed.  Is this the right way? Is there a right way?
Thank you in advanced!!!

Body:
That's the one way you did to achieve your goal, but that's not the good way. You don't have to make four fragment instead you can have one fragment and replace it when you press the other button. If you want to replace fragments

// Create fragment and give it an argument specifying the article it should show
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);

FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

Note: When you remove or replace a fragment and add the transaction to the back stack, the fragment that is removed is stopped (not destroyed). If the user navigates back to restore the fragment, it restarts. If you do not add the transaction to the back stack, then the fragment is destroyed when removed or replaced. To allow the user to navigate backward through the fragment transactions, you must call addToBackStack() before you commit the FragmentTransaction.


问:
how to extract data from namedtuple in file handling in python
Having trouble extracting data from namedtuple in file handling in python.
It shows property object at --- location

```<code>from collections import namedtuple

filename=input("Enter name of file ")
Data=namedtuple('Data',['name','id','balance'])

def write():
    file=open(filename,'a')
    name=input("Enter name ")
    idee=input("Enter ID ")
    bal=input("Enter balance ")
    data=Data(name,idee,bal)
    file.write(str(data))
    file.close()

def read():
    file=open(filename,'r')
    for line in file:
        print(Data.name,"\t",Data.id,"\t",Data.balance,"\n")

write()
write()
read()
</code>```

What should I do to extract data in data.name?

答:
You can just do:

```<code>print("%s\t%d\t%s\n" % line)
</code>```

to print the contents of the namedtuple. The official documentation may not be very obvious, but here is a good tutorial to understand named tuples

Body:
Having trouble extracting data from namedtuple in file handling in python.
It shows property object at --- location

from collections import namedtuple

filename=input("Enter name of file ")
Data=namedtuple('Data',['name','id','balance'])

def write():
    file=open(filename,'a')
    name=input("Enter name ")
    idee=input("Enter ID ")
    bal=input("Enter balance ")
    data=Data(name,idee,bal)
    file.write(str(data))
    file.close()

def read():
    file=open(filename,'r')
    for line in file:
        print(Data.name,"\t",Data.id,"\t",Data.balance,"\n")

write()
write()
read()

What should I do to extract data in data.name?

Body:
You can just do:

print("%s\t%d\t%s\n" % line)

to print the contents of the namedtuple. The official documentation may not be very obvious, but here is a good tutorial to understand named tuples


问:
When to use JWT
Since JWT is self-contained, it can be used for stateless authentication. If we want to revoke the token, then we need to lookup somewhere, in database, in memcache. But that is against stateless.

So, JWT can be used only when we need stateless and don't need to revoke the token?

答:
Well you could update a user record in your database to prohibit someone from logging in entirely (and thus tell your app to ignore the user's tokens), but I don't think there's a way of revoking individual tokens from a user (unless you gave your tokens individual IDs and stored the IDs in your database--but as you point out, that kinda seems like it would largely defeat the point of JWT's).

Update

This article talks about JWT revocation (as well as links to some other sources):
https://dadario.com.br/revoking-json-web-tokens/

Title: When to use JWT


问:
Make awk keep ending whitespace
I have a file list with two columns. I need to remove the first column and keep a list of filenames. If I happen to have a file that ends with a space, eg "some file ", the space is removed by awk.

Example with file "input" (notice the space at the end of "some file ")

```<code>abc some file
def some other file
</code>```

Running

```<code>cat input | awk '{$1=""; print substr($0, 2)}' > output
</code>```

will produce the file output

```<code>some file
some other file
</code>```

where "some file " is now "some file" resulting in a non existent file when processing the file list.

Any portable solution is appreciated :)

[EDIT] Tried to simplify the example above in order to make it more clear, but in fact there are more columns so some solutions may not apply.

Actual file is an rsync --list-only output:

```<code>drwxr-xr-x        4096 2017/06/04 11:24:21 .
drwxr-xr-x      234234 2017/06/04 11:24:19 some file
drwxr-xr-x     1341212 2017/06/04 11:24:19 some other file
</code>```

The column that shows filesizes may expand so removing a fixed amount of trailing characters will lead to errors.

Filenames can indeed contain paths and multiple spaces.

Example test file (keep in mind that filesize may vary, so the second column might increase in size):

```<code>drwxr-xr-x        4096 2017/06/04 11:24:21 .
drwxr-xr-x        4096 2017/06/04 11:24:19 another
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one/bites
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one/bites/ de_dust
-rw-r--r--           0 2017/06/04 11:24:19 another/one/bites/ de_dust/ 2017/06/04 11:24:19 Iron Rhapsody
drwxr-xr-x        4096 2017/06/04 11:24:19 phantom of
drwxr-xr-x        4096 2017/06/04 11:24:19 phantom of /the opera
-rw-r--r--           0 2017/06/04 11:24:19 phantom of /the opera/Bohemian Maiden
</code>```

[/EDIT]

答:
I suggest with GNU sed:

```<code>sed -r 's/^.* [0-9/]{10} [0-9:]{8} //' input
</code>```

Output:

```
.
some file
some other file
```

Title: Make awk keep ending whitespace

Body:
I have a file list with two columns. I need to remove the first column and keep a list of filenames. If I happen to have a file that ends with a space, eg "some file ", the space is removed by awk.

Example with file "input" (notice the space at the end of "some file ")

abc some file
def some other file

Running

cat input | awk '{$1=""; print substr($0, 2)}' > output

will produce the file output

some file
some other file

where "some file " is now "some file" resulting in a non existent file when processing the file list.

Any portable solution is appreciated :)

[EDIT] Tried to simplify the example above in order to make it more clear, but in fact there are more columns so some solutions may not apply.

Actual file is an rsync --list-only output:

drwxr-xr-x        4096 2017/06/04 11:24:21 .
drwxr-xr-x      234234 2017/06/04 11:24:19 some file
drwxr-xr-x     1341212 2017/06/04 11:24:19 some other file

The column that shows filesizes may expand so removing a fixed amount of trailing characters will lead to errors.

Filenames can indeed contain paths and multiple spaces.

Example test file (keep in mind that filesize may vary, so the second column might increase in size):

drwxr-xr-x        4096 2017/06/04 11:24:21 .
drwxr-xr-x        4096 2017/06/04 11:24:19 another
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one/bites
drwxr-xr-x        4096 2017/06/04 11:24:19 another/one/bites/ de_dust
-rw-r--r--           0 2017/06/04 11:24:19 another/one/bites/ de_dust/ 2017/06/04 11:24:19 Iron Rhapsody
drwxr-xr-x        4096 2017/06/04 11:24:19 phantom of
drwxr-xr-x        4096 2017/06/04 11:24:19 phantom of /the opera
-rw-r--r--           0 2017/06/04 11:24:19 phantom of /the opera/Bohemian Maiden

[/EDIT]

Body:
I suggest with GNU sed:

sed -r 's/^.* [0-9/]{10} [0-9:]{8} //' input

Output:

.
some file
some other file


问:
How to compute the "15% of the time" randomness?
I'm looking for a decent, elegant method of calculating this simple logic.

Right now I can't think of one, it's spinning my head.

I am required to do some action only 15% of the time.

I'm used to "50% of the time" where I just mod the milliseconds of the current time and see if it's odd or even, but I don't think that's elegant.

How would I elegantly calculate "15% of the time"?  Random number generator maybe?

Pseudo-code or any language are welcome.

Hope this is not subjective, since I'm looking for the "smartest" short-hand method of doing that.

Thanks.

答:
Here's one approach that combines randomness and a guarantee that eventually you get a positive outcome in a predictable range:

Have a target (15 in your case), a counter (initialized to 0), and a flag (initialized to false).

```<code>Accept a request.
If the counter is 15, reset the counter and the flag.
If the flag is true, return negative outcome.
Get a random true or false based on one of the methods described in other answers, but use a probability of 1/(15-counter).
Increment counter
If result is true, set flag to true and return a positive outcome. Else return a negative outcome.
Accept next request
</code>```

This means that the first request has probability of 1/15 of return positive, but by the 15th request, if no positive result has been returned, there's a probability of 1/1 of a positive result.

Body:
Here's one approach that combines randomness and a guarantee that eventually you get a positive outcome in a predictable range:

Have a target (15 in your case), a counter (initialized to 0), and a flag (initialized to false).

Accept a request.
If the counter is 15, reset the counter and the flag.
If the flag is true, return negative outcome.
Get a random true or false based on one of the methods described in other answers, but use a probability of 1/(15-counter).
Increment counter
If result is true, set flag to true and return a positive outcome. Else return a negative outcome.
Accept next request

This means that the first request has probability of 1/15 of return positive, but by the 15th request, if no positive result has been returned, there's a probability of 1/1 of a positive result.


问:
How do I prevent the warning "unicode constant cast with potential data loss" in Lazarus?
I'm trying to assign the Tricolon Unicode character #$205D as the caption to a button in a Lazarus Windows program like this:

```<code>MyButton.Caption := #$205D;
</code>```

It works, the button displays the Tricolon fine, but the compiler emits the warning "Warning: Unicode constant cast with potential data loss".

How do I correctly assign the Tricolon character to the caption of an LCL control to get rid of the warning?

答:
LCL uses UTF8 encoding but #$205D is UTF16 character constant. So use UTF8 encoded constants instead:</p>

```<code>const
    CTricolon = #$E2#$81#$9D;
    //CTricolon = '⁝'; // Also works fine if using character(s) as is in the source

...

    MyButton.Caption := CTricolon;
</code>```

Body:
I'm trying to assign the Tricolon Unicode character #$205D as the caption to a button in a Lazarus Windows program like this:

MyButton.Caption := #$205D;

It works, the button displays the Tricolon fine, but the compiler emits the warning "Warning: Unicode constant cast with potential data loss".

How do I correctly assign the Tricolon character to the caption of an LCL control to get rid of the warning?

Body:
LCL uses UTF8 encoding but #$205D is UTF16 character constant. So use UTF8 encoded constants instead:

const
    CTricolon = #$E2#$81#$9D;
    //CTricolon = '⁝'; // Also works fine if using character(s) as is in the source

...

    MyButton.Caption := CTricolon;


问:
NGINX server_name not work
I ecountered the following issue about server_name in nginx and might need your help. This is my default.cnf resided in /etc/nginx/conf.d/

```<code>server {
    listen       80;
    server_name  planner.dev;

    root   /var/www/planner.dev/src;
    index  index.php index.html index.htm;
    ...
}
</code>```

And I have a helloworld html file in /var/www/planner.dev/src
However, only localhost will run, planner.dev will not run.

```<code>$ curl planner.dev
curl: (6) Couldn't resolve host 'planner.dev'
</code>```

答:
The problem is most likely in the system hosting the server, than in the server itself.

I was running an Nginx server on Debian and happened to have the same issue, which I solved by editing the /etc/hosts file likeso:

```<code>127.0.0.1       localhost
127.0.0.1       vacuum
127.0.0.1       <mywebsite>.localhost
</code>```

More about the hosts file.

Title: NGINX server_name not work

Body:
I ecountered the following issue about server_name in nginx and might need your help. This is my default.cnf resided in /etc/nginx/conf.d/

server {
    listen       80;
    server_name  planner.dev;

    root   /var/www/planner.dev/src;
    index  index.php index.html index.htm;
    ...
}

And I have a helloworld html file in /var/www/planner.dev/src
However, only localhost will run, planner.dev will not run.

$ curl planner.dev
curl: (6) Couldn't resolve host 'planner.dev'

Body:
The problem is most likely in the system hosting the server, than in the server itself.

I was running an Nginx server on Debian and happened to have the same issue, which I solved by editing the /etc/hosts file likeso:

127.0.0.1       localhost
127.0.0.1       vacuum
127.0.0.1       <mywebsite>.localhost

More about the hosts file.


问:
C# xmlserialization SoapEnvelope namespace formating
Im having issues building a soapenvelope in c#. Here is an example of desired field in output

```<code><xml version="1.0">
<Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="id1">
<Body d2p1:type="Body" xmlns:d2p1="http://www.w3.org/2001/XMLSchema-instance">
<test xmlns:q1="http://www.w3.org/2001/XMLSchema" d2p1:type="q1:string">hello
</test>
</Body>
</Envelope>
</code>```

However when I serialize the class i get this

```<code><xml version="1.0">
<Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="id1">
<test href="#id2" />
</Envelope>
<Body id="id2" d2p1:type="Body" xmlns:d2p1="http://www.w3.org/2001/XMLSchema-instance">
<test xmlns:q1="http://www.w3.org/2001/XMLSchema" d2p1:type="q1:string">hello
</test>
</Body>
</code>```

As you can see the body is outside the envelope.

Here is the class
    namespace soaptest
    {

```<code>public class Envelope
{
    public Body test;
}

public class Body
{
    public string test;
}

}
</code>```

And here is how Im serializing

```<code>Envelope test = new Envelope();
MemoryStream ms = new MemoryStream();

test.test = new soaptest.Body();
test.test.test = "hello";

XmlWriter writer = new XmlTextWriter(ms, Encoding.UTF8);

SoapReflectionImporter importer = new SoapReflectionImporter();
XmlTypeMapping map = importer.ImportTypeMapping(typeof(Envelope));
XmlSerializer serializer = new XmlSerializer(map);
writer.WriteStartElement("xml version=\"1.0\"");
serializer.Serialize(writer, test);

ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string output = sr.ReadToEnd();
</code>```

Now I can do away with all attributes atm.  I just need it to be

```<code> <?xml version="1.0"?>
 <Envelope>
 <Body>
 //body elements
 </Body>
 </Envelope>
</code>```

So how can I get the serializer to do this?  Or is there a good SoapEnvelope Library for .net?

答:
Why so complex?

Model:

```<code>public class Envelope
{
    public Body Body;
}
public class Body
{
    [XmlElement("test")]
    public string Test;
}
</code>```

Usage:

```<code>Envelope envelope = new Envelope();
envelope.Body = new Body();
envelope.Body.Test = "hello";

XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
serializer.Serialize(Console.Out, envelope);
</code>```

Result:

```<code><?xml version="1.0" encoding="cp866"?>
<Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Body>
    <test>hello</test>
  </Body>
</Envelope>
</code>```

Body:
Im having issues building a soapenvelope in c#. Here is an example of desired field in output

<xml version="1.0">
<Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="id1">

<test xmlns:q1="http://www.w3.org/2001/XMLSchema" d2p1:type="q1:string">hello
</test>

</Envelope>

However when I serialize the class i get this

<xml version="1.0">
<Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="id1">
<test href="#id2" />
</Envelope>

<test xmlns:q1="http://www.w3.org/2001/XMLSchema" d2p1:type="q1:string">hello
</test>

As you can see the body is outside the envelope.

Here is the class
    namespace soaptest
    {

public class Envelope
{
    public Body test;
}

public class Body
{
    public string test;
}

}

And here is how Im serializing

Envelope test = new Envelope();
MemoryStream ms = new MemoryStream();

test.test = new soaptest.Body();
test.test.test = "hello";

XmlWriter writer = new XmlTextWriter(ms, Encoding.UTF8);

SoapReflectionImporter importer = new SoapReflectionImporter();
XmlTypeMapping map = importer.ImportTypeMapping(typeof(Envelope));
XmlSerializer serializer = new XmlSerializer(map);
writer.WriteStartElement("xml version=\"1.0\"");
serializer.Serialize(writer, test);

ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string output = sr.ReadToEnd();

Now I can do away with all attributes atm.  I just need it to be

 <?xml version="1.0"?>
 <Envelope>

 //body elements

 </Envelope>

So how can I get the serializer to do this?  Or is there a good SoapEnvelope Library for .net?

Body:
Why so complex?

Model:

public class Envelope
{
    public Body Body;
}
public class Body
{
    [XmlElement("test")]
    public string Test;
}

Usage:

Envelope envelope = new Envelope();
envelope.Body = new Body();
envelope.Body.Test = "hello";

XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
serializer.Serialize(Console.Out, envelope);

Result:

<?xml version="1.0" encoding="cp866"?>
<Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Body>
    <test>hello</test>
  </Body>
</Envelope>


问:
How do I use Python's map function with sklearn's preprocessing.scale?
I am trying to use a function (preprocessing.scale) on a list of data. I am new to mapreduce/parallelism in Python - I would like to process this on a large list of data to improve performance.

Example:

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

Using the syntax:

```<code>list(map(preprocessing.scale, X))
</code>```

I get this error:

```<code>TypeError: Singleton array array(1.0) cannot be considered a valid collection.
</code>```

I think that is because of the return type of the function, but I am not sure how to fix this. Any help would be greatly appreciated!

答:
You don't need/want to use map function as it does for loop under the hood.

Almost all sklearn methods are vectorized and they accept list-alike objects (lists, numpy arrays, etc.) and this would work much-much faster compared to map(...) approach

Demo:

```<code>In [121]: from sklearn.preprocessing import scale

In [122]: X = [1,2,3,4]

In [123]: scale(X)
Out[123]: array([-1.34164079, -0.4472136 ,  0.4472136 ,  1.34164079])
</code>```

the same demo using numpy array:

```<code>In [39]: x = np.array(X)

In [40]: x
Out[40]: array([1, 2, 3, 4])

In [41]: scale(x)
DataConversionWarning: Data with input dtype int32 was converted to float64 by the scale function.
  warnings.warn(msg, _DataConversionWarning)
Out[41]: array([-1.34164079, -0.4472136 ,  0.4472136 ,  1.34164079])
</code>```

it expects float dtype, so we can easily convert our numpy array to float dtype on the fly:

```<code>In [42]: scale(x.astype('float64'))
Out[42]: array([-1.34164079, -0.4472136 ,  0.4472136 ,  1.34164079])
</code>```

Body:
I am trying to use a function (preprocessing.scale) on a list of data. I am new to mapreduce/parallelism in Python - I would like to process this on a large list of data to improve performance.

Example:

X = [1,2,3,4]

Using the syntax:

list(map(preprocessing.scale, X))

I get this error:

TypeError: Singleton array array(1.0) cannot be considered a valid collection.

I think that is because of the return type of the function, but I am not sure how to fix this. Any help would be greatly appreciated!

Body:
You don't need/want to use map function as it does for loop under the hood.

Almost all sklearn methods are vectorized and they accept list-alike objects (lists, numpy arrays, etc.) and this would work much-much faster compared to map(...) approach

Demo:

In [121]: from sklearn.preprocessing import scale

In [122]: X = [1,2,3,4]

In [123]: scale(X)
Out[123]: array([-1.34164079, -0.4472136 ,  0.4472136 ,  1.34164079])

the same demo using numpy array:

In [39]: x = np.array(X)

In [40]: x
Out[40]: array([1, 2, 3, 4])

In [41]: scale(x)
DataConversionWarning: Data with input dtype int32 was converted to float64 by the scale function.
  warnings.warn(msg, _DataConversionWarning)
Out[41]: array([-1.34164079, -0.4472136 ,  0.4472136 ,  1.34164079])

it expects float dtype, so we can easily convert our numpy array to float dtype on the fly:

In [42]: scale(x.astype('float64'))
Out[42]: array([-1.34164079, -0.4472136 ,  0.4472136 ,  1.34164079])


问:
use formControlName with something like
I have a dynamic form which shows multiple datasets I've got via REST.
The user will edit this dataset and then later just submit it to get it sent back to the server.

The form is built dynamically with FormBuilder.array() and looped through via formArrayName + *ngFor in my template.

One property of each dataset is a "last updated" information I want to display along with the editable data in my form. Right now I use an <input> field with disabled attribute - but this looks kinda ugly.

When I used a model driven form i just had a {{mf.lastUpdated}} part for each dataset which just displayed the date nicely.

Now that I want to use reactive Forms, I can't set formControlName in a  Tag - so how am I supposed to display the information without any input possibility?

Edit

Plunker: http://plnkr.co/edit/JZIjXH9CagJNHLxK64fG?p=preview

The "last Used" field - I want to display it as "text only" without an input-tag

答:
A possible solution without the need of workaround is to use the attribute readonly for the inputs and then style the target field as desired (inline style below just for sake of the example).

```<code> <div>
     <label>last used</label>
     <input type="text" formControlName="_lastUsed" readonly style="border:0">
</div>
</code>```

Title: use formControlName with something like <span>

Body:
A possible solution without the need of workaround is to use the attribute readonly for the inputs and then style the target field as desired (inline style below just for sake of the example).

 <div>
     <label>last used</label>
     <input type="text" formControlName="_lastUsed" readonly style="border:0">
</div>


问:
Connect an Android app to localhost without internet connection
i have an Android app that needs to access offline a MySQL database that's hosted on my localhost (i'm using WampServer).
i can't use USB tethering or port forwarding because my laptop won't have internet connection too.
what can i do? </p>

答: You can setup wifi, connect your system which contains server and your android device to same wifi. Assign a static IP to your server system and let your android connect to that server's MySql through the IP you assigned. Basically it is nothing much different then your web api and db hosted on cloud server and your android application  connect to that cloud using either the domain or ip.</p>


问:
Get CSV from Tensorflow summaries
I have some very large tensorflow summaries. If these are plotted using tensorboard, I can download CSV files from them.

However, plotting these using tensorboard would take a very long time. I found in the docs that there is a method for reading the summary directly in Python. This method is summary_iterator and can be used as follows:

```<code>import tensorflow as tf

for e in tf.train.summary_iterator(path to events file):
    print(e)
</code>```

Can I use this method to create CSV files directly? If so, how can I do this? This would save a lot of time.

答:
One possible way of doing it would be like this:

```<code>from tensorboard.backend.event_processing import event_accumulator
import numpy as np
import pandas as pd
import sys

def create_csv(inpath, outpath):
    sg = {event_accumulator.COMPRESSED_HISTOGRAMS: 1,
          event_accumulator.IMAGES: 1,
          event_accumulator.AUDIO: 1,
          event_accumulator.SCALARS: 0,
          event_accumulator.HISTOGRAMS: 1}
    ea = event_accumulator.EventAccumulator(inpath, size_guidance=sg)
    ea.Reload()
    scalar_tags = ea.Tags()['scalars']
    df = pd.DataFrame(columns=scalar_tags)
    for tag in scalar_tags:
        events = ea.Scalars(tag)
        scalars = np.array(map(lambda x: x.value, events))
        df.loc[:, tag] = scalars
    df.to_csv(outpath)

if __name__ == '__main__':
    args = sys.argv
    inpath = args[1]
    outpath = args[2]
    create_csv(inpath, outpath)
</code>```

Please note, this code will load the entire event file into memory, so best to run this on a cluster. For information about the sg argument of the EventAccumulator, see this SO question.

An additional improvement might be to not only store the value of each scalar, but also the step.

Note The code snippet was updated for recent versions of TF.  For TF < 1.1 use the following import instead:

```<code>from tensorflow.tensorboard.backend.event_processing import event_accumulator as eva
</code>```

Title: Get CSV from Tensorflow summaries

Body:
I have some very large tensorflow summaries. If these are plotted using tensorboard, I can download CSV files from them.

However, plotting these using tensorboard would take a very long time. I found in the docs that there is a method for reading the summary directly in Python. This method is summary_iterator and can be used as follows:

import tensorflow as tf

for e in tf.train.summary_iterator(path to events file):
    print(e)

Can I use this method to create CSV files directly? If so, how can I do this? This would save a lot of time.

Body:
One possible way of doing it would be like this:

from tensorboard.backend.event_processing import event_accumulator
import numpy as np
import pandas as pd
import sys

def create_csv(inpath, outpath):
    sg = {event_accumulator.COMPRESSED_HISTOGRAMS: 1,
          event_accumulator.IMAGES: 1,
          event_accumulator.AUDIO: 1,
          event_accumulator.SCALARS: 0,
          event_accumulator.HISTOGRAMS: 1}
    ea = event_accumulator.EventAccumulator(inpath, size_guidance=sg)
    ea.Reload()
    scalar_tags = ea.Tags()['scalars']
    df = pd.DataFrame(columns=scalar_tags)
    for tag in scalar_tags:
        events = ea.Scalars(tag)
        scalars = np.array(map(lambda x: x.value, events))
        df.loc[:, tag] = scalars
    df.to_csv(outpath)

if __name__ == '__main__':
    args = sys.argv
    inpath = args[1]
    outpath = args[2]
    create_csv(inpath, outpath)

Please note, this code will load the entire event file into memory, so best to run this on a cluster. For information about the sg argument of the EventAccumulator, see this SO question.

An additional improvement might be to not only store the value of each scalar, but also the step.

Note The code snippet was updated for recent versions of TF.  For TF < 1.1 use the following import instead:

from tensorflow.tensorboard.backend.event_processing import event_accumulator as eva

ContentLicense: CC BY-SA 4.0


问:
Relu Performing worse than sigmoid?
I use sigmoid on all the layers and output and get a final error rate of 0.00012 but when I use Relu which is theoretically Better , i get the worst results possible. can anyone explain why is this happening? I am using a very simple 2 layer implementation code available on 100 of websites but still am giving it below,

```<code>import numpy as np
#test
#avg(nonlin(np.dot(nonlin(np.dot([0,0,1],syn0)),syn1)))
#returns list >> [predicted_output, confidence]
def nonlin(x,deriv=False):#Sigmoid
    if(deriv==True):
        return x*(1-x)

    return 1/(1+np.exp(-x))

def relu(x, deriv=False):#RELU
    if (deriv == True):
        for i in range(0, len(x)):
            for k in range(len(x[i])):
                if x[i][k] > 0:
                    x[i][k] = 1
                else:
                    x[i][k] = 0
        return x
    for i in range(0, len(x)):
        for k in range(0, len(x[i])):
            if x[i][k] > 0:
                pass  # do nothing since it would be effectively replacing x with x
            else:
                x[i][k] = 0
    return x

X = np.array([[0,0,1],
            [0,0,0],
            [0,1,1],
            [1,0,1],
            [1,0,0],
            [0,1,0]])

y = np.array([[0],[1],[0],[0],[1],[1]])

np.random.seed(1)

# randomly initialize our weights with mean 0
syn0 = 2*np.random.random((3,4)) - 1
syn1 = 2*np.random.random((4,1)) - 1

def avg(i):
        if i > 0.5:
            confidence = i
            return [1,float(confidence)]
        else:
            confidence=1.0-float(i)
            return [0,confidence]
for j in xrange(500000):

    # Feed forward through layers 0, 1, and 2
    l0 = X
    l1 = nonlin(np.dot(l0,syn0Performing))
    l2 = nonlin(np.dot(l1,syn1))
    #print 'this is',l2,'\n'
    # how much did we miss the target value?
    l2_error = y - l2
    #print l2_error,'\n'
    if (j% 100000) == 0:
        print "Error:" + str(np.mean(np.abs(l2_error)))
        print syn1

    # in what direction is the target value?
    # were we really sure? if so, don't change too much.
    l2_delta = l2_error*nonlin(l2,deriv=True)

    # how much did each l1 value contribute to the l2 error (according to the weights)?
    l1_error = l2_delta.dot(syn1.T)

    # in what direction is the target l1?
    # were we really sure? if so, don't change too much.
    l1_delta = l1_error * nonlin(l1,deriv=True)

    syn1 += l1.T.dot(l2_delta)
    syn0 += l0.T.dot(l1_delta)
print "Final Error:" + str(np.mean(np.abs(l2_error)))
def p(l):
        return avg(nonlin(np.dot(nonlin(np.dot(l,syn0)),syn1)))
</code>```

So p(x) is the predicton function after traning , where x is an 1 x 3 matrix of input values.

答:
Why do you say it's theoretically better? In majority of applications ReLU has proven better, but it doesn't mean it is universally better. Your example is very simple and the input scaled between [0,1], same as the output. That's exactly where I would expect sigmoid to perform well. You don't meet sigmoids in hidden layers in practice due to the vanishing gradient problem and some other issues with large networks, but it's hardly an issue for you.

Also, if by any chance you were using the ReLU derivative, you were missing an 'else' in your code. Your derivative would be simple overwritten.

Just as a refresher, here's the definition of ReLU:

f(x)=max(0,x)

... meaning it can blow your activation to infinite. You want to avoid having ReLU on the last (output) layer.

On a side note, whenever possible you should take advantage of vectorised operations:

```<code>def relu(x, deriv=False):#RELU
    if (deriv == True):
        mask = x > 0
        x[mask] = 1
        x[~mask] = 0
    else: # HERE YOU WERE MISSING "ELSE"
        return np.maximum(0,x)
</code>```

Yes, it's much faster then if / else you were doing.

Title: Relu Performing worse than sigmoid?

Body:
I use sigmoid on all the layers and output and get a final error rate of 0.00012 but when I use Relu which is theoretically Better , i get the worst results possible. can anyone explain why is this happening? I am using a very simple 2 layer implementation code available on 100 of websites but still am giving it below,

import numpy as np
#test
#avg(nonlin(np.dot(nonlin(np.dot([0,0,1],syn0)),syn1)))
#returns list >> [predicted_output, confidence]
def nonlin(x,deriv=False):#Sigmoid
    if(deriv==True):
        return x*(1-x)

    return 1/(1+np.exp(-x))

def relu(x, deriv=False):#RELU
    if (deriv == True):
        for i in range(0, len(x)):
            for k in range(len(x[i])):
                if x[i][k] > 0:
                    x[i][k] = 1
                else:
                    x[i][k] = 0
        return x
    for i in range(0, len(x)):
        for k in range(0, len(x[i])):
            if x[i][k] > 0:
                pass  # do nothing since it would be effectively replacing x with x
            else:
                x[i][k] = 0
    return x

X = np.array([[0,0,1],
            [0,0,0],
            [0,1,1],
            [1,0,1],
            [1,0,0],
            [0,1,0]])

y = np.array([[0],[1],[0],[0],[1],[1]])

np.random.seed(1)

# randomly initialize our weights with mean 0
syn0 = 2*np.random.random((3,4)) - 1
syn1 = 2*np.random.random((4,1)) - 1

def avg(i):
        if i > 0.5:
            confidence = i
            return [1,float(confidence)]
        else:
            confidence=1.0-float(i)
            return [0,confidence]
for j in xrange(500000):

    # Feed forward through layers 0, 1, and 2
    l0 = X
    l1 = nonlin(np.dot(l0,syn0Performing))
    l2 = nonlin(np.dot(l1,syn1))
    #print 'this is',l2,'\n'
    # how much did we miss the target value?
    l2_error = y - l2
    #print l2_error,'\n'
    if (j% 100000) == 0:
        print "Error:" + str(np.mean(np.abs(l2_error)))
        print syn1

    # in what direction is the target value?
    # were we really sure? if so, don't change too much.
    l2_delta = l2_error*nonlin(l2,deriv=True)

    # how much did each l1 value contribute to the l2 error (according to the weights)?
    l1_error = l2_delta.dot(syn1.T)

    # in what direction is the target l1?
    # were we really sure? if so, don't change too much.
    l1_delta = l1_error * nonlin(l1,deriv=True)

    syn1 += l1.T.dot(l2_delta)
    syn0 += l0.T.dot(l1_delta)
print "Final Error:" + str(np.mean(np.abs(l2_error)))
def p(l):
        return avg(nonlin(np.dot(nonlin(np.dot(l,syn0)),syn1)))

So p(x) is the predicton function after traning , where x is an 1 x 3 matrix of input values.

Body:
Why do you say it's theoretically better? In majority of applications ReLU has proven better, but it doesn't mean it is universally better. Your example is very simple and the input scaled between [0,1], same as the output. That's exactly where I would expect sigmoid to perform well. You don't meet sigmoids in hidden layers in practice due to the vanishing gradient problem and some other issues with large networks, but it's hardly an issue for you.

Also, if by any chance you were using the ReLU derivative, you were missing an 'else' in your code. Your derivative would be simple overwritten.

Just as a refresher, here's the definition of ReLU:

f(x)=max(0,x)

... meaning it can blow your activation to infinite. You want to avoid having ReLU on the last (output) layer.

On a side note, whenever possible you should take advantage of vectorised operations:

def relu(x, deriv=False):#RELU
    if (deriv == True):
        mask = x > 0
        x[mask] = 1
        x[~mask] = 0
    else: # HERE YOU WERE MISSING "ELSE"
        return np.maximum(0,x)

Yes, it's much faster then if / else you were doing.


问:
How to download stock data from Matlab
I have downloaded the last version I found (18/04/2017) of hist_stock_data.

It does not get the data from Yahoo (returning zero status).

Any way to fix this?

Any alternative for downloading stock data from Matlab?

答:
Have you tried to use the fetch function?

```<code>d = fetch(c,s) returns data for all fields from the Yahoo! website for the indicated security.
</code>```

Note:  This function does not support retrieving multiple securities at once. You must fetch a single security at a time.

Title: How to download stock data from Matlab

Body:
Have you tried to use the fetch function?

d = fetch(c,s) returns data for all fields from the Yahoo! website for the indicated security.

Note:  This function does not support retrieving multiple securities at once. You must fetch a single security at a time.


问:
Finding all numbers in a array with top frequency?
I am trying to find out all the numbers with maximum frequency. i.e If maximum frequency is 5 then, I need all numbers that occurred 5 times in a array.

let us consider following example of array:

1 8 7 8 9 2 1 9 6 4 3 5

Here, Most frequent numbers are 8, 1, 9 with highest frequency of 2. My expected output is something like this:

```<code>8 => 2
1 => 2
9 => 2
</code>```

In my project, I am trying to find out most frequent numbers and least frequent numbers. Here I want just most frequent numbers.

I have generated 1000 random numbers similar to my project scenario and have calculated distinct numbers and then their occurrence.

```<code>    int n=100;
    int N=1000;

    int data[] = new int[N];
    Set<Integer> set = new HashSet<Integer>();

    Random random = new Random();

    for(int i=0;i<N;i++){
        int  number = random.nextInt(n);
        data[i] = number;
        set.add(number);
    }

    int frequency[] = new int[set.size()];
    Integer[] distinct = set.toArray(new Integer[set.size()]);

    for (int j=0;j<set.size();j++){
        int count=0;
        for(int k=0;k<N;k++){
            if(distinct[j]==data[k]){
                count = count+1;
            }
        }
        frequency[j] = count;
    }
</code>```

After calculating frequencies of each number, I have calculated numbers with most frequencies using answer from here which is optimized one.

```<code>    int max = Integer.MIN_VALUE;
    List<Integer> vals = new ArrayList<>();

    for (int q=0; q < frequency.length; ++q) {

        if (frequency[q] == max) {
            vals.add(q);
        }

        else if (frequency[q] > max) {
            vals.clear();
            vals.add(q);
            max = frequency[q];
        }
    }

    for(int num : vals){
        System.out.println(distinct[num]+" => "+frequency[num]);
    }
</code>```

Here, Loop in first code making whole process slower. This is only part of large code and sample test case.

I want to make the process faster since there may be large elements in the array in real case.

Anyone have way to optimize those loops ?
 or
some other way to get the result ?

Any kind of help is appreciated.

答:
I would use Java8 stream for it. In some cases you can even use parallel stream to improve performance. Here is how I would do that:

```<code> public static void main(String[] args) {
    List<Integer> integers = Arrays.asList(1, 8, 7, 8, 9, 2, 1, 9, 6, 4, 3, 5);
    //Here we have statistics of frequency for all numbers
    LinkedHashMap<Integer, Integer> statistics = integers.stream().distinct()
        .collect(Collectors.toMap(Function.identity(), number -> Collections.frequency(integers, number)))
        .entrySet().stream().sorted(Collections.reverseOrder(Comparator.comparing(Map.Entry::getValue)))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1, o2) -> o1, LinkedHashMap::new));
    //Calculate max frequency
    Integer maxFrequency = statistics.entrySet().stream()
        .max(Comparator.comparingInt(Map.Entry::getValue))
        .map(Map.Entry::getValue).orElse(null);
    //Collect max frequent numbers to a map
    Map<Integer, Integer> topFrequentNumbers = statistics.entrySet().stream()
        .filter(o -> o.getValue().equals(maxFrequency))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    //Print
    topFrequentNumbers.forEach((number, frequency) -> System.out.println(number + " => " + frequency));
}
</code>```

Output:

```<code>1 => 2
8 => 2
9 => 2
</code>```

As I mentioned, you can play with parallel streams and extracting some pieces to improve performance.

Body:
I am trying to find out all the numbers with maximum frequency. i.e If maximum frequency is 5 then, I need all numbers that occurred 5 times in a array.

let us consider following example of array:

1 8 7 8 9 2 1 9 6 4 3 5

Here, Most frequent numbers are 8, 1, 9 with highest frequency of 2. My expected output is something like this:

8 => 2
1 => 2
9 => 2

In my project, I am trying to find out most frequent numbers and least frequent numbers. Here I want just most frequent numbers.

I have generated 1000 random numbers similar to my project scenario and have calculated distinct numbers and then their occurrence.

    int n=100;
    int N=1000;

    int data[] = new int[N];
    Set<Integer> set = new HashSet<Integer>();

    Random random = new Random();

    for(int i=0;i<N;i++){
        int  number = random.nextInt(n);
        data[i] = number;
        set.add(number);
    }

    int frequency[] = new int[set.size()];
    Integer[] distinct = set.toArray(new Integer[set.size()]);

    for (int j=0;j<set.size();j++){
        int count=0;
        for(int k=0;k<N;k++){
            if(distinct[j]==data[k]){
                count = count+1;
            }
        }
        frequency[j] = count;
    }

After calculating frequencies of each number, I have calculated numbers with most frequencies using answer from here which is optimized one.

    int max = Integer.MIN_VALUE;
    List<Integer> vals = new ArrayList<>();

    for (int q=0; q < frequency.length; ++q) {

        if (frequency[q] == max) {
            vals.add(q);
        }

        else if (frequency[q] > max) {
            vals.clear();
            vals.add(q);
            max = frequency[q];
        }
    }

    for(int num : vals){
        System.out.println(distinct[num]+" => "+frequency[num]);
    }

Here, Loop in first code making whole process slower. This is only part of large code and sample test case.

I want to make the process faster since there may be large elements in the array in real case.

Anyone have way to optimize those loops ?
 or
some other way to get the result ?

Any kind of help is appreciated.

Body:
I would use Java8 stream for it. In some cases you can even use parallel stream to improve performance. Here is how I would do that:

 public static void main(String[] args) {
    List<Integer> integers = Arrays.asList(1, 8, 7, 8, 9, 2, 1, 9, 6, 4, 3, 5);
    //Here we have statistics of frequency for all numbers
    LinkedHashMap<Integer, Integer> statistics = integers.stream().distinct()
        .collect(Collectors.toMap(Function.identity(), number -> Collections.frequency(integers, number)))
        .entrySet().stream().sorted(Collections.reverseOrder(Comparator.comparing(Map.Entry::getValue)))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1, o2) -> o1, LinkedHashMap::new));
    //Calculate max frequency
    Integer maxFrequency = statistics.entrySet().stream()
        .max(Comparator.comparingInt(Map.Entry::getValue))
        .map(Map.Entry::getValue).orElse(null);
    //Collect max frequent numbers to a map
    Map<Integer, Integer> topFrequentNumbers = statistics.entrySet().stream()
        .filter(o -> o.getValue().equals(maxFrequency))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    //Print
    topFrequentNumbers.forEach((number, frequency) -> System.out.println(number + " => " + frequency));
}

Output:

1 => 2
8 => 2
9 => 2

As I mentioned, you can play with parallel streams and extracting some pieces to improve performance.


问:
How to navigate the JSON hierarchy with PHP?
I am building a weather application that decodes a JSON file (found here: http://api.openweathermap.org/data/2.5/forecast?q=Helsinki&appid=77f5e3fbc99649054660f82f871220f4&units=metric)

The problem I am running into is navigating the JSON file in my PHP code to correctly select the tempature.

I need to do list->1->main->temp but this pulls up a number error in PHP. How do I correctly set the navigation?

```<code>echo "<form id='searchform' method='POST' action='https://projekt2-sofiamusick.c9users.io/wordpress/prognos/'>
Search: <input type='text' name='searchquery' placeholder='Search the forum' />
<input class='sendbutton_search' type='submit' name='search' value='>>' />
</form>";

if (isset($_POST['search'])){

$cityz = $_POST['searchquery'];
echo "<br>";
echo "<div id=apithing>";
$data = file_get_contents("http://api.openweathermap.org/data/2.5/forecast?q=$cityz&appid=77f5e3fbc99649054660f82f871220f4&units=metric");
$jsonObject = json_decode($data, JSON_NUMERIC_CHECK);
json_encode( array( 'list' => (int)$jsonObject ) );
$list = $jsonObject->list;
$number = $jsonObject->'1';
$mains = $jsonObject->main;
echo $mains;
</code>```

答:
If you use JSON_NUMERIC_CHECK, your data present as array.

If you want get first element, just use $jsonObject['list'][0]

Without JSON_NUMERIC_CHECK, your data present as stdClass, and first element you can get with $jsonObject->list{0}

Body:
I am building a weather application that decodes a JSON file (found here: http://api.openweathermap.org/data/2.5/forecast?q=Helsinki&appid=77f5e3fbc99649054660f82f871220f4&units=metric)

The problem I am running into is navigating the JSON file in my PHP code to correctly select the tempature.

I need to do list->1->main->temp but this pulls up a number error in PHP. How do I correctly set the navigation?

echo "<form id='searchform' method='POST' action='https://projekt2-sofiamusick.c9users.io/wordpress/prognos/'>
Search: <input type='text' name='searchquery' placeholder='Search the forum' />
<input class='sendbutton_search' type='submit' name='search' value='>>' />
</form>";

if (isset($_POST['search'])){

$cityz = $_POST['searchquery'];
echo "
";
echo "
";
$data = file_get_contents("http://api.openweathermap.org/data/2.5/forecast?q=$cityz&appid=77f5e3fbc99649054660f82f871220f4&units=metric");
$jsonObject = json_decode($data, JSON_NUMERIC_CHECK);
json_encode( array( 'list' => (int)$jsonObject ) );
$list = $jsonObject->list;
$number = $jsonObject->'1';
$mains = $jsonObject->main;
echo $mains;


问:
how to tell what kind of asn1 i'm receiving
Im slowly getting my head around asn1 notation. Encoding asn1 from an struct seems to quite easy.However decoding asn1 to my application is harder. I want to know if I have an application that receives data on say udp port 600, and this can be a number of asn1 structures, how do i tell which asn1 structure i should be decoding into?

So, when i receive asn1 packets, do we first determine it's type and the decode it depending on its type?

or does my asn1 compiler handle of this for me?

finding examples of this stuff is hard...even for google ;-) .

A tutorial that outlines the building of simple network server using asn1 would be awesome!

答:
ASN.1 corresponds roughly to the Presentation Layer of the OSI seven-layer cake. It relies on the Application Layer to determine what types of information is being exchanged between the endpoints. So, there's no universal header or identifier that would indicate which protocol or syntax is being presented by the ASN.1 stream. That could be implied by the port number, or made explicit by an additional protocol layer (e.g., HTTP.)

EDIT (responding to your comment): The ASN.1 standard defines four "classes" of tags: UNIVERSAL, APPLICATION, PRIVATE, and CONTEXT-SPECIFIC. APPLICATION basically means that the tag is defined for use within a specific application (i.e., it's not pre-defined as part of ASN.1.) But an APPLICATION tag doesn't carry enough information to specify (or even hint at) which application is in use.

(Actually, there's very little semantic difference among "APPLICATION", "PRIVATE", and "CONTEXT-SPECIFIC"; these three classes are used mostly for historical and stylistic reasons.)


问:
characters in for loop printing out too far away from values
I am very new to java and for loops. I would like my code to print out this

```<code>Andy      **
Kristy    **********
Amy       ***** `
</code>```

But my I am getting this instead

```<code>Andy          **
Kristy          **********
Amy          *****
</code>```

How do I change my for loop to stop the spacing from the names being this way? Thank you.

```<code>public static void drawChart(String name, int age) {
    System.out.print(name);
    for(int j = 1; j <= 10; j++) {
        System.out.print(" ");
    }

    for (int i=0; i<age; i++) {
        System.out.print("*");
    }

    System.out.println(" ");
}
</code>```

答:
You can use String.format() utility to write the name in a certain width. If the name is less than that width, it'll fill the rest with spaces. Something like that.

```<code>public static void drawChart(String name, int age){
        String nameWithPadding = String.format("%-20s", name);
        System.out.print(nameWithPadding);
        for (int i = 0; i < age; i++)
            System.out.print('*');
        System.out.println();
}
</code>```

Here, this part %-20s is writing the name in 20 chars. First it writes the name, followed by spaces until it reaches 20 chars.

Body:
I am very new to java and for loops. I would like my code to print out this

Andy      **
Kristy    **********
Amy       ***** `

But my I am getting this instead

Andy          **
Kristy          **********
Amy          *****

How do I change my for loop to stop the spacing from the names being this way? Thank you.

public static void drawChart(String name, int age) {
    System.out.print(name);
    for(int j = 1; j <= 10; j++) {
        System.out.print(" ");
    }

    for (int i=0; i<age; i++) {
        System.out.print("*");
    }

    System.out.println(" ");
}

Body:
You can use String.format() utility to write the name in a certain width. If the name is less than that width, it'll fill the rest with spaces. Something like that.

public static void drawChart(String name, int age){
        String nameWithPadding = String.format("%-20s", name);
        System.out.print(nameWithPadding);
        for (int i = 0; i < age; i++)
            System.out.print('*');
        System.out.println();
}

Here, this part %-20s is writing the name in 20 chars. First it writes the name, followed by spaces until it reaches 20 chars.


问:
How to save raw html to sql with codeigniter?
I'm working with Ionize - i'm trying to save text with html tags to mysqli, but i keep getting the text like this :

```<code>   <p><div class="foo">foo</div></p>
</code>```

while i want to get

```<code>    <div class="foo">foo</div>
</code>```

I've tried to replace all the htmlspecialchars methods with html_entity_decode
but it didn't worked

答: It's ok to have it saved like that, you just have to apply htmlspecialchars_decode on your result before printing it.</p>

Body:
I'm working with Ionize - i'm trying to save text with html tags to mysqli, but i keep getting the text like this :

foo

while i want to get

foo

I've tried to replace all the htmlspecialchars methods with html_entity_decode
but it didn't worked


问:
English Language Regex in C#
I need a regex pattern which can detect if the given text is in English or not, but I want to include the following:

Allowing spaces

Allowing numbers and words

Allowing multiple lines and tabs

Allowing all special characters !@#$%^&*()_-+={}|/<>~`':";[]

Allowing URLs, emails

If the given text contains any character rather than English, it should be considered a non-English text, this should be applied if the text contains Arabic letters/words like "ا ب ت ... etc." and the same for French "é, â ... etc." and also all of the other languages

In brief, I need to know if the given text, any text with any format, is in English or not. I tried a lot of patterns but I didn't get it, and actually, I don't need to use any language detector as the application will be used offline.

Samples of the texts which should not be accepted:

Hello! ... é

مرحبا بك

للتحميل اضغط هنا ... http://www.google.com

So, if the text contains non-English letter, it should be considered non-English text.

答:
I think I found it, I tried the Basic Latin Unicode category, and it works fine so far. I used:

```<code>"^[\u0000-\u007F]+$"
</code>```

Its idea is about checking if the given text is in English and is written by using English letters only, in addition, it allows special characters. So, if the given text was like this "I met my friend in a café", it is considered as non-English text, as the given text should contain only English letters and avoid any other letters even if typed a name, place ... etc. this was exactly what I need.

Thank you all.

Resources:

http://kourge.net/projects/regexp-unicode-block

https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx

Regular expression to match non-English characters?

Title: English Language Regex in C#

Body:
I think I found it, I tried the Basic Latin Unicode category, and it works fine so far. I used:

"^[\u0000-\u007F]+$"

Its idea is about checking if the given text is in English and is written by using English letters only, in addition, it allows special characters. So, if the given text was like this "I met my friend in a café", it is considered as non-English text, as the given text should contain only English letters and avoid any other letters even if typed a name, place ... etc. this was exactly what I need.

Thank you all.

Resources:

http://kourge.net/projects/regexp-unicode-block

https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx

Regular expression to match non-English characters?


问:
TabLayout tab selection
How should I select a tab in TabLayout programmatically? </p>

```<code> TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
 tabLayout.setupWithViewPager(viewPager);
</code>```

答:
This can help too </p>

```<code>viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int i, float v, int i1) {
    }

    @Override
    public void onPageSelected(int i) {
        tablayout.getTabAt(i).select();
    }

    @Override
    public void onPageScrollStateChanged(int i) {
    }
});
</code>```

Title: TabLayout tab selection

Body:
How should I select a tab in TabLayout programmatically?

 TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
 tabLayout.setupWithViewPager(viewPager);

Body:
This can help too

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int i, float v, int i1) {
    }

    @Override
    public void onPageSelected(int i) {
        tablayout.getTabAt(i).select();
    }

    @Override
    public void onPageScrollStateChanged(int i) {
    }
});


问:
Saving temporary data in MVC5 asp.net
I need to save the data from the registration page temporary. If the admin verifies the user, I want to move the data to the database, else the data should be deleted after a time. What do you recommend for that? I read about Tempdata and session but I don't know if they are best practice for this issue.</p>

答:
The data will need to be stored on the server for availability by other users (admin) so I would suggest using a database.

If a user registers, store the data (all the registration fields etc) with a boolean property for instance Verified = false.

These users can be listed for the admin to approve, once approved, set Verified = tree, in this case the is all you need to do and you data is where it should be.

Title: Saving temporary data in MVC5 asp.net


问:
Endpoint which returns send_file not called again
I am writing a Flask app in which I have an HTTP endpoint which returns a send_file of an image I create in the function. Unfortunately, it seems the browser caches that image and doesn't even call the endpoint again, loading the original image on subsequent reloads.

Any idea why this is happening and what the fix might be?

答:
send_file has the option called cache_timeout use that to get rid of browser cache problem.

```<code>send_file('filename', cache_timeout=0)
</code>```

Body:
send_file has the option called cache_timeout use that to get rid of browser cache problem.

send_file('filename', cache_timeout=0)


问:
Zygote preloading vs boot.art loading

Boot images loading (boot.oat, boot.art)

When Android boots up, it loads some boot images which contain some frequently used classes. In particular boot.oat contains the code of the classes, and boot.art some pre-initialized heap.
This speedups application launch, and saves some memory due to the paging mechanism. (More details here)

Zygote preloading

In ZygoteInit.java, there is a preload function.
It preloads classes, resources, shared libraries, etc.
preloadClasses in particular loads the classes found in:
/system/etc/preloaded-classes. Which basically causes the static initializers of these classes run.

How they differ?

What is the difference between the two?
Isn't the sole purpose of boot.art to avoid the explicit initialization that is done by zygotespreload`?

Shouldn't the zygote's preload run only for imageless bootup?

答: That's probably because /system/etc/preloaded-classes wasn't really part of boot.art. Android provides the flexibility to choose what goes into boot.art so that the image size can be kept small but which obviously will result into a few classes being loaded at run time during zygote initialization.</p>

Title: Zygote preloading vs boot.art loading


问:
How to retrieve object from Go http.Request?
I have a working app that recieves HTTP GET parameters. They've been Strings and ints until now and it has worked fine getting each field using

```<code>http.Request.FormValue("field")
</code>```

But now I've added an array of simple objects in the parameters and I don't know how to transform it to a slice of Go structs.

The array in question is

```<code>mods:[{
    name : x,
    max : 1,
    min : 2
 },{
    name:y,...
 }]
</code>```

So I'm not sure how to proceed to map it to a Go struct. Should I create the struct first and map the result of r.FormValue using JSON?

答:
Let's say you want to fetch a set of github users and want to print their nicknames (Login field in api.github.com).

Given a User array example:

```<code>[{
  "login": "simonjefford",
  "id": 136,
  "avatar_url": "https://avatars1.githubusercontent.com/u/136?v=3",
  "gravatar_id": "",
  "url": "https://api.github.com/users/simonjefford",
  "html_url": "https://github.com/simonjefford",
  "followers_url": "https://api.github.com/users/simonjefford/followers",
  "following_url": "https://api.github.com/users/simonjefford/following{/other_user}",
  "gists_url": "https://api.github.com/users/simonjefford/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/simonjefford/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/simonjefford/subscriptions",
  "organizations_url": "https://api.github.com/users/simonjefford/orgs",
  "repos_url": "https://api.github.com/users/simonjefford/repos",
  "events_url": "https://api.github.com/users/simonjefford/events{/privacy}",
  "received_events_url": "https://api.github.com/users/simonjefford/received_events",
  "type": "User",
  "site_admin": false
}]
</code>```

You need a proper struct to handle it:

```<code>type Users []struct {
  Login string `json:"login"`
  ID int `json:"id"`
  AvatarURL string `json:"avatar_url"`
  GravatarID string `json:"gravatar_id"`
  URL string `json:"url"`
  HTMLURL string `json:"html_url"`
  FollowersURL string `json:"followers_url"`
  FollowingURL string `json:"following_url"`
  GistsURL string `json:"gists_url"`
  StarredURL string `json:"starred_url"`
  SubscriptionsURL string `json:"subscriptions_url"`
  OrganizationsURL string `json:"organizations_url"`
  ReposURL string `json:"repos_url"`
  EventsURL string `json:"events_url"`
  ReceivedEventsURL string `json:"received_events_url"`
  Type string `json:"type"`
  SiteAdmin bool `json:"site_admin"`
}
</code>```

I suggest you to use json-to-go to have a nice a clean struct given a json.

Then you can do the following:

```<code>package main

import (
  "fmt"
  "encoding/json"
  "net/http"
  "log"
  "io/ioutil"
)

func main() {

  response, err := http.Get("https://api.github.com/users?since=135")
  if err != nil {
     log.Fatal(err)
  } else {

    defer response.Body.Close()
    users := UnmarshalUsers(response)
    for _, u := range users {
        //Print each user's Login nickname
        fmt.Println(u.Login)
    }

  }

}
</code>```

Where UnmarshalUsers is

```<code>func UnmarshalUsers(r *http.Response) Users {
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        panic(err)
    }
    var users Users
    err = json.Unmarshal(body, &users)
    if err != nil {
        panic(err)
    }

    return users
}
</code>```

Body:
I have a working app that recieves HTTP GET parameters. They've been Strings and ints until now and it has worked fine getting each field using

http.Request.FormValue("field")

But now I've added an array of simple objects in the parameters and I don't know how to transform it to a slice of Go structs.

The array in question is

mods:[{
    name : x,
    max : 1,
    min : 2
 },{
    name:y,...
 }]

So I'm not sure how to proceed to map it to a Go struct. Should I create the struct first and map the result of r.FormValue using JSON?

Body:
Let's say you want to fetch a set of github users and want to print their nicknames (Login field in api.github.com).

Given a User array example:

[{
  "login": "simonjefford",
  "id": 136,
  "avatar_url": "https://avatars1.githubusercontent.com/u/136?v=3",
  "gravatar_id": "",
  "url": "https://api.github.com/users/simonjefford",
  "html_url": "https://github.com/simonjefford",
  "followers_url": "https://api.github.com/users/simonjefford/followers",
  "following_url": "https://api.github.com/users/simonjefford/following{/other_user}",
  "gists_url": "https://api.github.com/users/simonjefford/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/simonjefford/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/simonjefford/subscriptions",
  "organizations_url": "https://api.github.com/users/simonjefford/orgs",
  "repos_url": "https://api.github.com/users/simonjefford/repos",
  "events_url": "https://api.github.com/users/simonjefford/events{/privacy}",
  "received_events_url": "https://api.github.com/users/simonjefford/received_events",
  "type": "User",
  "site_admin": false
}]

You need a proper struct to handle it:

type Users []struct {
  Login string `json:"login"`
  ID int `json:"id"`
  AvatarURL string `json:"avatar_url"`
  GravatarID string `json:"gravatar_id"`
  URL string `json:"url"`
  HTMLURL string `json:"html_url"`
  FollowersURL string `json:"followers_url"`
  FollowingURL string `json:"following_url"`
  GistsURL string `json:"gists_url"`
  StarredURL string `json:"starred_url"`
  SubscriptionsURL string `json:"subscriptions_url"`
  OrganizationsURL string `json:"organizations_url"`
  ReposURL string `json:"repos_url"`
  EventsURL string `json:"events_url"`
  ReceivedEventsURL string `json:"received_events_url"`
  Type string `json:"type"`
  SiteAdmin bool `json:"site_admin"`
}

I suggest you to use json-to-go to have a nice a clean struct given a json.

Then you can do the following:

package main

import (
  "fmt"
  "encoding/json"
  "net/http"
  "log"
  "io/ioutil"
)

func main() {

  response, err := http.Get("https://api.github.com/users?since=135")
  if err != nil {
     log.Fatal(err)
  } else {

    defer response.Body.Close()
    users := UnmarshalUsers(response)
    for _, u := range users {
        //Print each user's Login nickname
        fmt.Println(u.Login)
    }

  }

}

Where UnmarshalUsers is

func UnmarshalUsers(r *http.Response) Users {
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        panic(err)
    }
    var users Users
    err = json.Unmarshal(body, &users)
    if err != nil {
        panic(err)
    }

    return users
}


问:
Get the value of an IntInsnNode using ASM
I'm trying to get the value of an IntInsnNode using the ASM (Bytecode) library.
The IntInsnNode instuctions are below:

```<code> sipush 18998
 bipush 91
 bipush 34
</code>```

So what I'm trying to achieve is getting the 18998, 91 and 34.

答:
I found the answer.
It can be done using the operand from IntInsnNode class.

Body:
I'm trying to get the value of an IntInsnNode using the ASM (Bytecode) library.
The IntInsnNode instuctions are below:

 sipush 18998
 bipush 91
 bipush 34

So what I'm trying to achieve is getting the 18998, 91 and 34.


问:
Changing address contained by pointer using function
If I've declared a pointer p as int *p; in main module, I can change the address contained by p by assigning p = &a; where a is another integer variable already declared.
I now want to change the address by using a function as:

```<code>void change_adrs(int*q)
{
    int *newad;
    q = newad;
}
</code>```

If I call this function from main module

```<code>int main()
{
    int *p;
    int a = 0;
    p = &a; // this changes the address contained by pointer p
    printf("The address is %u\n", p);
    change_adrs(p);
    printf("The address is %u\n", p); // but this doesn't change the address
    return 0;
}
</code>```

the address content is unchanged. What's wrong with using a function for same task?

答:
If you want to alter the content of a variable in a function in C, pointer is a kinda variable as well, you have to pass it by pointer or indirect reference by using always & address and * dereference operators. I mean * operator is always used and preceded when changing the value of a variable.

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

void changeIntVal(int *x) {
    *x = 5;
}

void changePointerAddr(int **q) {
    int *newad;
    *q = newad;
}

void changePPAddr(int ***q) {
    int **dummy;
    *q = dummy;
}

int main() {
    int *p;
    int **pp;
    int *tempForPP;
    int a = 0;
    printf("\n The address pointing by p -> %p, pp -> %p, value of a -> %d ", p, pp, a);

    p = &a;
    pp = &tempForPP;
    printf("\n The address pointing by p -> %p, pp -> %p, value of a -> %d ", p, pp, a);

    changeIntVal(&a);        // ----
                             //    |---
    changePointerAddr(&p);   // ----  |---->  parts of what I mean
                             //    |---
    changePPAddr(&pp);       // ----

    printf("\n The address pointing by p -> %p, pp -> %p, value of a -> %d ", p, pp, a);

    return 0;

}
</code>```

Body:
If I've declared a pointer p as int *p; in main module, I can change the address contained by p by assigning p = &a; where a is another integer variable already declared.
I now want to change the address by using a function as:

void change_adrs(int*q)
{
    int *newad;
    q = newad;
}

If I call this function from main module

int main()
{
    int *p;
    int a = 0;
    p = &a; // this changes the address contained by pointer p
    printf("The address is %u\n", p);
    change_adrs(p);
    printf("The address is %u\n", p); // but this doesn't change the address
    return 0;
}

the address content is unchanged. What's wrong with using a function for same task?

Body:
If you want to alter the content of a variable in a function in C, pointer is a kinda variable as well, you have to pass it by pointer or indirect reference by using always & address and * dereference operators. I mean * operator is always used and preceded when changing the value of a variable.

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

void changeIntVal(int *x) {
    *x = 5;
}

void changePointerAddr(int **q) {
    int *newad;
    *q = newad;
}

void changePPAddr(int ***q) {
    int **dummy;
    *q = dummy;
}

int main() {
    int *p;
    int **pp;
    int *tempForPP;
    int a = 0;
    printf("\n The address pointing by p -> %p, pp -> %p, value of a -> %d ", p, pp, a);

    p = &a;
    pp = &tempForPP;
    printf("\n The address pointing by p -> %p, pp -> %p, value of a -> %d ", p, pp, a);

    changeIntVal(&a);        // ----
                             //    |---
    changePointerAddr(&p);   // ----  |---->  parts of what I mean
                             //    |---
    changePPAddr(&pp);       // ----

    printf("\n The address pointing by p -> %p, pp -> %p, value of a -> %d ", p, pp, a);

    return 0;

}


问:
Python file I/O with Tkinter
I'm trying to open a .txt file with Python. I'm trying to fill a Tkinter text widget with the files contents.

However with the following snippet, when I try to open the files contents and put it in a the text widget self.Te, nothing happens. Any clues?

Snippet:

```<code>    self.Open = tkFileDialog.askopenfilename(initialdir='C:')

    text_file = open(self.Open, "r")
    # self.Te is a text widget
    self.Te.insert('1.0', text_file.read())
</code>```

答:
Here is a working example:

```<code>#!/usr/bin/env python

from Tkinter import *
from tkFileDialog  import askopenfilename

class App:
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.button = Button(frame, text="QUIT", command=frame.quit)
        self.button.pack(side=BOTTOM)

        self.text = Text(frame)
        self.text.pack(side=TOP)

        self.choosen = askopenfilename(initialdir='~')
        self.text.insert(END, open(self.choosen).read())

root = Tk()
app = App(root)
root.mainloop()
</code>```

See also Text widget method documentation:

http://www.pythonware.com/library/tkinter/introduction/x8369-methods.htm

... Insert text at the given position (typically INSERT or END) ...

Title: Python file I/O with Tkinter

Body:
I'm trying to open a .txt file with Python. I'm trying to fill a Tkinter text widget with the files contents.

However with the following snippet, when I try to open the files contents and put it in a the text widget self.Te, nothing happens. Any clues?

Snippet:

    self.Open = tkFileDialog.askopenfilename(initialdir='C:')

    text_file = open(self.Open, "r")
    # self.Te is a text widget
    self.Te.insert('1.0', text_file.read())

Body:
Here is a working example:

#!/usr/bin/env python

from Tkinter import *
from tkFileDialog  import askopenfilename

class App:
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.button = Button(frame, text="QUIT", command=frame.quit)
        self.button.pack(side=BOTTOM)

        self.text = Text(frame)
        self.text.pack(side=TOP)

        self.choosen = askopenfilename(initialdir='~')
        self.text.insert(END, open(self.choosen).read())

root = Tk()
app = App(root)
root.mainloop()

See also Text widget method documentation:

http://www.pythonware.com/library/tkinter/introduction/x8369-methods.htm

... Insert text at the given position (typically INSERT or END) ...


问:
Client side router's version of window.onload?
I'm having some difficulties finding ways to tell when every resource (e.g., images, videos, etc) has been loaded. I can easily do it on the first page by using window.onload, but the load event doesn't seem to fire when changing routes via a client side router. I'm specifically using react-router, if that helps.

Is there a better solution?

答:
To change window dynamically, do this:

```<code>import React, { Component } from 'react';
import {withRouter} from 'react-router';

class YourComponent extends Component {

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) { // detect page change
      window.scrollTo(0, 0); // for example // or document.querySelector ... or any js
    }
  }

  render() {
   return this.props.children
  }

}

export default withRouter(YourComponent)
</code>```

Then wrap as a parent component :

```<code>// import react and everything
// import { BrowserRouter as Router } from 'react-router-dom';

// in your render
<Router>
  <YourComponent>
    <OtherComponentOrRouting />
  </YourComponent>
<Router>
</code>```

Body:
To change window dynamically, do this:

import React, { Component } from 'react';
import {withRouter} from 'react-router';

class YourComponent extends Component {

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) { // detect page change
      window.scrollTo(0, 0); // for example // or document.querySelector ... or any js
    }
  }

  render() {
   return this.props.children
  }

}

export default withRouter(YourComponent)

Then wrap as a parent component :

// import react and everything
// import { BrowserRouter as Router } from 'react-router-dom';

// in your render
<Router>
  <YourComponent>
    <OtherComponentOrRouting />
  </YourComponent>
<Router>