问:
Pandas- creating a table that inserts new rows based on column values?
I have a dataframe that has names of an item, data on it, and then competitor data all in one row:

```<code> name   value1   value2    ex_value1     ex_value2
 jim       0.4      0.6           0.7           0.3
 tim       0.2      0.8   0.766666667   0.233333333
 john        1        0           0.5           0.5
 paul      0.9      0.1   0.533333333   0.466666667
</code>```

What I want to do is create a new table that has indexes by name, but inserts new rows based on the competitor data, so that it shows jim, ex-jim, tim,ex-tim, etc:

```<code>   name       value1        value2
  jim               0.4           0.6
  tim               0.2           0.8
  john                1             0
  paul              0.9           0.1
  ex_jim            0.7           0.3
  ex_tim    0.766666667   0.233333333
  ex_john           0.5           0.5
  ex_paul   0.533333333   0.466666667
</code>```

How would I go about doing this? Would I have to set index on name, then insert new that way? Would I got about this through a loop? Appreciate guidance on this

答:
You can do this using concat</p>

```<code>df_ex = df[['name','ex_value1', 'ex_value2']].rename(columns = {'ex_value1': 'value1', 'ex_value2': 'value2'})

df_ex['name'] = 'ex_' + df_ex['name']

pd.concat([df[['name','value1', 'value2']], df_ex ]).round(2)

    name    value1  value2
0   jim     0.40    0.60
1   tim     0.20    0.80
2   john    1.00    0.00
3   paul    0.90    0.10
0   ex_jim  0.70    0.30
1   ex_tim  0.77    0.23
2   ex_john 0.50    0.50
3   ex_paul 0.53    0.47
</code>```

Body:
I have a dataframe that has names of an item, data on it, and then competitor data all in one row:

 name   value1   value2    ex_value1     ex_value2
 jim       0.4      0.6           0.7           0.3
 tim       0.2      0.8   0.766666667   0.233333333
 john        1        0           0.5           0.5
 paul      0.9      0.1   0.533333333   0.466666667

What I want to do is create a new table that has indexes by name, but inserts new rows based on the competitor data, so that it shows jim, ex-jim, tim,ex-tim, etc:

   name       value1        value2
  jim               0.4           0.6
  tim               0.2           0.8
  john                1             0
  paul              0.9           0.1
  ex_jim            0.7           0.3
  ex_tim    0.766666667   0.233333333
  ex_john           0.5           0.5
  ex_paul   0.533333333   0.466666667

How would I go about doing this? Would I have to set index on name, then insert new that way? Would I got about this through a loop? Appreciate guidance on this

Body:
You can do this using concat

df_ex = df[['name','ex_value1', 'ex_value2']].rename(columns = {'ex_value1': 'value1', 'ex_value2': 'value2'})

df_ex['name'] = 'ex_' + df_ex['name']

pd.concat([df[['name','value1', 'value2']], df_ex ]).round(2)

    name    value1  value2
0   jim     0.40    0.60
1   tim     0.20    0.80
2   john    1.00    0.00
3   paul    0.90    0.10
0   ex_jim  0.70    0.30
1   ex_tim  0.77    0.23
2   ex_john 0.50    0.50
3   ex_paul 0.53    0.47


来源: stackexchange

问:
Query inside NOT IN statement Doctrine
I found this sentence in the code:

```<code>        $dql
            = <<<DQL
SELECT u FROM AppBundle:User u
JOIN u.Roles r
JOIN u.team t
WHERE u.id NOT IN (
      SELECT user.id
      FROM GameBundle:Goal g
      JOIN g.user user
      WHERE
        g.objective = :objective
    )
  AND
    r.profile = :sales_profile
  AND
    r.company = :company
  AND
    u.onlyStatus NOT IN (:status)
DQL;
</code>```

I don't know how to works that query inside NOT IN sentence, help me please.

I need to know:

What return the query inside of NOT IN, (data types, so on...)

How to works a query inside of NOT IN (is posible ?)

答:
```<code>SELECT u FROM AppBundle:User u
JOIN u.Roles r
JOIN u.team t
WHERE u.id NOT IN (
      SELECT user.id
      FROM GameBundle:Goal g
      JOIN g.user user
      WHERE
        g.objective = :objective
    )
</code>```

this means take all the users that don't currently have 'objective' in the 'Goal' table.

Is this what you needed ?

ContentLicense: CC BY-SA 3.0

Title: Query inside NOT IN statement Doctrine

Body:
I found this sentence in the code:

        $dql
            = <<<DQL
SELECT u FROM AppBundle:User u
JOIN u.Roles r
JOIN u.team t
WHERE u.id NOT IN (
      SELECT user.id
      FROM GameBundle:Goal g
      JOIN g.user user
      WHERE
        g.objective = :objective
    )
  AND
    r.profile = :sales_profile
  AND
    r.company = :company
  AND
    u.onlyStatus NOT IN (:status)
DQL;

I don't know how to works that query inside NOT IN sentence, help me please.

I need to know:

What return the query inside of NOT IN, (data types, so on...)

How to works a query inside of NOT IN (is posible ?)

Body:
SELECT u FROM AppBundle:User u
JOIN u.Roles r
JOIN u.team t
WHERE u.id NOT IN (
      SELECT user.id
      FROM GameBundle:Goal g
      JOIN g.user user
      WHERE
        g.objective = :objective
    )

this means take all the users that don't currently have 'objective' in the 'Goal' table.

Is this what you needed ?


问:
Looping through nested arrays and converting to objects
I want to convert an group of nested arrays into an array of objects with the collected information from the nested arrays:

BEFORE:

```<code>var employeeData = [
  [
    ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
  ]
]
</code>```

AFTER:

```<code>[
  {firstName: 'Bob', lastName: 'Lob', age: 22, role: 'salesperson'},
  {firstName: 'Mary', lastName: 'Joe', age: 32, role: 'director'}
]
</code>```

Here is the function I wrote to solve this but I can't quite see where the loop is going wrong:

    var employeeData = [
      [
        ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
      ],
      [
        ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
      ]
    ]

    function transformData(employeeData) {
      let newObject = {};
      let newArr = [];

      for (var i = 0; i < employeeData.length; i++) {
        for (var x = 0; x < employeeData[i].length; x++) {
          for (var y = 0; y < employeeData[i][y].length; y++) {
            newObject[employeeData[i][y][0]] = employeeData[i][y][1];
          }
        }
        newArr.push(newObject);
        newObject = {};
      }
      return newArr;
    }

    console.log(transformData(employeeData));```

Thanks in advance.

答:
How to fix your code

You only need 2 for loops:
1. iterate the array
2. iterate the sub arrays and construct the object

var employeeData = [[["firstName","Bob"],["lastName","Lob"],["age",22],["role","salesperson"]],[["firstName","Mary"],["lastName","Joe"],["age",32],["role","director"]]]

function transformData(employeeData) {
  let newObject;
  const newArr = [];

  for (var i = 0; i < employeeData.length; i++) {
    newObject = {}; // init new object
    for (var x = 0; x < employeeData[i].length; x++) {
        newObject[employeeData[i][x][0]] = employeeData[i][x][1]; // iterate inner arrays and assign properties to object
    }
    newArr.push(newObject);
  }
  return newArr;
}

console.log(transformData(employeeData));```
</div>
</div>
</p>

<p>Another option is to use a combination of Array#map to iterate the outer array and Array#reduce to construct an object from the inner arrays:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const employeeData = [[["firstName","Bob"],["lastName","Lob"],["age",22],["role","salesperson"]],[["firstName","Mary"],["lastName","Joe"],["age",32],["role","director"]]]

const result = employeeData.map((arr) =>
  arr.reduce((o, [key, value]) => (o[key] = value, o), {})
);

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

Body:
I want to convert an group of nested arrays into an array of objects with the collected information from the nested arrays:

BEFORE:

var employeeData = [
  [
    ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
  ]
]

AFTER:

[
  {firstName: 'Bob', lastName: 'Lob', age: 22, role: 'salesperson'},
  {firstName: 'Mary', lastName: 'Joe', age: 32, role: 'director'}
]

Here is the function I wrote to solve this but I can't quite see where the loop is going wrong:

    var employeeData = [
      [
        ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
      ],
      [
        ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
      ]
    ]

    function transformData(employeeData) {
      let newObject = {};
      let newArr = [];

      for (var i = 0; i < employeeData.length; i++) {
        for (var x = 0; x < employeeData[i].length; x++) {
          for (var y = 0; y < employeeData[i][y].length; y++) {
            newObject[employeeData[i][y][0]] = employeeData[i][y][1];
          }
        }
        newArr.push(newObject);
        newObject = {};
      }
      return newArr;
    }

    console.log(transformData(employeeData));

Thanks in advance.

Body:
How to fix your code

You only need 2 for loops:
1. iterate the array
2. iterate the sub arrays and construct the object

var employeeData = [[["firstName","Bob"],["lastName","Lob"],["age",22],["role","salesperson"]],[["firstName","Mary"],["lastName","Joe"],["age",32],["role","director"]]]

function transformData(employeeData) {
  let newObject;
  const newArr = [];

  for (var i = 0; i < employeeData.length; i++) {
    newObject = {}; // init new object
    for (var x = 0; x < employeeData[i].length; x++) {
        newObject[employeeData[i][x][0]] = employeeData[i][x][1]; // iterate inner arrays and assign properties to object
    }
    newArr.push(newObject);
  }
  return newArr;
}

console.log(transformData(employeeData));

Another option is to use a combination of Array#map to iterate the outer array and Array#reduce to construct an object from the inner arrays:

const employeeData = [[["firstName","Bob"],["lastName","Lob"],["age",22],["role","salesperson"]],[["firstName","Mary"],["lastName","Joe"],["age",32],["role","director"]]]

const result = employeeData.map((arr) =>
  arr.reduce((o, [key, value]) => (o[key] = value, o), {})
);

console.log(result);

ContentLicense: CC BY-SA 4.0


问:
PHP server on local machine?
I'm trying to build a PHP site and I'm wanting to test my PHP files without uploading them to my host. Basically testing them on my own machine before I upload them. How do I do that?</p>

答:
AppServ is a small program in Windows to run:

Apache

PHP

MySQL

phpMyAdmin

It will also give you a startup and stop button for Apache. Which I find very useful.

Title: PHP server on local machine?


问:
Consume SQS tasks from App Engine
I'm attempting to integrate with a third party that is posting messages on an Amazon SQS queue. I need my GAE backend to receive these messages.

Essentially, I want the following script to launch and always be running

```<code>import boto3
sqs_client = boto3.client('sqs',
    aws_access_key_id=KEY,
    aws_secret_access_key=SECRET,
    region_name=REGION)
while True:
    sqs_client.receive_message(QueueUrl=QUEUE_URL, WaitTimeSeconds=60)
    for message in msgs_response.get('Messages', []):
        deferred.defer(process_and_delete_message, message)
</code>```

My main appengine web app is on Automatic Scaling (with the 60-second &10-minute task timeouts), but I'm thinking of setting up a micro-service set to either Manual Scaling or Basic Scaling because:

Requests can run indefinitely. A manually-scaled instance can choose to handle /_ah/start and execute a program or script for many hours without returning an HTTP response code. Task queue tasks can run up to 24 hours.

https://cloud.google.com/appengine/docs/standard/python/an-overview-of-app-engine

Apparently both Manual & Basic Scaling also allow "Background Threads", but I am having a hard-time finding documentation for it and I'm thinking this may be a relic from the days before they deprecated Backends in favor of Modules (although I did find this https://cloud.google.com/appengine/docs/standard/python/refdocs/modules/google/appengine/api/background_thread/background_thread#BackgroundThread).

Is Manual or Basic Scaling suited for this? If so, what should I use to listen on sqs_client.receive_message()? One thing I'm concerned about is this task/background thread dieing and not relaunching itself.

答:
This maybe a possible solution:

Try to use a Google Compute Engine micro instance to run that script continuously and send a REST call to your app engine app. Easy Python Example For Compute Engine

OR:

I have used modules that run instance type B2/B1 for long running jobs; and I have never had any trouble; but those jobs do start and stop. I use the basic scaling: with max_instances set to 1. The jobs I have run take around 6 hours to complete.

Title: Consume SQS tasks from App Engine

Body:
I'm attempting to integrate with a third party that is posting messages on an Amazon SQS queue. I need my GAE backend to receive these messages.

Essentially, I want the following script to launch and always be running

import boto3
sqs_client = boto3.client('sqs',
    aws_access_key_id=KEY,
    aws_secret_access_key=SECRET,
    region_name=REGION)
while True:
    sqs_client.receive_message(QueueUrl=QUEUE_URL, WaitTimeSeconds=60)
    for message in msgs_response.get('Messages', []):
        deferred.defer(process_and_delete_message, message)

My main appengine web app is on Automatic Scaling (with the 60-second &10-minute task timeouts), but I'm thinking of setting up a micro-service set to either Manual Scaling or Basic Scaling because:

Requests can run indefinitely. A manually-scaled instance can choose to handle /_ah/start and execute a program or script for many hours without returning an HTTP response code. Task queue tasks can run up to 24 hours.

https://cloud.google.com/appengine/docs/standard/python/an-overview-of-app-engine

Apparently both Manual & Basic Scaling also allow "Background Threads", but I am having a hard-time finding documentation for it and I'm thinking this may be a relic from the days before they deprecated Backends in favor of Modules (although I did find this https://cloud.google.com/appengine/docs/standard/python/refdocs/modules/google/appengine/api/background_thread/background_thread#BackgroundThread).

Is Manual or Basic Scaling suited for this? If so, what should I use to listen on sqs_client.receive_message()? One thing I'm concerned about is this task/background thread dieing and not relaunching itself.


答:
I would recommend splitting your dataframe into two and then concatting it back together. Something like:</p>

```<code>import pandas as pd

df = pd.DataFrame([['jim', .4, .6, .7, .3], ['john', 1, 0, .5, .5]], columns=['name', 'value1', 'value2', 'ex_value1', 'ex_value2'])

ex_df = df.copy()

ex_df['name'] = 'ex_'+ex_df['name'].astype(str)

ex_df = ex_df[['name', 'ex_value1', 'ex_value2']]
ex_df.columns = ['name', 'value1', 'value2']

df = df[['name', 'value1', 'value2']]

frames = (df, ex_df)

new = pd.concat(frames).reset_index()
new = new[['name', 'value1', 'value2']]

print(new)

#output
         name  value1  value2
0      jim     0.4     0.6
1     john     1.0     0.0
2   ex_jim     0.7     0.3
3  ex_john     0.5     0.5
</code>```

Title: Pandas- creating a table that inserts new rows based on column values?

Body:
I would recommend splitting your dataframe into two and then concatting it back together. Something like:

import pandas as pd

df = pd.DataFrame([['jim', .4, .6, .7, .3], ['john', 1, 0, .5, .5]], columns=['name', 'value1', 'value2', 'ex_value1', 'ex_value2'])

ex_df = df.copy()

ex_df['name'] = 'ex_'+ex_df['name'].astype(str)

ex_df = ex_df[['name', 'ex_value1', 'ex_value2']]
ex_df.columns = ['name', 'value1', 'value2']

df = df[['name', 'value1', 'value2']]

frames = (df, ex_df)

new = pd.concat(frames).reset_index()
new = new[['name', 'value1', 'value2']]

print(new)

#output
         name  value1  value2
0      jim     0.4     0.6
1     john     1.0     0.0
2   ex_jim     0.7     0.3
3  ex_john     0.5     0.5


问:
rewrite if/else for textbox into a single line of code
Is it possible to rewrite this into a single line of code?</p>

```<code>if (txtInvoiceDate.Text != "")
{
  query.Parameters.AddWithValue("@InvoiceDate", SqlDbType.SmallDateTime).Value = DateTime.Parse(txtInvoiceDate.Text.ToString());
}
else
{
  query.Parameters.AddWithValue("@InvoiceDate", SqlDbType.SmallDateTime).Value = DBNull.Value;
}
</code>```

答:
Short answer: yes

Long answer:

```<code>query.Parameters.AddWithValue("@InvoiceDate", SqlDbType.SmallDateTime).Value = string.IsNullOrWhiteSpace(txtInvoiceDate.Text) ? DBNull.Value : DateTime.Parse(txtInvoiceDate.Text.ToString());
</code>```

Body:
Is it possible to rewrite this into a single line of code?

if (txtInvoiceDate.Text != "")
{
  query.Parameters.AddWithValue("@InvoiceDate", SqlDbType.SmallDateTime).Value = DateTime.Parse(txtInvoiceDate.Text.ToString());
}
else
{
  query.Parameters.AddWithValue("@InvoiceDate", SqlDbType.SmallDateTime).Value = DBNull.Value;
}

Body:
Short answer: yes

Long answer:

query.Parameters.AddWithValue("@InvoiceDate", SqlDbType.SmallDateTime).Value = string.IsNullOrWhiteSpace(txtInvoiceDate.Text) ? DBNull.Value : DateTime.Parse(txtInvoiceDate.Text.ToString());


问:
Migrating intellisense from Visual Studio 2015 to VSCode

Hi,

In VS2015 I had excellent intellisense support through the use of intellisense.js reference files dotted through out the project. These combined with JsDoc notation ensured that all my non-library code had intellisense support.

```<code>/// <reference path="hudtimer.js" />
/// <reference path="intellisense.js" />
/// <reference path="menulayergametimers.js" />
/// <reference path="menulayerstreakidentifier.js" />
/// <reference path="streakidentifier.js" />
/// <reference path="menulayerpop.js" />
/// <reference path="popentity.js" />
/// <reference path="popentityfactory.js" />
/// <reference path="popactions.js" />
/// <reference path="menulayerpophud.js" />
/// <reference path="popquestion.js" />
/// <reference path="popcharacter.js" />
/// <reference path="popvfxmanager.js" />
</code>```

In VSCode, these files are essentially ignored which results in very poor intellisense. It seems to prefer TypeScript definitions, which is not something I've really looked into before and could potentially consume an enormous amount of time to create/generate for each file in the code base (big project!)

Is there a way to force/coax VSCode into using the already set-up intellisense.js files?

答:
Try creating a jsconfig.json file at the root of your project with the contents:

```<code>{
    "compilerOptions": {
        "target": "ES6"
    },
    "exclude": [
        "node_modules",
        "**/node_modules/*"
    ]
}
</code>```

This file should ensure that all js file in your workspace—including intellisense.js—are picked up and included in the same JavaScript project.

In the future, I also recommend you try to migrate away from using a reference paths file to using the jsconfig to define your project structure

Body:
Hi,

In VS2015 I had excellent intellisense support through the use of intellisense.js reference files dotted through out the project. These combined with JsDoc notation ensured that all my non-library code had intellisense support.

/// <reference path="hudtimer.js" />
/// <reference path="intellisense.js" />
/// <reference path="menulayergametimers.js" />
/// <reference path="menulayerstreakidentifier.js" />
/// <reference path="streakidentifier.js" />
/// <reference path="menulayerpop.js" />
/// <reference path="popentity.js" />
/// <reference path="popentityfactory.js" />
/// <reference path="popactions.js" />
/// <reference path="menulayerpophud.js" />
/// <reference path="popquestion.js" />
/// <reference path="popcharacter.js" />
/// <reference path="popvfxmanager.js" />

In VSCode, these files are essentially ignored which results in very poor intellisense. It seems to prefer TypeScript definitions, which is not something I've really looked into before and could potentially consume an enormous amount of time to create/generate for each file in the code base (big project!)

Is there a way to force/coax VSCode into using the already set-up intellisense.js files?

Body:
Try creating a jsconfig.json file at the root of your project with the contents:

{
    "compilerOptions": {
        "target": "ES6"
    },
    "exclude": [
        "node_modules",
        "**/node_modules/*"
    ]
}

This file should ensure that all js file in your workspace—including intellisense.js—are picked up and included in the same JavaScript project.

In the future, I also recommend you try to migrate away from using a reference paths file to using the jsconfig to define your project structure


问:
How to pass Global variables to classes in PHP?
How can I pass the global variables to the classes I want to use without declare them as GLOBAL in every method of the class ?

example :

```<code>$admin = "admin_area";

if($_POST['login']){
      $user = new Administrator;
      $user->auth($pass,$username);
    }
</code>```

in the class Administrator I want the variable $admin be accessible in all methods of the class without doing this :

```<code>class Administrator{

   public function auth($pass,$user){

     global $admin;
     .....

  }
  public function logout(){
    global $admin;

    .....
}

}
</code>```

答:
Well, you can declare a member variable, and pass it to the constructor:

```<code>class Administrator {
    protected $admin = '';

    public function __construct($admin) {
        $this->admin = $admin;
    }

    public function logout() {
        $this->admin; //That's how you access it
    }
}
</code>```

Then instantiate by:

```<code>$adminObject = new Administrator($admin);
</code>```

But I'd suggest trying to avoid the global variables as much as possible.  They will make your code much harder to read and debug.  By doing something like above (passing it to the constructor of a class), you improve it greatly...

ContentLicense: CC BY-SA 2.5

Body:
How can I pass the global variables to the classes I want to use without declare them as GLOBAL in every method of the class ?

example :

$admin = "admin_area";

if($_POST['login']){
      $user = new Administrator;
      $user->auth($pass,$username);
    }

in the class Administrator I want the variable $admin be accessible in all methods of the class without doing this :

class Administrator{

   public function auth($pass,$user){

     global $admin;
     .....

  }
  public function logout(){
    global $admin;

    .....
}

}

Body:
Well, you can declare a member variable, and pass it to the constructor:

class Administrator {
    protected $admin = '';

    public function __construct($admin) {
        $this->admin = $admin;
    }

    public function logout() {
        $this->admin; //That's how you access it
    }
}

Then instantiate by:

$adminObject = new Administrator($admin);

But I'd suggest trying to avoid the global variables as much as possible.  They will make your code much harder to read and debug.  By doing something like above (passing it to the constructor of a class), you improve it greatly...


问:
Multiplying a np.int8 array with 127 yields different numpy array types depending on platform
The following code:

```<code>>>> import numpy as np
>>> np.arange(2).astype(np.int8) * 127
</code>```

produces for numpy 1.13.3

```<code># On Windows
array([0, 127], dtype=int16)
# On Linux
array([0, 127], dtype=int8)
</code>```

However, if I change the 127 to a 126, both return a np.int8 array. And if I change the 127 to a 128 both return a np.int16 array.

Questions:

Is this expected behaviour?

Why is it different for the two platforms for this one case?

答:
This is due to NumPy issue 5917. A < instead of <= caused np.can_cast(127, np.int8) to be False, so NumPy used a too-large dtype for 127. The OS-dependence is because C longs have a different size on Linux and Windows, and some NumPy code paths depend on the size of a C long.

A fix has been released in NumPy 1.14.0. Once you update to at least NumPy 1.14.0, you should see a dtype of int8 on all platforms.

Body:
The following code:

>>> import numpy as np
>>> np.arange(2).astype(np.int8) * 127

produces for numpy 1.13.3

# On Windows
array([0, 127], dtype=int16)
# On Linux
array([0, 127], dtype=int8)

However, if I change the 127 to a 126, both return a np.int8 array. And if I change the 127 to a 128 both return a np.int16 array.

Questions:

Is this expected behaviour?

Why is it different for the two platforms for this one case?


问:
How to remove hover/clicked effect in pygtk?
I want to remove or turn off this hover and clicked effect on button in pygtk. Do you have any ideas? I couldn't find anything useful here gtk.Button

I am talking about this:

Normal

Hover

Clicked

答:
-Do you really want a button? The main distinction between buttons and labels are those effects (labels don't generate events, but you can make them do so by packing them into a Gtk.EventBox)

-Here's how to disable the events that cause the effects in first place:

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#  test_inert_button.py
#
#  Copyright 2017 John Coppens <john@jcoppens.com>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
#

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class MainWindow(Gtk.Window):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.connect("destroy", lambda x: Gtk.main_quit())
        self.set_size_request(400, 300)

        btn1 = Gtk.Button("One - inert button")
        btn2 = Gtk.Button("Two - active button")

        btn1.connect("enter-notify-event", self.on_leave)
        btn1.connect("button-press-event", self.on_leave)

        vbox = Gtk.VBox()
        vbox.pack_start(btn1, False, False, 0)
        vbox.pack_start(btn2, False, False, 0)

        self.add(vbox)
        self.show_all()

    def on_leave(self, btn, event):
        return True

    def run(self):
        Gtk.main()

def main(args):
    mainwdw = MainWindow()
    mainwdw.run()

    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))
</code>```

The on_leave method's return True tells the default handler that events are handled so it won't do the effects. The top button One doesn't react, the bottom one still does.

Body:
-Do you really want a button? The main distinction between buttons and labels are those effects (labels don't generate events, but you can make them do so by packing them into a Gtk.EventBox)

-Here's how to disable the events that cause the effects in first place:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#  test_inert_button.py
#
#  Copyright 2017 John Coppens <john@jcoppens.com>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
#

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class MainWindow(Gtk.Window):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.connect("destroy", lambda x: Gtk.main_quit())
        self.set_size_request(400, 300)

        btn1 = Gtk.Button("One - inert button")
        btn2 = Gtk.Button("Two - active button")

        btn1.connect("enter-notify-event", self.on_leave)
        btn1.connect("button-press-event", self.on_leave)

        vbox = Gtk.VBox()
        vbox.pack_start(btn1, False, False, 0)
        vbox.pack_start(btn2, False, False, 0)

        self.add(vbox)
        self.show_all()

    def on_leave(self, btn, event):
        return True

    def run(self):
        Gtk.main()

def main(args):
    mainwdw = MainWindow()
    mainwdw.run()

    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))

The on_leave method's return True tells the default handler that events are handled so it won't do the effects. The top button One doesn't react, the bottom one still does.


问:
Using read.csv for rowSums with blanks in R
I'm working in R with data imported from a csv file and I'm trying to take a rowSum of a subset of my data. The data can either be 0, 1, or blank. I'd like to take a sum of all the 1s across all these rows (and ideally find a count of how many non-blank columns there are in each row, but that's my next problem). I am trying the following code:

```<code>df1 <- read.csv("/Users/ardyn/test.csv", header = T, na.strings = "")

rowSums(df1[,36:135])
</code>```

Which gives me the following error:

"Error in rowSums(df1[, 36:135]) : 'x' must be numeric".

When I check, the columns I'm trying to sum across are factors with 3 levels (".","0","1").

How do I import the data or change my rowSums command so that when I take a sum across a subset of variables it just counts the 1s?

答:
I am not sure if the previous answer took care of the problem where you wanted to sum over only the 1's. So maybe this is what you can do

```<code>df1 <- read.csv("/Users/ardyn/test.csv", header = TRUE, na.strings = ".",stringsAsFactors=FALSE)

myfun <- function(x) {
if (x==1) {
    return (as.numeric(x))
          }
else {
    return (0L)
      }
}
rowSums(apply(df1,c(1,2),myfun))
</code>```

I think it should stop throwing the 'x' must be numeric error

Body:
I'm working in R with data imported from a csv file and I'm trying to take a rowSum of a subset of my data. The data can either be 0, 1, or blank. I'd like to take a sum of all the 1s across all these rows (and ideally find a count of how many non-blank columns there are in each row, but that's my next problem). I am trying the following code:

df1 <- read.csv("/Users/ardyn/test.csv", header = T, na.strings = "")

rowSums(df1[,36:135])

Which gives me the following error:

"Error in rowSums(df1[, 36:135]) : 'x' must be numeric".

When I check, the columns I'm trying to sum across are factors with 3 levels (".","0","1").

How do I import the data or change my rowSums command so that when I take a sum across a subset of variables it just counts the 1s?

Body:
I am not sure if the previous answer took care of the problem where you wanted to sum over only the 1's. So maybe this is what you can do

df1 <- read.csv("/Users/ardyn/test.csv", header = TRUE, na.strings = ".",stringsAsFactors=FALSE)

myfun <- function(x) {
if (x==1) {
    return (as.numeric(x))
          }
else {
    return (0L)
      }
}
rowSums(apply(df1,c(1,2),myfun))

I think it should stop throwing the 'x' must be numeric error


问:
recording audio in android app by holding a button on it
Purpose- I'm actually making doorbell kind of app, where on tapping a button ,app rings(plays a small audio) & on holding it app records audio till user holds it.
my objective- start recording when user holds button & stops when user releases button.

```<code>public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "AudioRecordTest";
private Button ring,record;
private String outputfile = null;
private MediaRecorder rec = null;
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
// Requesting permission to RECORD_AUDIO
private boolean permissionToRecordAccepted = false;
private String [] permissions = {Manifest.permission.RECORD_AUDIO};

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode){
        case REQUEST_RECORD_AUDIO_PERMISSION:
            permissionToRecordAccepted  = grantResults[0] == PackageManager.PERMISSION_GRANTED;
            break;
    }
    if (!permissionToRecordAccepted ) finish();

}

private void startrec()
{
    Log.e(LOG_TAG, "startRecording:Calling ");
    rec = new MediaRecorder();
    rec.setAudioSource(MediaRecorder.AudioSource.MIC);
    rec.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
    rec.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
    outputfile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/rec.amr";
    rec.setOutputFile(outputfile);
    try {
        rec.prepare();
        rec.start();
    } catch (IOException ioe2) {
    }
    Toast.makeText(MainActivity.this, "RECORDING STARTED", Toast.LENGTH_SHORT).show();

}
private void stoprec(){
    rec.stop();rec.release();
    Toast.makeText(MainActivity.this, "RECORDING STOPPED", Toast.LENGTH_SHORT).show();
    Log.e(LOG_TAG, "stopRecording:Calling ");
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ring = findViewById(R.id.ringbutton);
    record =findViewById(R.id.recordbutton);

    ring.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v1) {
            try {
                Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                r.play();
            } catch (IllegalStateException ise) {}
        }
    });

    record.setOnTouchListener(new View.OnTouchListener(){
        @Override
        public boolean onTouch(View v2, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) startrec();
         else if (event.getAction() == MotionEvent.ACTION_UP) stoprec();
            return true;}
    });
}
</code>```

}

Problem- app crashes on touching record button

if u know a better way to do this pls tell.

答:
You should use OnTouchListener event and start recording on ACTION_DOWN and stop on ACTION_UP.

Please check this
How to use View.OnTouchListener instead of onClick

Body:
Purpose- I'm actually making doorbell kind of app, where on tapping a button ,app rings(plays a small audio) & on holding it app records audio till user holds it.
my objective- start recording when user holds button & stops when user releases button.

public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "AudioRecordTest";
private Button ring,record;
private String outputfile = null;
private MediaRecorder rec = null;
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
// Requesting permission to RECORD_AUDIO
private boolean permissionToRecordAccepted = false;
private String [] permissions = {Manifest.permission.RECORD_AUDIO};

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode){
        case REQUEST_RECORD_AUDIO_PERMISSION:
            permissionToRecordAccepted  = grantResults[0] == PackageManager.PERMISSION_GRANTED;
            break;
    }
    if (!permissionToRecordAccepted ) finish();

}

private void startrec()
{
    Log.e(LOG_TAG, "startRecording:Calling ");
    rec = new MediaRecorder();
    rec.setAudioSource(MediaRecorder.AudioSource.MIC);
    rec.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
    rec.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
    outputfile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/rec.amr";
    rec.setOutputFile(outputfile);
    try {
        rec.prepare();
        rec.start();
    } catch (IOException ioe2) {
    }
    Toast.makeText(MainActivity.this, "RECORDING STARTED", Toast.LENGTH_SHORT).show();

}
private void stoprec(){
    rec.stop();rec.release();
    Toast.makeText(MainActivity.this, "RECORDING STOPPED", Toast.LENGTH_SHORT).show();
    Log.e(LOG_TAG, "stopRecording:Calling ");
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ring = findViewById(R.id.ringbutton);
    record =findViewById(R.id.recordbutton);

    ring.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v1) {
            try {
                Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                r.play();
            } catch (IllegalStateException ise) {}
        }
    });

    record.setOnTouchListener(new View.OnTouchListener(){
        @Override
        public boolean onTouch(View v2, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) startrec();
         else if (event.getAction() == MotionEvent.ACTION_UP) stoprec();
            return true;}
    });
}

}

Problem- app crashes on touching record button

if u know a better way to do this pls tell.


答:
Copy them into object variables in the constructor.

```<code> global $user;
 $this->user = $user;
</code>```

It's not too elegant, anyway, using globals is not too elegant.

Title: How to pass Global variables to classes in PHP?

Body:
Copy them into object variables in the constructor.

 global $user;
 $this->user = $user;

It's not too elegant, anyway, using globals is not too elegant.


问:
How to sort in a group with KnockOut JS
I am heading to sort each item in each group with KnockOut JS. However, only the group worked and the sorting didn't work as my expectation. Please see my code below with comment lines and share me your idea or any guideline.

CSS:

```<code>.displayTable {
  display: table;
  border: 1px solid black;
  border-collapse: collapse;
  width: 100px;
}

.displayRow {
  display: table-row;
}

.displayCell {
  display: table-cell;
  border: 1px solid black;
}

.displayCell.age,
.displayCell.section {
  width: 50px;
}
</code>```

HTML:

```<code><div class="displayTable" data-bind="foreach: choices">
  <div class="displayRow">
    <div class="displayCell" data-bind="text: $data"></div>
    <div class="displayCell">Age</div>
    <div class="displayCell">Phone</div>
  </div>
  <div class="displayRow" data-bind="foreach: $root.people.index.type()[$data]">
    <div class="displayTable">
      <div class="displayRow">
        <div class="displayCell" data-bind="text: name"></div>
        <div class="displayCell" data-bind="text: age"></div>
      </div>
    </div>
  </div>
</div>
</code>```

JS:

```<code>ko.observableArray.fn.distinct = function(prop, sort) {
  var target = this;
  target.index = {};
  target.index[prop] = ko.observable({});

  ko.computed(function() {
    //rebuild index
    var propIndex = {};

    ko.utils.arrayForEach(target(), function(item) {
      var key = ko.utils.unwrapObservable(item[prop]);
      propIndex[key] = propIndex[key] || [];
      propIndex[key].push(item);
    });

        // Sort by age in a group
    //propIndex[key].sort(function(l, r) {
    //  return l.age == r.age ? 0 : (l.age < r.age ? -1 : 1);
    //});

    target.index[prop](propIndex);
  });

  return target;
};

var Person = function(name, type, age) {
  this.name = ko.observable(name);
  this.type = ko.observable(type);
  this.age = ko.observable(age);
}

var ViewModel = function() {
  var self = this;
  this.choices = ["Friend", "Enemy", "Other"];
  this.people = ko.observableArray([
    new Person("Jimmy", "Friend", 35),
    new Person("George", "Friend", 40),
    new Person("Mike", "Friend", 30),
    new Person("Zippy", "Enemy", 20)
  ]).distinct('type', 'sort');

  this.addPerson = function() {
    self.people.push(new Person("new", "Other", 0));
  };

  this.removePerson = function(person) {
    self.people.remove(person);
  };
};

ko.applyBindings(new ViewModel());
</code>```

The result must be:

```<code>Friend:
George  40
Jimmy   35
Mike    30
</code>```

or

```<code>Friend:
Mike    30
Jimmy   35
George  40
</code>```

And it also sorts in all other groups.

Here is my JS Fiddle

答:
The indexes you're trying to sort are object dictionaries not arrays so you'll have to loop through them using a property enumerator. Additionally the properties you're sorting on, "age" in your sample, are observables and have to be unboxed with parenthesis or with ko.unwrap if they aren't always observable.

If you want to used the passed-in sort value to determine which property to sort on I would do something like the following right after the loop that builds the propIndex object.

```<code>// Sort within groups
for(var i in propIndex){
  if(propIndex.hasOwnProperty(i)){
    propIndex[i].sort(function(l, r) {
      return ko.unwrap(l[sort]) == ko.unwrap(r[sort]) ? 0 : (ko.unwrap(l[sort]) < ko.unwrap(r[sort]) ? -1 : 1);
    });
  }
}
</code>```

Title: How to sort in a group with KnockOut JS

Body:
I am heading to sort each item in each group with KnockOut JS. However, only the group worked and the sorting didn't work as my expectation. Please see my code below with comment lines and share me your idea or any guideline.

CSS:

.displayTable {
  display: table;
  border: 1px solid black;
  border-collapse: collapse;
  width: 100px;
}

.displayRow {
  display: table-row;
}

.displayCell {
  display: table-cell;
  border: 1px solid black;
}

.displayCell.age,
.displayCell.section {
  width: 50px;
}

HTML:

Age

Phone

JS:

ko.observableArray.fn.distinct = function(prop, sort) {
  var target = this;
  target.index = {};
  target.index[prop] = ko.observable({});

  ko.computed(function() {
    //rebuild index
    var propIndex = {};

    ko.utils.arrayForEach(target(), function(item) {
      var key = ko.utils.unwrapObservable(item[prop]);
      propIndex[key] = propIndex[key] || [];
      propIndex[key].push(item);
    });

        // Sort by age in a group
    //propIndex[key].sort(function(l, r) {
    //  return l.age == r.age ? 0 : (l.age < r.age ? -1 : 1);
    //});

    target.index[prop](propIndex);
  });

  return target;
};

var Person = function(name, type, age) {
  this.name = ko.observable(name);
  this.type = ko.observable(type);
  this.age = ko.observable(age);
}

var ViewModel = function() {
  var self = this;
  this.choices = ["Friend", "Enemy", "Other"];
  this.people = ko.observableArray([
    new Person("Jimmy", "Friend", 35),
    new Person("George", "Friend", 40),
    new Person("Mike", "Friend", 30),
    new Person("Zippy", "Enemy", 20)
  ]).distinct('type', 'sort');

  this.addPerson = function() {
    self.people.push(new Person("new", "Other", 0));
  };

  this.removePerson = function(person) {
    self.people.remove(person);
  };
};

ko.applyBindings(new ViewModel());

The result must be:

Friend:
George  40
Jimmy   35
Mike    30

or

Friend:
Mike    30
Jimmy   35
George  40

And it also sorts in all other groups.

Here is my JS Fiddle

Body:
The indexes you're trying to sort are object dictionaries not arrays so you'll have to loop through them using a property enumerator. Additionally the properties you're sorting on, "age" in your sample, are observables and have to be unboxed with parenthesis or with ko.unwrap if they aren't always observable.

If you want to used the passed-in sort value to determine which property to sort on I would do something like the following right after the loop that builds the propIndex object.

// Sort within groups
for(var i in propIndex){
  if(propIndex.hasOwnProperty(i)){
    propIndex[i].sort(function(l, r) {
      return ko.unwrap(l[sort]) == ko.unwrap(r[sort]) ? 0 : (ko.unwrap(l[sort]) < ko.unwrap(r[sort]) ? -1 : 1);
    });
  }
}


问:
Reason for using bit manipulation in array size

I have recently got a basic idea of bit manipulation, and I was going through a problem where I found this C++ statement:

```<code>int popcount[1<<16];
</code>```

I do have a basic idea of left/right Bit shift, but I would like to know why it is used in array size place.

答: 1<<16 is a common way to write 2 ** 16, which is easier to verify and modify than the "magic number" 65536. You may also encounter things like 1000 * 1000 instead of 1000000 for the same reason (although C++14 allows for 1000'000).

Body:
I have recently got a basic idea of bit manipulation, and I was going through a problem where I found this C++ statement:

int popcount[1<<16];

I do have a basic idea of left/right Bit shift, but I would like to know why it is used in array size place.


问:
Extending SuperTest
I like to use SuperTest to work with my auth system like this:

```<code>    const request = require('./valid_access_token')(require('supertest'));

    request(app)
    .get('/v1/bots')
    .valid_token()
    .expect('Content-Type', /json/)
    ...
</code>```

valid_token() would insert a valid access-token

```<code>    module.exports = function (Request) {

      const Token = require('../../../app/v1/models/loader')('token');
      const UserFactory = require('../fixtures/user');

      Request.prototype.valid_token = function()
      {

        return UserFactory.createAsync('user')
        .then(function(user){
            return new Token({username: user.username}).createWeeklyAsync()
            .then(function(userToken){
                this.set("access-token",userToken[0].token);
                return this;
            })
        })
       }
       return Request;
    }
</code>```

However, when I run it I get this error:

```<code>TypeError: request(...).get(...).valid_token is not a function
</code>```

I tried various different approaches, no luck.

答:
All the credit goes to https://github.com/acabreragnz

```<code>const request = require('supertest');
const Test = request.Test;

Test.prototype.authenticate = function(user) {
  const {token, xsrfToken} = user.tokens;

  return this
   .set('Authorization', `Bearer ${token}`)
   .set('X-XSRF-TOKEN', xsrfToken);
}
</code>```

Then in your tests

```<code>return request(app)
  .post('/user/settings')
  .authenticate(user)
  .send(...)
</code>```

https://github.com/visionmedia/supertest/issues/381#issuecomment-282198972

Title: Extending SuperTest

Body:
I like to use SuperTest to work with my auth system like this:

    const request = require('./valid_access_token')(require('supertest'));

    request(app)
    .get('/v1/bots')
    .valid_token()
    .expect('Content-Type', /json/)
    ...

valid_token() would insert a valid access-token

    module.exports = function (Request) {

      const Token = require('../../../app/v1/models/loader')('token');
      const UserFactory = require('../fixtures/user');

      Request.prototype.valid_token = function()
      {

        return UserFactory.createAsync('user')
        .then(function(user){
            return new Token({username: user.username}).createWeeklyAsync()
            .then(function(userToken){
                this.set("access-token",userToken[0].token);
                return this;
            })
        })
       }
       return Request;
    }

However, when I run it I get this error:

TypeError: request(...).get(...).valid_token is not a function

I tried various different approaches, no luck.

Body:
All the credit goes to https://github.com/acabreragnz

const request = require('supertest');
const Test = request.Test;

Test.prototype.authenticate = function(user) {
  const {token, xsrfToken} = user.tokens;

  return this
   .set('Authorization', `Bearer ${token}`)
   .set('X-XSRF-TOKEN', xsrfToken);
}

Then in your tests

return request(app)
  .post('/user/settings')
  .authenticate(user)
  .send(...)

https://github.com/visionmedia/supertest/issues/381#issuecomment-282198972


问:
How to perform double sort inside an array?
I don't know the exact term exists for this type of sorting. Here is the problem -
I have a class foo

```<code>class foo:
    def __init__(self,a1,a2):
        self.attrb1 = a1
        self.attrb2 = a2

    def sort(self):
        return self.attrb1
</code>```

An array "bar" contain objects of type foo. I want to sort the array in descending order according to the two attributes. First by attrb1

```<code>bar.sort(key=foo.sort,reverse=True)
</code>```

Then I want to sort the sorted elements within themselves according to attrb2. So for two elements foo1 and foo2 in the array we have -

```<code>foo1 > foo2
if foo1.attrb1 > foo2.attrb1
elif foo1.attrb1 == foo2.attrb1
foo1.attrb2 > foo2.attrb2
</code>```

How can I do this?

答:
You're using classes already so just implement __lt__:

```<code>class foo:
    def __init__(self,a1,a2):
        self.attrb1 = a1
        self.attrb2 = a2

    # just for convenience in `__lt__`
    def defaultorder(self):
        return self.attrb1, self.attrb2

    # answers `self < other`, used by the sorting algorithm
    def __lt__(self, other):
        return self.defaultorder() < other.defaultorder()

bar.sort(reverse=True)
</code>```

Body:
I don't know the exact term exists for this type of sorting. Here is the problem -
I have a class foo

class foo:
    def __init__(self,a1,a2):
        self.attrb1 = a1
        self.attrb2 = a2

    def sort(self):
        return self.attrb1

An array "bar" contain objects of type foo. I want to sort the array in descending order according to the two attributes. First by attrb1

bar.sort(key=foo.sort,reverse=True)

Then I want to sort the sorted elements within themselves according to attrb2. So for two elements foo1 and foo2 in the array we have -

foo1 > foo2
if foo1.attrb1 > foo2.attrb1
elif foo1.attrb1 == foo2.attrb1
foo1.attrb2 > foo2.attrb2

How can I do this?

Body:
You're using classes already so just implement __lt__:

class foo:
    def __init__(self,a1,a2):
        self.attrb1 = a1
        self.attrb2 = a2

    # just for convenience in `__lt__`
    def defaultorder(self):
        return self.attrb1, self.attrb2

    # answers `self < other`, used by the sorting algorithm
    def __lt__(self, other):
        return self.defaultorder() < other.defaultorder()

bar.sort(reverse=True)


问:
Delete whole anchor tag in contenteditable div on one keypress
I have following HTML:

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Document</title>
    </head>
    <body>
        <div id="edit" contenteditable>
            This is <a href="#">link</a> that is editable.
        </div>
    </body>
</html>
</code>```

What I'm trying to do is a very simple text editor where you can put in links (they would get turned into html via JS) but when you hit backspace in the back or delete in front of them, I want it to disappear at once (not deleting anchor text letter by letter).

How would one go about it? My steps with Javascript would be sth like this:

When pressing Backspace key, detect if  is before the cursor, if so run regex on the section before cursor, pick a first match and replace it with blank space.

The opposite, detect if Delete key is pressed, check if  is in front of it and remove it as well.

I'm just not quite sure how to put this in code and also if I can run regex and have it recognize the text in contenteditable area. I'd like to avoid any heavy external libraries because the text editor will not really do much more besides this.

If anybody wants to fork href="http://codepen.io/anon/pen/XdbadP" rel="nofollow">my Codepen here it is.
Thanks for any advice.

答:
There is a clean way to solve this:

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Document</title>
    </head>
    <body>
        <div id="edit" contenteditable>
            This is <a href="#" contenteditable="false">link</a> that is editable.
        </div>
    </body>
</html>
</code>```

Adding a contenteditable="false" will register the anchor as a whole and not letter by letter.

Body:
I have following HTML:

<!DOCTYPE html>

        <meta charset="UTF-8" />
        <title>Document</title>

            This is link that is editable.

What I'm trying to do is a very simple text editor where you can put in links (they would get turned into html via JS) but when you hit backspace in the back or delete in front of them, I want it to disappear at once (not deleting anchor text letter by letter).

How would one go about it? My steps with Javascript would be sth like this:

When pressing Backspace key, detect if  is before the cursor, if so run regex on the section before cursor, pick a first match and replace it with blank space.

The opposite, detect if Delete key is pressed, check if  is in front of it and remove it as well.

I'm just not quite sure how to put this in code and also if I can run regex and have it recognize the text in contenteditable area. I'd like to avoid any heavy external libraries because the text editor will not really do much more besides this.

If anybody wants to fork my Codepen here it is.
Thanks for any advice.

Body:
There is a clean way to solve this:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Document</title>
    </head>
    <body>
        <div id="edit" contenteditable>
            This is <a href="#" contenteditable="false">link</a> that is editable.
        </div>
    </body>
</html>

Adding a contenteditable="false" will register the anchor as a whole and not letter by letter.


问:
Cache full page using Workbox
I'm trying to cache full page using Workbox but it is not working according to my requirement I want to cache not html only I want to cache full page with Image,Js,Css Currently It is caching only html

```<code>workbox.routing.registerRoute('/about.html', new workbox.strategies.NetworkFirst());
</code>```

above code I am using for page cache

答:
Each subresource used on your page (images, JavaScript, CSS, etc.) results in a new HTTP request. The routes that you register will be matched against the URL for each HTTP request. Right now the route you've registered will match the specific URL pathname '/about.html'.

If you'd like to cache absolutely every same-origin request that's made by your webapp, you can adjust your routing logic to use a RegExp wildcard, like:

```<code>workbox.routing.registerRoute(
  new RegExp('/.*'),
  new workbox.strategies.NetworkFirst()
);
</code>```

You can further modify that RegExp if you'd like to narrow down what gets cached, or use a different strategy for different types of URLs.

Title: Cache full page using Workbox

Body:
I'm trying to cache full page using Workbox but it is not working according to my requirement I want to cache not html only I want to cache full page with Image,Js,Css Currently It is caching only html

workbox.routing.registerRoute('/about.html', new workbox.strategies.NetworkFirst());

above code I am using for page cache

Body:
Each subresource used on your page (images, JavaScript, CSS, etc.) results in a new HTTP request. The routes that you register will be matched against the URL for each HTTP request. Right now the route you've registered will match the specific URL pathname '/about.html'.

If you'd like to cache absolutely every same-origin request that's made by your webapp, you can adjust your routing logic to use a RegExp wildcard, like:

workbox.routing.registerRoute(
  new RegExp('/.*'),
  new workbox.strategies.NetworkFirst()
);

You can further modify that RegExp if you'd like to narrow down what gets cached, or use a different strategy for different types of URLs.


答:
What's wrong with your code:

The third level for loop is messed up. It should be removed:

```<code>for (var y = 0; y < employeeData[i][x].length; y++) {
//                                  ^ by the way this should be x not y (not fixing the problem though)
</code>```

because the third level arrays contain 2 elements that you need to use at the same time (as key-value), the for loop for them should be removed.

Fix:

```<code>for (var i = 0; i < employeeData.length; i++) {
    for (var x = 0; x < employeeData[i].length; x++) {
        newObject[employeeData[i][x][0]] = employeeData[i][x][1];
    }
    newArr.push(newObject);
    newObject = {};
}
</code>```

Fixed code example:

var employeeData = [
  [
    ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
  ]
]

function transformData(employeeData) {
  let newObject = {};
  let newArr = [];

  for (var i = 0; i < employeeData.length; i++) {
    for (var x = 0; x < employeeData[i].length; x++) {
        newObject[employeeData[i][x][0]] = employeeData[i][x][1];
    }
    newArr.push(newObject);
    newObject = {};
  }
  return newArr;
}

console.log(transformData(employeeData));```
</div>
</div>
</p>

<p><strong>Alternative solution:</strong></p>

<p>You can <code>map</code> <code>employeeData</code> array into a new array, <code>reduce</code>ing every sub-array into an object like this:</p>

```var result = employeeData.map(function(sub) {
    return sub.reduce(function(obj, pair) {
        obj[ pair[0] ] = pair[1];
        return obj;
    }, {});
});
```

<p>Which can be shortened using ES6's arrow functions to:</p>

```let result = employeeData.map(sub => sub.reduce((obj, pair) => (obj[pair[0]] = pair[1], obj), {}));
```

<p><strong>Example:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let employeeData = [
  [
    ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
  ]
];

let result = employeeData.map(sub => sub.reduce((obj, pair) => (obj[pair[0]] = pair[1], obj), {}));

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

Title: Looping through nested arrays and converting to objects

Body:
I want to convert an group of nested arrays into an array of objects with the collected information from the nested arrays:

BEFORE:

var employeeData = [
  [
    ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
  ]
]

AFTER:

[
  {firstName: 'Bob', lastName: 'Lob', age: 22, role: 'salesperson'},
  {firstName: 'Mary', lastName: 'Joe', age: 32, role: 'director'}
]

Here is the function I wrote to solve this but I can't quite see where the loop is going wrong:

    var employeeData = [
      [
        ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
      ],
      [
        ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
      ]
    ]

    function transformData(employeeData) {
      let newObject = {};
      let newArr = [];

      for (var i = 0; i < employeeData.length; i++) {
        for (var x = 0; x < employeeData[i].length; x++) {
          for (var y = 0; y < employeeData[i][y].length; y++) {
            newObject[employeeData[i][y][0]] = employeeData[i][y][1];
          }
        }
        newArr.push(newObject);
        newObject = {};
      }
      return newArr;
    }

    console.log(transformData(employeeData));

Thanks in advance.

Body:
What's wrong with your code:

The third level for loop is messed up. It should be removed:

for (var y = 0; y < employeeData[i][x].length; y++) {
//                                  ^ by the way this should be x not y (not fixing the problem though)

because the third level arrays contain 2 elements that you need to use at the same time (as key-value), the for loop for them should be removed.

Fix:

for (var i = 0; i < employeeData.length; i++) {
    for (var x = 0; x < employeeData[i].length; x++) {
        newObject[employeeData[i][x][0]] = employeeData[i][x][1];
    }
    newArr.push(newObject);
    newObject = {};
}

Fixed code example:

var employeeData = [
  [
    ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
  ]
]

function transformData(employeeData) {
  let newObject = {};
  let newArr = [];

  for (var i = 0; i < employeeData.length; i++) {
    for (var x = 0; x < employeeData[i].length; x++) {
        newObject[employeeData[i][x][0]] = employeeData[i][x][1];
    }
    newArr.push(newObject);
    newObject = {};
  }
  return newArr;
}

console.log(transformData(employeeData));

Alternative solution:

You can map employeeData array into a new array, reduceing every sub-array into an object like this:

var result = employeeData.map(function(sub) {
    return sub.reduce(function(obj, pair) {
        obj[ pair[0] ] = pair[1];
        return obj;
    }, {});
});

Which can be shortened using ES6's arrow functions to:

let result = employeeData.map(sub => sub.reduce((obj, pair) => (obj[pair[0]] = pair[1], obj), {}));

Example:

let employeeData = [
  [
    ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
  ]
];

let result = employeeData.map(sub => sub.reduce((obj, pair) => (obj[pair[0]] = pair[1], obj), {}));

console.log(result);


问:
Iterate through a table for selenium testing
I want to go through a table and iterate all the rows of the table and want to check validation for a particular columns data, like which date is past date need to identify.

```<code>WebElement tableElement = webDriver.findElement(By.xpath("//[@id='tableID']/tbody/tr"));
    String rowElement = null;

    for(int i = 0; i < 9 ; i ++){
        rowElement = tableElement.findElement(By.xpath("//*[@id='column" + i + "']/td[3]")).getText();
        System.out.println(rowElement.toString());
    }
</code>```

Error i got ->

```<code>org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='tableID']/tbody/tr"}
</code>```

Though I double check the table id and it is correct. I am new to selenium testing. Please help to get the data.

答:
I have not tested the code, but below is the correction I allude to in my comment to your original post:

```<code>WebElement tableElement = webDriver.findElement(By.xpath("//*[@id='tableID']/tbody/tr"));
    String rowElement = null;

    for(int i = 0; i < 9 ; i ++){
        rowElement = tableElement.findElement(By.xpath("//*[@id='column" + i + "']/td[3]")).getText();
        System.out.println(rowElement.toString());
    }
</code>```

Although I think it would probably be best to create an array of table records:

```<code>List <WebElement> rows = webDriver.findElements(By.xpath("//tr[@id='tableID']");

for (int i = 0; i < rows.size(); i++) {
   String rowElement = rows.get(i).findElement(By.xpath("//*[@id='column" + i + "']/td[3]")).getText();
}
</code>```

The above is also "air code" and not tested, might contain typos, take it as more psuedo code.

Body:
I want to go through a table and iterate all the rows of the table and want to check validation for a particular columns data, like which date is past date need to identify.

WebElement tableElement = webDriver.findElement(By.xpath("//[@id='tableID']/tbody/tr"));
    String rowElement = null;

    for(int i = 0; i < 9 ; i ++){
        rowElement = tableElement.findElement(By.xpath("//*[@id='column" + i + "']/td[3]")).getText();
        System.out.println(rowElement.toString());
    }

Error i got ->

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='tableID']/tbody/tr"}

Though I double check the table id and it is correct. I am new to selenium testing. Please help to get the data.

Body:
I have not tested the code, but below is the correction I allude to in my comment to your original post:

WebElement tableElement = webDriver.findElement(By.xpath("//*[@id='tableID']/tbody/tr"));
    String rowElement = null;

    for(int i = 0; i < 9 ; i ++){
        rowElement = tableElement.findElement(By.xpath("//*[@id='column" + i + "']/td[3]")).getText();
        System.out.println(rowElement.toString());
    }

Although I think it would probably be best to create an array of table records:

List <WebElement> rows = webDriver.findElements(By.xpath("//tr[@id='tableID']");

for (int i = 0; i < rows.size(); i++) {
   String rowElement = rows.get(i).findElement(By.xpath("//*[@id='column" + i + "']/td[3]")).getText();
}

The above is also "air code" and not tested, might contain typos, take it as more psuedo code.


问:
Error column ambiguously defined with inner join
So I am trying to use inner join for 3 tables and I am getting the already specified error. Here is what I did:

```<code>SELECT phone
   INTO v_phone
FROM PEOPLE
  INNER JOIN Family ON PEOPLE.ID=FAMILY.ID
  INNER JOIN PETS ON FAMILY.ID=PETS.ID
WHERE PETS.ID=:NEW.ID;
</code>```

what is the issue here..

答:
Is PHONE from FAMILY, PEOPLE or PETS table? That is what the error is - it does not know which table to get phone from.

Ambiguous means that it cannot decide...It could be a choice of many, and it doesn't know which one to choose as it needs more information. Ambiguously defined means the field has too little information (it needs a Table Alias also)

Use PEOPLE.PHONE perhaps, depending on which phone value you need

Body:
So I am trying to use inner join for 3 tables and I am getting the already specified error. Here is what I did:

SELECT phone
   INTO v_phone
FROM PEOPLE
  INNER JOIN Family ON PEOPLE.ID=FAMILY.ID
  INNER JOIN PETS ON FAMILY.ID=PETS.ID
WHERE PETS.ID=:NEW.ID;

what is the issue here..


问:
Python "yield" keyword to calculate
A bar shop has a ten-day promotion. During this period, the price of an beer drops 10 percent each day. For example, a beer that costs 10$ on the first day costs $9 on the second day and $8.1 on the third day.

I want to write a python function that uses yield keyword to calculate beer price each day.

For instance if we give input 10,
My expected output is:

```<code>Price is discounted to : 9

Price is discounted to : 8.1
</code>```

..etc

```<code>class DiscountCalc:
    def get_item_price(self):
        return input('Input a starting price (0 to quit): ')

    def discount(self, current_price, days):
        yield (current_price - (current_price*10)//100)

    def run(self):
        initial = self.get_item_price()
        for price in self.discount(initial, 10):
            print "Price is discounted to : " + str(price)

DiscountCalc().run()
</code>```

答:
it's due to the cycle, this should fix it:</p>

```<code>def discount(self, current_price, days):
    for day in range(days):
        yield current_price
        current_price = current_price * 0.9

def run(self):
    initial = self.get_item_price()
    for price in self.discount(initial, 10):
        print(price)
</code>```

Title: Python "yield" keyword to calculate

Body:
A bar shop has a ten-day promotion. During this period, the price of an beer drops 10 percent each day. For example, a beer that costs 10$ on the first day costs $9 on the second day and $8.1 on the third day.

I want to write a python function that uses yield keyword to calculate beer price each day.

For instance if we give input 10,
My expected output is:

Price is discounted to : 9

Price is discounted to : 8.1

..etc

class DiscountCalc:
    def get_item_price(self):
        return input('Input a starting price (0 to quit): ')

    def discount(self, current_price, days):
        yield (current_price - (current_price*10)//100)

    def run(self):
        initial = self.get_item_price()
        for price in self.discount(initial, 10):
            print "Price is discounted to : " + str(price)

DiscountCalc().run()

Body:
it's due to the cycle, this should fix it:

def discount(self, current_price, days):
    for day in range(days):
        yield current_price
        current_price = current_price * 0.9

def run(self):
    initial = self.get_item_price()
    for price in self.discount(initial, 10):
        print(price)


问:
Rand Implementation
I would like to go through how rand() and srand() functions are implemented and would like to tweak the code to modify it to my requirements. Where can i find the source code of rand() and srand(). </p>

答:
The glibc one (used by gcc) is the simple formula:

```<code>x = 1103515245 * x + 12345
</code>```

wrapping around at 232, as shown here. You can just set x as the seed then keep calling a function to evaluate that expression (and update the seed).

But you should be aware the linear congruential generators like this are considered adequate but not ideal.

While the only ideal random number generator would be perfectly random, the Mersenne Twister probably comes closer.

Title: Rand Implementation

Body:
The glibc one (used by gcc) is the simple formula:

x = 1103515245 * x + 12345

wrapping around at 232, as shown here. You can just set x as the seed then keep calling a function to evaluate that expression (and update the seed).

But you should be aware the linear congruential generators like this are considered adequate but not ideal.

While the only ideal random number generator would be perfectly random, the Mersenne Twister probably comes closer.


问:
Spring MVC: How to return image in @ResponseBody?
I'm getting image data (as byte[]) from DB. How to return this image in @ResponseBody ?

EDIT

I did it without @ResponseBody using HttpServletResponse as method parameter:

```<code>@RequestMapping("/photo1")
public void photo(HttpServletResponse response) throws IOException {
    response.setContentType("image/jpeg");
    InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
    IOUtils.copy(in, response.getOutputStream());
}
</code>```

Using @ResponseBody with registered org.springframework.http.converter.ByteArrayHttpMessageConverter converter as @Sid said doesn't work for me :(.

```<code>@ResponseBody
@RequestMapping("/photo2")
public byte[] testphoto() throws IOException {
    InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
    return IOUtils.toByteArray(in);
}
</code>```

答:
I think you maybe need a service to store file upload and get that file.
Check more detail from here

1) Create a Storage Sevice

```<code>@Service
public class StorageService {

Logger log = LoggerFactory.getLogger(this.getClass().getName());
private final Path rootLocation = Paths.get("upload-dir");

public void store(MultipartFile file) {
    try {
        Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
    } catch (Exception e) {
        throw new RuntimeException("FAIL!");
    }
}

public Resource loadFile(String filename) {
    try {
        Path file = rootLocation.resolve(filename);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        } else {
            throw new RuntimeException("FAIL!");
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException("FAIL!");
    }
}

public void deleteAll() {
    FileSystemUtils.deleteRecursively(rootLocation.toFile());
}

public void init() {
    try {
        Files.createDirectory(rootLocation);
    } catch (IOException e) {
        throw new RuntimeException("Could not initialize storage!");
    }
}
}
</code>```

2) Create Rest Controller to upload and get file

```<code>@Controller
public class UploadController {

@Autowired
StorageService storageService;

List<String> files = new ArrayList<String>();

@PostMapping("/post")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
    String message = "";
    try {
        storageService.store(file);
        files.add(file.getOriginalFilename());

        message = "You successfully uploaded " + file.getOriginalFilename() + "!";
        return ResponseEntity.status(HttpStatus.OK).body(message);
    } catch (Exception e) {
        message = "FAIL to upload " + file.getOriginalFilename() + "!";
        return      ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
    }
}

@GetMapping("/getallfiles")
public ResponseEntity<List<String>> getListFiles(Model model) {
    List<String> fileNames = files
            .stream().map(fileName -> MvcUriComponentsBuilder
                    .fromMethodName(UploadController.class, "getFile", fileName).build().toString())
            .collect(Collectors.toList());

    return ResponseEntity.ok().body(fileNames);
}

@GetMapping("/files/{filename:.+}")
@ResponseBody
public ResponseEntity<Resource> getFile(@PathVariable String filename) {
    Resource file = storageService.loadFile(filename);
    return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
            .body(file);
}
</code>```

}

Body:
I'm getting image data (as byte[]) from DB. How to return this image in @ResponseBody ?

EDIT

I did it without @ResponseBody using HttpServletResponse as method parameter:

@RequestMapping("/photo1")
public void photo(HttpServletResponse response) throws IOException {
    response.setContentType("image/jpeg");
    InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
    IOUtils.copy(in, response.getOutputStream());
}

Using @ResponseBody with registered org.springframework.http.converter.ByteArrayHttpMessageConverter converter as @Sid said doesn't work for me :(.

@ResponseBody
@RequestMapping("/photo2")
public byte[] testphoto() throws IOException {
    InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
    return IOUtils.toByteArray(in);
}

Body:
I think you maybe need a service to store file upload and get that file.
Check more detail from here

1) Create a Storage Sevice

@Service
public class StorageService {

Logger log = LoggerFactory.getLogger(this.getClass().getName());
private final Path rootLocation = Paths.get("upload-dir");

public void store(MultipartFile file) {
    try {
        Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
    } catch (Exception e) {
        throw new RuntimeException("FAIL!");
    }
}

public Resource loadFile(String filename) {
    try {
        Path file = rootLocation.resolve(filename);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        } else {
            throw new RuntimeException("FAIL!");
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException("FAIL!");
    }
}

public void deleteAll() {
    FileSystemUtils.deleteRecursively(rootLocation.toFile());
}

public void init() {
    try {
        Files.createDirectory(rootLocation);
    } catch (IOException e) {
        throw new RuntimeException("Could not initialize storage!");
    }
}
}

2) Create Rest Controller to upload and get file

@Controller
public class UploadController {

@Autowired
StorageService storageService;

List<String> files = new ArrayList<String>();

@PostMapping("/post")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
    String message = "";
    try {
        storageService.store(file);
        files.add(file.getOriginalFilename());

        message = "You successfully uploaded " + file.getOriginalFilename() + "!";
        return ResponseEntity.status(HttpStatus.OK).body(message);
    } catch (Exception e) {
        message = "FAIL to upload " + file.getOriginalFilename() + "!";
        return      ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
    }
}

@GetMapping("/getallfiles")
public ResponseEntity<List<String>> getListFiles(Model model) {
    List<String> fileNames = files
            .stream().map(fileName -> MvcUriComponentsBuilder
                    .fromMethodName(UploadController.class, "getFile", fileName).build().toString())
            .collect(Collectors.toList());

    return ResponseEntity.ok().body(fileNames);
}

@GetMapping("/files/{filename:.+}")
@ResponseBody
public ResponseEntity<Resource> getFile(@PathVariable String filename) {
    Resource file = storageService.loadFile(filename);
    return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
            .body(file);
}

}


问:
Using Css to prevent wrapping of text with previous text?
Is there a CSS way to prevent a text element from wrapping from a previous text element?

i.e.
My Table Header  shows as

My

Table

Header

MySearchIcon

But I want it to display like this:

My

Table

Header MySearchIcon

The actual code is a combination of Razor and Html

```<code>  <th>
   @Html.DisplayNameFor(m => m.Projects.FirstOrDefault().Name) <i class="fa fa-search smaller fa-fade"></i>
  </th>
</code>```

This is in a header of a table and depending on the header length I do want wrapping but I want a space and the icon to be stuck to the last word in the header and not wrap.

Because of the Razor piece of the code I can't place the non-breaking space up against the output directly,

答:
The solution ended up being to add a  element after the razor code.
i.e.</p>

```<code> <th>
   @Html.DisplayNameFor(m => m.Projects.FirstOrDefault().Name)<text> <i class="fa fa-search smaller fa-fade"></i></text>
  </th>
</code>```

Body:
Is there a CSS way to prevent a text element from wrapping from a previous text element?

i.e.
My Table Header  shows as

My

Table

Header

MySearchIcon

But I want it to display like this:

My

Table

Header MySearchIcon

The actual code is a combination of Razor and Html

   @Html.DisplayNameFor(m => m.Projects.FirstOrDefault().Name)

This is in a header of a table and depending on the header length I do want wrapping but I want a space and the icon to be stuck to the last word in the header and not wrap.

Because of the Razor piece of the code I can't place the non-breaking space up against the output directly,

Body:
The solution ended up being to add a  element after the razor code.
i.e.

 <th>
   @Html.DisplayNameFor(m => m.Projects.FirstOrDefault().Name)<text>&nbsp;<i class="fa fa-search smaller fa-fade"></i></text>
  </th>


问:
Run and process a while loop while a process is running Java 7
I have a C program that sends a message to java program (via MQ) the java program runs another program and sends status messages back to the C program what that other program is running.  The program works and does exactly what I want.  However, I've moved all of this to a new server that is running Java 7 (upgrading java version is not an option now) and I quickly came to discover that the isAlive() method I was using isn't available in Java 7 for the Process class, its only in Java 8.  How would I rewrite this code to work with Java 7</p>

```<code>try {
   Process p = null;
                        p = run.exec(prog, env, new File(config.getProperty("ROOTDIR")));
                } catch (IOException e) {
                        PCHLog.log(new RCReply("C5014", e));
                }
                String dsp = " \\";

                while(p.isAlive()){
                        Messenger.sendMessage(message + dsp, reply2q);
                        if (dsp.equals(" \\")){
                                dsp = " /";
                        }
                        else {
                                dsp = " \\";
                        }
                        Thread.sleep(1000);
                }
</code>```

答:
In this question, you will find an interesting solution. In essence, you ask for exitValue() to check if the process is still alive.

```<code>boolean isRunning(Process process) {
    try {
        process.exitValue();
        return false;
    } catch (Exception e) {
        return true;
    }
}
</code>```

Body:
I have a C program that sends a message to java program (via MQ) the java program runs another program and sends status messages back to the C program what that other program is running.  The program works and does exactly what I want.  However, I've moved all of this to a new server that is running Java 7 (upgrading java version is not an option now) and I quickly came to discover that the isAlive() method I was using isn't available in Java 7 for the Process class, its only in Java 8.  How would I rewrite this code to work with Java 7

try {
   Process p = null;
                        p = run.exec(prog, env, new File(config.getProperty("ROOTDIR")));
                } catch (IOException e) {
                        PCHLog.log(new RCReply("C5014", e));
                }
                String dsp = " \\";

                while(p.isAlive()){
                        Messenger.sendMessage(message + dsp, reply2q);
                        if (dsp.equals(" \\")){
                                dsp = " /";
                        }
                        else {
                                dsp = " \\";
                        }
                        Thread.sleep(1000);
                }

Body:
In this question, you will find an interesting solution. In essence, you ask for exitValue() to check if the process is still alive.

boolean isRunning(Process process) {
    try {
        process.exitValue();
        return false;
    } catch (Exception e) {
        return true;
    }
}


问:
Explicit ack to JMS using Alpakka
I am currently using Akka-Camel for integrating my Akka based application with various message queues.

Now that I want to upgrade to the latest version of Akka I see that this integration is now deprecated.

I have tried using alpakka-jsm integration but am unable to see whether I can perform explicit ack to the message queues once I have processed the message. Does this functionality exist in this new component?

答:
Alpakka 0.15 makes the acknowledgement mode in the JMS connector configurable. An example that's adapted from the linked documentation:

val jmsSource: Source[Message, NotUsed] = JmsSource(
  JmsSourceSettings(connectionFactory)
    .withQueue("myqueue")
    .withAcknowledgeMode(AcknowledgeMode.ClientAcknowledge)
)

val result = jmsSource
  .map {
    case textMessage: TextMessage =>
      val text = textMessage.getText
      textMessage.acknowledge()
      text
  }
  .runWith(Sink.seq)
```

Title: Explicit ack to JMS using Alpakka


问:
prepare data for CNTK LSTM
Hi I want to prepare my data, which will be then used to learn LSTM network.

I use pandas and numpy arrays.

I have csv file which i read like

```<code>df = pd.read_csv("data.csv",....)
</code>```

That csv file contains values of wind direction and hour of day and some other values...

Hour of day is represented as integer from 0 to 24. I need it to be represented by values of sinus and cosinus.

Wind direction is represented as one or two characters like: NW, N, SE, etc..
(NW - northwest, N - north, ... etc) - I need it to be represented by values of sinus and cosinus as well.

I am a newbie in pandas, python and everything mentioned here...

Thak you for any help.

答:
So i figured it out...

I will just create two values from one. "Time" will be represented by two values, one sinus and other cosinus and they will feed my LSTM...

I will do the same with "wind direction"..

(i will do this manually with external script and then read csv with pandas...)

Title: prepare data for CNTK LSTM

Body:
Hi I want to prepare my data, which will be then used to learn LSTM network.

I use pandas and numpy arrays.

I have csv file which i read like

df = pd.read_csv("data.csv",....)

That csv file contains values of wind direction and hour of day and some other values...

Hour of day is represented as integer from 0 to 24. I need it to be represented by values of sinus and cosinus.

Wind direction is represented as one or two characters like: NW, N, SE, etc..
(NW - northwest, N - north, ... etc) - I need it to be represented by values of sinus and cosinus as well.

I am a newbie in pandas, python and everything mentioned here...

Thak you for any help.


问:
Unable to save data in child activity android studio
After entering the details in EditText in child activity when I go back to parent activity and comes back to child activity the EditText value is becoming blank. I have used below mentioned code, but no use.

Below mentioned is childactivity.java details.

Can anyone help in this.

```<code>import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

public class NotesActivity extends AppCompatActivity {
    String typedText;
    EditText inputTxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes);
        inputTxt = (EditText) findViewById(R.id.notes1);
    }

    @Override
    protected void onPause() {
        super.onPause();
        typedText = inputTxt.getText().toString();
    }

    @Override
    protected void onResume() {
        super.onResume();
        inputTxt.setText(typedText);
    }
}
</code>```

答:
When you destroy the activity even if you are setting typedText to something it will become null because the next time you launch this activity from other, a new instance will be created and old data will be lost.
You have to store data with persistent storage options.
https://developer.android.com/guide/topics/data/data-storage.html

To store data in SharedPreferences you can modify following code.

```<code>private final String PREFS_NAME = "packageName";

SharedPreferences sharedPref = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("typedText", inputTxt.getText().toString());
editor.commit();
</code>```

And to retrieve the value you can do as following.

```<code>SharedPreferences sharedPref = getSharedPreferences(PREFS_NAME, 0);
String typedValue = sharedPref.getString("typedText", "defaultValue/null");
</code>```

Body:
After entering the details in EditText in child activity when I go back to parent activity and comes back to child activity the EditText value is becoming blank. I have used below mentioned code, but no use.

Below mentioned is childactivity.java details.

Can anyone help in this.

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

public class NotesActivity extends AppCompatActivity {
    String typedText;
    EditText inputTxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes);
        inputTxt = (EditText) findViewById(R.id.notes1);
    }

    @Override
    protected void onPause() {
        super.onPause();
        typedText = inputTxt.getText().toString();
    }

    @Override
    protected void onResume() {
        super.onResume();
        inputTxt.setText(typedText);
    }
}

Body:
When you destroy the activity even if you are setting typedText to something it will become null because the next time you launch this activity from other, a new instance will be created and old data will be lost.
You have to store data with persistent storage options.
https://developer.android.com/guide/topics/data/data-storage.html

To store data in SharedPreferences you can modify following code.

private final String PREFS_NAME = "packageName";

SharedPreferences sharedPref = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("typedText", inputTxt.getText().toString());
editor.commit();

And to retrieve the value you can do as following.

SharedPreferences sharedPref = getSharedPreferences(PREFS_NAME, 0);
String typedValue = sharedPref.getString("typedText", "defaultValue/null");


问:
Extra tabstop on VSCode snippet with choices
I have a snippet that stops an "extra" time. it's been annoying me, so I'm hoping someone can help me clear it up here.

```<code>"pylint": {
    "prefix": "pylint",
    "body": "# pylint: ${1|disable,enable|}=${2|R0102\\, simplifiable-if-statement,R0101\\,too-many-nested-blocks|}",
    "description": "Add a pylint comment"
},
</code>```

For some reason it stops on [disable, enable], then on = ?!, and then again (appropriately) on [R0102, simplifiable-if-statement, R0101, too-many-nested-blocks]. why is it stopping on the equals sign?

答:
Maybe something like this will work:

Extension macros

settings.json

"macros": {
    "jumpToNextSnippetPlaceholder": [
        "acceptSelectedSuggestion",
        "jumpToNextSnippetPlaceholder"
    ]
}
```

<p><code>keybindings.json</code></p>

<pre class="lang-json prettyprint-override"><code>{
    "command": "macros.jumpToNextSnippetPlaceholder",
    "key": "tab",
    "when": "editorTextFocus && hasNextTabstop && inSnippetMode && !editorTabMovesFocus && suggestWidgetVisible"
}
</code>```

Body:
I have a snippet that stops an "extra" time. it's been annoying me, so I'm hoping someone can help me clear it up here.

"pylint": {
    "prefix": "pylint",
    "body": "# pylint: ${1|disable,enable|}=${2|R0102\\, simplifiable-if-statement,R0101\\,too-many-nested-blocks|}",
    "description": "Add a pylint comment"
},

For some reason it stops on [disable, enable], then on = ?!, and then again (appropriately) on [R0102, simplifiable-if-statement, R0101, too-many-nested-blocks]. why is it stopping on the equals sign?

Body:
Maybe something like this will work:

Extension macros

settings.json

"macros": {
    "jumpToNextSnippetPlaceholder": [
        "acceptSelectedSuggestion",
        "jumpToNextSnippetPlaceholder"
    ]
}

keybindings.json

{
    "command": "macros.jumpToNextSnippetPlaceholder",
    "key": "tab",
    "when": "editorTextFocus && hasNextTabstop && inSnippetMode && !editorTabMovesFocus && suggestWidgetVisible"
}


问:
Looping through nested arrays and converting to objects
I want to convert an group of nested arrays into an array of objects with the collected information from the nested arrays:

BEFORE:

```<code>var employeeData = [
  [
    ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
  ]
]
</code>```

AFTER:

```<code>[
  {firstName: 'Bob', lastName: 'Lob', age: 22, role: 'salesperson'},
  {firstName: 'Mary', lastName: 'Joe', age: 32, role: 'director'}
]
</code>```

Here is the function I wrote to solve this but I can't quite see where the loop is going wrong:

    var employeeData = [
      [
        ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
      ],
      [
        ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
      ]
    ]

    function transformData(employeeData) {
      let newObject = {};
      let newArr = [];

      for (var i = 0; i < employeeData.length; i++) {
        for (var x = 0; x < employeeData[i].length; x++) {
          for (var y = 0; y < employeeData[i][y].length; y++) {
            newObject[employeeData[i][y][0]] = employeeData[i][y][1];
          }
        }
        newArr.push(newObject);
        newObject = {};
      }
      return newArr;
    }

    console.log(transformData(employeeData));```

Thanks in advance.

答:
You may just want to use a Map instead of an Object for each set of values in the outer array.

Then it's a very simple conversion of new Map(data);. Maps were added to the spec for these kinds of datasets.

var employeeData = [
  [['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']],
  [['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']]
];

const res = employeeData.map(a => new Map(a));

for (const m of res) {
 console.log(m.get("firstName"));
}```
</div>
</div>
</p>

<p>But if you do ultimately want <code>Object</code> types in the array, then you can convert the each <code>Map()</code>.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var employeeData = [
  [['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']],
  [['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']]
];

const res = employeeData.map(a => new Map(a));

for (const m of res) {
 console.log(m.get("firstName"));
}

const oRes = res.map(m => Object.assign({}, ...Array.from(m.entries()).map(([k,v]) => ({[k]:v}))));

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

Body:
I want to convert an group of nested arrays into an array of objects with the collected information from the nested arrays:

BEFORE:

var employeeData = [
  [
    ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
  ]
]

AFTER:

[
  {firstName: 'Bob', lastName: 'Lob', age: 22, role: 'salesperson'},
  {firstName: 'Mary', lastName: 'Joe', age: 32, role: 'director'}
]

Here is the function I wrote to solve this but I can't quite see where the loop is going wrong:

    var employeeData = [
      [
        ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
      ],
      [
        ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
      ]
    ]

    function transformData(employeeData) {
      let newObject = {};
      let newArr = [];

      for (var i = 0; i < employeeData.length; i++) {
        for (var x = 0; x < employeeData[i].length; x++) {
          for (var y = 0; y < employeeData[i][y].length; y++) {
            newObject[employeeData[i][y][0]] = employeeData[i][y][1];
          }
        }
        newArr.push(newObject);
        newObject = {};
      }
      return newArr;
    }

    console.log(transformData(employeeData));

Thanks in advance.

Body:
You may just want to use a Map instead of an Object for each set of values in the outer array.

Then it's a very simple conversion of new Map(data);. Maps were added to the spec for these kinds of datasets.

var employeeData = [
  [['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']],
  [['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']]
];

const res = employeeData.map(a => new Map(a));

for (const m of res) {
 console.log(m.get("firstName"));
}

But if you do ultimately want Object types in the array, then you can convert the each Map().

var employeeData = [
  [['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']],
  [['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']]
];

const res = employeeData.map(a => new Map(a));

for (const m of res) {
 console.log(m.get("firstName"));
}

const oRes = res.map(m => Object.assign({}, ...Array.from(m.entries()).map(([k,v]) => ({[k]:v}))));

console.log(oRes);