问:
R trouble reshaping matrix to 1 column, byrow T or F same result
```<code>m <- matrix(1:9,3,3, byrow = TRUE)
m
m2 <- matrix(m, ncol = 1, byrow = TRUE)
m2
m3 <- matrix(m, ncol = 1, byrow = FALSE)
m3
identical(m2,m3)
desiredM <- matrix(t(m), ncol = 1)
desiredM
</code>```

I create a matrix, and want to create a new matrix 1 column wide, with data filled in by going across, then using the next row down, going across, then next row down and across...ect...

I would assume m2 would yield my desired result, but it doesn't.

I am further puzzled as setting byrow TRUE or FALSE doesn't seem to have an effect.

Thank you for taking time to clarifying this behavior, which must be right, once properly understood.

Body:
m <- matrix(1:9,3,3, byrow = TRUE)
m
m2 <- matrix(m, ncol = 1, byrow = TRUE)
m2
m3 <- matrix(m, ncol = 1, byrow = FALSE)
m3
identical(m2,m3)
desiredM <- matrix(t(m), ncol = 1)
desiredM

I create a matrix, and want to create a new matrix 1 column wide, with data filled in by going across, then using the next row down, going across, then next row down and across...ect...

I would assume m2 would yield my desired result, but it doesn't.

I am further puzzled as setting byrow TRUE or FALSE doesn't seem to have an effect.

Thank you for taking time to clarifying this behavior, which must be right, once properly understood.

Body:
matrix(t(m), ncol = 1)

      [,1]
 [1,]    1
 [2,]    2
 [3,]    3
 [4,]    4
 [5,]    5
 [6,]    6
 [7,]    7
 [8,]    8
 [9,]    9


来源: stackexchange

问:
React/Express - required props 'undefined' in match/RouterContext
I'm working on implementing server-side rendering for my React/Express app - the app is actually working as desired, but I'm getting a warning on my server related to match() and RouterContext that I'd like to understand and resolve.

Basically, in the callback function for match, the arguments (err, redirect, props) are all evaluating as undefined.

index.js (Express app root):

```<code>'use strict'
require('babel-register')({
    presets: ['es2015', 'react']
});

const express = require('express')
const path = require('path')
const app = express()
const React = require('react')
const reactDomServer = require('react-dom/server')
const routes = require('./src/routes.jsx')
const reactRouter = require('react-router')
let { match, RouterContext, createRoutes } = reactRouter

app.get('*', (req, res) => {
    match({ routes: createRoutes(routes), location: req.url }, (err, redirect, props) => {
        const appHtml = renderToString(React.createElement(RouterContext, props))
        res.send(renderPage(appHtml))
    })
})
</code>```

So if I throw a console.log() in for err, redirect, and props, they all come back as undefined. This causes my server to return the warning

```<code>Warning: Failed prop type: The prop `router` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `location` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `routes` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `params` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `components` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed child context type: The child context `router` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
</code>```

Again, to my surprise, my app seems to work just fine - I can refresh pages, access urls directly (i.e. 'localhost:3000/person/1234'), but these warnings persist. Maybe I don't understand the needs of RouterContext (likely).

Regardless, I would like to resolve this, because I want to use those arguments to set up some conditionals... any guidance on this would be much appreciated.

Update
I've realized that err and redirect are supposed to default to undefined (unless there's an error or redirect), but no matter what I do, props seems to be stuck on undefined as well.

From https://knowbody.github.io/react-router-docs/api/match.html: "If all three parameters are undefined, this means that there was no route found matching the given location."

But I don't understand - the app seems to work fine. What gives?

答:
createRoutes has been removed from react-router (few releases ago).

```<code>let { match, RouterContext, createRoutes } = reactRouter
// 'createRoutes' is undefined
</code>```

You should create/prepare your routes manually and export it as a standalone module (the snippet below is taken from the official docs)

```<code>module.exports = (
  <Route path="/" component={App}>
    <IndexRoute component={Home}/>
    <Route path="/repos" component={Repos}>
      <Route path="/repos/:userName/:repoName" component={Repo}/>
    </Route>
    <Route path="/about" component={About}/>
  </Route>
)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on implementing server-side rendering for my React/Express app - the app is actually working as desired, but I'm getting a warning on my server related to match() and RouterContext that I'd like to understand and resolve.

Basically, in the callback function for match, the arguments (err, redirect, props) are all evaluating as undefined.

index.js (Express app root):

'use strict'
require('babel-register')({
    presets: ['es2015', 'react']
});

const express = require('express')
const path = require('path')
const app = express()
const React = require('react')
const reactDomServer = require('react-dom/server')
const routes = require('./src/routes.jsx')
const reactRouter = require('react-router')
let { match, RouterContext, createRoutes } = reactRouter

app.get('*', (req, res) => {
    match({ routes: createRoutes(routes), location: req.url }, (err, redirect, props) => {
        const appHtml = renderToString(React.createElement(RouterContext, props))
        res.send(renderPage(appHtml))
    })
})

So if I throw a console.log() in for err, redirect, and props, they all come back as undefined. This causes my server to return the warning

Warning: Failed prop type: The prop `router` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `location` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `routes` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `params` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed prop type: The prop `components` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext
Warning: Failed child context type: The child context `router` is marked as required in `RouterContext`, but its value is `undefined`.
    in RouterContext

Again, to my surprise, my app seems to work just fine - I can refresh pages, access urls directly (i.e. 'localhost:3000/person/1234'), but these warnings persist. Maybe I don't understand the needs of RouterContext (likely).

Regardless, I would like to resolve this, because I want to use those arguments to set up some conditionals... any guidance on this would be much appreciated.

Update
I've realized that err and redirect are supposed to default to undefined (unless there's an error or redirect), but no matter what I do, props seems to be stuck on undefined as well.

From https://knowbody.github.io/react-router-docs/api/match.html: "If all three parameters are undefined, this means that there was no route found matching the given location."

But I don't understand - the app seems to work fine. What gives?

Body:
createRoutes has been removed from react-router (few releases ago).

let { match, RouterContext, createRoutes } = reactRouter
// 'createRoutes' is undefined

You should create/prepare your routes manually and export it as a standalone module (the snippet below is taken from the official docs)

module.exports = (
  <Route path="/" component={App}>
    <IndexRoute component={Home}/>
    <Route path="/repos" component={Repos}>
      <Route path="/repos/:userName/:repoName" component={Repo}/>
    </Route>
    <Route path="/about" component={About}/>
  </Route>
)


问:
Name of a symmetric matrix with zeroes in the diagonal
I am looking for a term that can be used for a matrix with the diagonal line equal to zeros and the upper and lower triangles are symmetric.

for example if I have a matrix of size 5 by 5 the matrix will be as following:

```<code>0 1 2 3 4
1 0 5 6 7
2 5 0 8 9
3 6 8 0 10
4 7 9 10 0
</code>```

Is there a term for this matrix?

答:
It is a Zero-diagonal-symmetric-matrice, also known as hollow symmetric (or hermitian) matrice.

Reference here - https://math.stackexchange.com/questions/79779/properties-of-zero-diagonal-symmetric-matrices

Body:
I am looking for a term that can be used for a matrix with the diagonal line equal to zeros and the upper and lower triangles are symmetric.

for example if I have a matrix of size 5 by 5 the matrix will be as following:

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

Is there a term for this matrix?


问:
How to make Responsive button with Bootstrap
I'm Trying to have submit button center the page.
my code in html is:

```<code><div class="container-fluid">
<div class="row" style="margin-right:0;margin-left:0">

<form method="POST"
      action="https://api.instagram.com/oauth/authorize/redirect_uri=http://hanie-asemi.ir/laravel/public/instagram/test&response_type=code">
    {{csrf_field()}}

    <button type="submit" class="btn btn-primary submit">Submit</button>
</form>
</div>
</code>```

I give the submit button center in desktop but this button Not at the center in mobile!what can I do to centered button in mobile?

答:
Since Bootstrap 2.3.0 you can use .text-center, like this:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

    <form method="POST" action="https://api.instagram.com/oauth/authorize/redirect_uri=http://hanie-asemi.ir/laravel/public/instagram/test&response_type=code">
      {{csrf_field()}}

        <button type="submit" class="btn btn-primary submit">Submit</button>

    </form>

```

Body:
I'm Trying to have submit button center the page.
my code in html is:

<form method="POST"
      action="https://api.instagram.com/oauth/authorize/redirect_uri=http://hanie-asemi.ir/laravel/public/instagram/test&response_type=code">
    {{csrf_field()}}

    <button type="submit" class="btn btn-primary submit">Submit</button>
</form>

I give the submit button center in desktop but this button Not at the center in mobile!what can I do to centered button in mobile?

Body:
Since Bootstrap 2.3.0 you can use .text-center, like this:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container-fluid">
  <div class="row" style="margin-right:0;margin-left:0">

    <form method="POST" action="https://api.instagram.com/oauth/authorize/redirect_uri=http://hanie-asemi.ir/laravel/public/instagram/test&response_type=code">
      {{csrf_field()}}

      <div class="row text-center">
        <button type="submit" class="btn btn-primary submit">Submit</button>
      </div>
    </form>
  </div>


问:
Getting undefined method when trying to use a ruby wrapper for the Spotify Web API
I was messing around with RSpotify which is a ruby wrapper for the Spotify API.

I added a form and sent the search result param to be looked up in the API but i'm getting the following error:

```<code>NoMethodError: undefined method `empty?' for nil:NilClass
from /Users/user/.rvm/gems/ruby-2.3.1/gems/rspotify-1.21.0/lib/rspotify/connection.rb:71:in `send_request'
</code>```

I double checked and reinstalled the gem, added it to the gemfile and everything. I can't seem to figure out why it's not working.

Here's the code (It was working a few weeks ago when I wrote it):

```<code>post '/music' do
  search =  RSpotify::Artist.search(params[:search])
    @artist = search.first
    @image = @artist.images.first["url"]
    @top_tracks = @artist.top_tracks(:US)
    albums = @artist.albums
    @titles = []
    albums.each { |album| @titles << album.name }
    @titles.uniq!
    @related_artists = @artist.related_artists
    erb :'/music/show'
end
</code>```

答:
You seem to be using an outdated version (1.21.0, judging by your output). The current version is 1.22.1 (see https://rubygems.org/gems/rspotify) => maybe try updating.

Also, like Jeff said: Apparently there's an open GitHub issue that says that this issue occurs when you're not properly authenticated. So maybe check that your credentials are 1) set and 2) still valid. A simple way to check your credentials is to simply use them with the API directly (see http://www.compciv.org/recipes/data/touring-the-spotify-api/) => if they don't work there, it's probably not the code but your credentials that aren't working properly.

Body:
I was messing around with RSpotify which is a ruby wrapper for the Spotify API.

I added a form and sent the search result param to be looked up in the API but i'm getting the following error:

NoMethodError: undefined method `empty?' for nil:NilClass
from /Users/user/.rvm/gems/ruby-2.3.1/gems/rspotify-1.21.0/lib/rspotify/connection.rb:71:in `send_request'

I double checked and reinstalled the gem, added it to the gemfile and everything. I can't seem to figure out why it's not working.

Here's the code (It was working a few weeks ago when I wrote it):

post '/music' do
  search =  RSpotify::Artist.search(params[:search])
    @artist = search.first
    @image = @artist.images.first["url"]
    @top_tracks = @artist.top_tracks(:US)
    albums = @artist.albums
    @titles = []
    albums.each { |album| @titles << album.name }
    @titles.uniq!
    @related_artists = @artist.related_artists
    erb :'/music/show'
end


答:
From ?matrix

Non-atomic classed R objects are coerced by as.vector and all attributes discarded.

This means that the vector that is being passed to matrix is

```<code>as.vector(m)
[1] 1 4 7 2 5 8 3 6 9
</code>```

The reason byrow doesn't have an effect on your output is it determines how the data from the vector are read into the new matrix, not how the values from the old matrix are read out.

So, seeing as as.vector coerces the matrix by reading down columns before transversing rows, you probably want to do something like:

```<code>matrix(t(m), ncol= 1)
</code>```

Title: R trouble reshaping matrix to 1 column, byrow T or F same result

Body:
From ?matrix

Non-atomic classed R objects are coerced by as.vector and all attributes discarded.

This means that the vector that is being passed to matrix is

as.vector(m)
[1] 1 4 7 2 5 8 3 6 9

The reason byrow doesn't have an effect on your output is it determines how the data from the vector are read into the new matrix, not how the values from the old matrix are read out.

So, seeing as as.vector coerces the matrix by reading down columns before transversing rows, you probably want to do something like:

matrix(t(m), ncol= 1)


问:
D3 table with rowspan
I'm repetitively new to D3, but have hit a dead end trying to use D3 to convert this:

```<code>[
 { Year: 2014, Month: 'Dec', Team: 'T1', Sales: 123 },
 { Year: 2015, Month: 'Jan', Team: 'T1', Sales: 123 },
 { Year: 2015, Month: 'Jan', Team: 'T2"', Sales: 123 },
 { Year: 2015, Month: 'Feb', Team: 'T1', Sales: 123 },
 { Year: 2015, Month: 'Feb', Team: 'T2"', Sales: 123 },
 { Year: 2015, Month: 'Apr', Team: 'T1', Sales: 123 },
 { Year: 2015, Month: 'Apr', Team: 'T2"', Sales: 123 },
 { Year: 2015, Month: 'Mar', Team: 'T1', Sales: 123 },
 { Year: 2015, Month: 'Mar', Team: 'T2"', Sales: 123 }
]
</code>```

into this:

```<code><table border="1">
    <tr>
        <td>Year</td>
        <td>Month</td>
        <td>T1</td>
        <td>T2</td>
    </tr>
    <tr>
        <td rowspan="1">2015</td>
        <td>Dec</td>
        <td>123</td>
    </tr>
    <tr>
        <td rowspan="4">2015</td>
        <td>Jan</td>
        <td>123</td>
        <td>123</td>
    </tr>
    <tr>
        <td>Feb</td>
        <td>123</td>
        <td>123</td>
    </tr>
    <tr>
        <td>Apr</td>
        <td>123</td>
        <td>123</td>
    </tr>
    <tr>
        <td>Mar</td>
        <td>123</td>
        <td>123</td>
    </tr>
</table>
</code>```

Is it possible?  I have tried pre-processing the data with nest to restructure it but still have been unable to get my desired table output.

Any tips or pointers much appresiated

答:
I wanted to be able to do this exact thing but needed the ability to keep the d3 data bindings so I could access the data on click events.

By allowing d3 to bind the data via the selection.data(...) function the d3 keeps track of what dom elements belong to what datums. The code is essentially the same as @cyril and indeed does use a for each loop to create the elements; however, it is all done with d3 calls vs plain javascript loops that create a static display.

Another difference is that I group the parent collection of the whole year each into its own tbody element in the table.

Working example on JSBin.

```<code>var table = d3.select("body").append("table"),
  thead = table.append("thead");

thead.append("tr")
  .selectAll("th")
  .data(["Year", "Month", "T1", "Sales"])
  .enter()
  .append("th")
  .text(function(column) {
    return column;
  });

//this will group my data into key:year and all its yearly data
var nested_data = d3.nest()
  .key(function(d) {
    return d.Year;
  }).entries(data);

var rowgroups = table.selectAll('tbody')
  .data(nested_data)
  .enter()
  .append('tbody')
  .each(function(rowgroup) {
    var rowspan = rowgroup.values.length;
    // Add the actual table rows nested in a tbody for this group of year
    d3.select(this)
      .selectAll('tr')
      .data(function(d) {
        return d.values;
      })
      .enter().append('tr')
      .each(function(rowdata, index) {
        var row = d3.select(this);
        if (index == 0) {
          row.append('td').attr('rowspan', rowspan).text(rowdata.Year);
        }
        row.append('td').text(rowdata.Month);
        row.append('td').text(rowdata.Team);
        row.append('td').text(rowdata.Sales);

        // Add a click handler that will return the datum instead of undefined
        row.on('click', function(rowdata) {
          console.log('Row Clicked');
          console.log(rowdata);
        });
      });
  });
</code>```

I am new to d3 and would love feedback on this solution, it does work just not sure if this is the best way to do it.

Title: D3 table with rowspan

Body:
I'm repetitively new to D3, but have hit a dead end trying to use D3 to convert this:

[
 { Year: 2014, Month: 'Dec', Team: 'T1', Sales: 123 },
 { Year: 2015, Month: 'Jan', Team: 'T1', Sales: 123 },
 { Year: 2015, Month: 'Jan', Team: 'T2"', Sales: 123 },
 { Year: 2015, Month: 'Feb', Team: 'T1', Sales: 123 },
 { Year: 2015, Month: 'Feb', Team: 'T2"', Sales: 123 },
 { Year: 2015, Month: 'Apr', Team: 'T1', Sales: 123 },
 { Year: 2015, Month: 'Apr', Team: 'T2"', Sales: 123 },
 { Year: 2015, Month: 'Mar', Team: 'T1', Sales: 123 },
 { Year: 2015, Month: 'Mar', Team: 'T2"', Sales: 123 }
]

into this:

        Year
        Month
        T1
        T2

        2015
        Dec
        123

        2015
        Jan
        123
        123

        Feb
        123
        123

        Apr
        123
        123

        Mar
        123
        123

Is it possible?  I have tried pre-processing the data with nest to restructure it but still have been unable to get my desired table output.

Any tips or pointers much appresiated

Body:
I wanted to be able to do this exact thing but needed the ability to keep the d3 data bindings so I could access the data on click events.

By allowing d3 to bind the data via the selection.data(...) function the d3 keeps track of what dom elements belong to what datums. The code is essentially the same as @cyril and indeed does use a for each loop to create the elements; however, it is all done with d3 calls vs plain javascript loops that create a static display.

Another difference is that I group the parent collection of the whole year each into its own tbody element in the table.

Working example on JSBin.

var table = d3.select("body").append("table"),
  thead = table.append("thead");

thead.append("tr")
  .selectAll("th")
  .data(["Year", "Month", "T1", "Sales"])
  .enter()
  .append("th")
  .text(function(column) {
    return column;
  });

//this will group my data into key:year and all its yearly data
var nested_data = d3.nest()
  .key(function(d) {
    return d.Year;
  }).entries(data);

var rowgroups = table.selectAll('tbody')
  .data(nested_data)
  .enter()
  .append('tbody')
  .each(function(rowgroup) {
    var rowspan = rowgroup.values.length;
    // Add the actual table rows nested in a tbody for this group of year
    d3.select(this)
      .selectAll('tr')
      .data(function(d) {
        return d.values;
      })
      .enter().append('tr')
      .each(function(rowdata, index) {
        var row = d3.select(this);
        if (index == 0) {
          row.append('td').attr('rowspan', rowspan).text(rowdata.Year);
        }
        row.append('td').text(rowdata.Month);
        row.append('td').text(rowdata.Team);
        row.append('td').text(rowdata.Sales);

        // Add a click handler that will return the datum instead of undefined
        row.on('click', function(rowdata) {
          console.log('Row Clicked');
          console.log(rowdata);
        });
      });
  });

I am new to d3 and would love feedback on this solution, it does work just not sure if this is the best way to do it.


问:
How can I print a set of names in Javascript the first time the script runs followed by a prompt the second time?
This is the exercise:

Create a small program that contains a list of employee
names. Print out the list of names when the program runs
the first time. Prompt for an employee name and remove
that specific name from the list of names. Display the
remaining employees, each on its own line.

Example Output

There are 5 employees:

John Smith

Jackie Jackson

Chris Jones

Amanda Cullen

Jeremy Goodwin

Enter an employee name to remove: Chris Jones

There are 4 employees:

John Smith

Jackie Jackson

Amanda Cullen

Jeremy Goodwin

Constraint

• Use an array or list to store the names.

This is what I've tried so far (although it prompts for the name to be removed as soon as the script loads, rather than after the first 5 names have been printed).

var nameToRemove;
var employee = ["John Smith", "Jackie Jackson", "Chris Jones", "Amanda Cullen", "Jeremy Goodwin"];
var i;

document.write("There are " + employee.length + " employees:

");
for (i = 0; i < employee.length; i++) {
    document.write(employee[i] + "
");
}

nameToRemove = employee.indexOf(prompt("Enter an employee name to remove:"));

if (nameToRemove > -1) {
  employee.splice(nameToRemove, 1);
}

document.write("
There are " + employee.length + " employees:

");
for (i = 0; i < employee.length; i++) {
    document.write(employee[i] + "
");
}```

答:
Since you are using document.write to write the elements of the array to the document, it takes a little more time to reflect it to the user while the content has already been written to the DOM. I used the same code but instead of using document.write I used console.log and it worked as expected.

The only workaround I could find in your case is to use the setTimeout function.

Check out this fiddle to see it in action

Also, the dialogue boxes such as alert and prompt  stop the execution of the wholw javascript until an action is taken, this makes the reflection of the written content only possible after you click cancel or okay on the prompt box.


问:
Filter Pandas dataframe row and replace value in column
I got a big list of phone numbers in all sorts of formats:

```<code>df = pd.DataFrame(
    {'phone': ['0123/12345', '0123-23456', '0123/4455-10', '0123-4455-22'],
     'name': ['A-1', 'B-1', 'C/3', 'D/7']})

  name phone
0 A-1  0123/12345
1 B-1  0123-23456
2 C/3  0123/4455-10
3 D/7  0123-4455-22
</code>```

The formats I want are in rows #0 and #2.

When I concentrate on #1, I tried the following:

```<code>df.loc[(df.phone.str.count('-')==1) &
       (df.phone.str.count('/')==0)].apply(lambda x: x.str.replace('-', '/'))
</code>```

And this does the trick on the number, but unfortunately also on the name column:

```<code>  name phone
1 B/1  0123/23456
</code>```

But the name column must not be changed.

So I have two questions:

How can I filter the row and only change the phone column?

How can I go with #3, where I would want to replace the first occurrence of '-' to '/'?

答:
Or if you're no fan of regex (like me), you can simply do this:

```<code>df['phone'] = df.phone.apply(lambda x: x.replace('-','/',1) if '/' not in x else x)
print(df)

  name         phone
0  A-1    0123/12345
1  B-1    0123/23456
2  C/3  0123/4455-10
3  D/7  0123/4455-22
</code>```

Probably not the best or fastest way, still I feel more comfortable with it since I don't know regex yet.

Hope that was helpful.

Body:
I got a big list of phone numbers in all sorts of formats:

df = pd.DataFrame(
    {'phone': ['0123/12345', '0123-23456', '0123/4455-10', '0123-4455-22'],
     'name': ['A-1', 'B-1', 'C/3', 'D/7']})

  name phone
0 A-1  0123/12345
1 B-1  0123-23456
2 C/3  0123/4455-10
3 D/7  0123-4455-22

The formats I want are in rows #0 and #2.

When I concentrate on #1, I tried the following:

df.loc[(df.phone.str.count('-')==1) &
       (df.phone.str.count('/')==0)].apply(lambda x: x.str.replace('-', '/'))

And this does the trick on the number, but unfortunately also on the name column:

  name phone
1 B/1  0123/23456

But the name column must not be changed.

So I have two questions:

How can I filter the row and only change the phone column?

How can I go with #3, where I would want to replace the first occurrence of '-' to '/'?

Body:
Or if you're no fan of regex (like me), you can simply do this:

df['phone'] = df.phone.apply(lambda x: x.replace('-','/',1) if '/' not in x else x)
print(df)

  name         phone
0  A-1    0123/12345
1  B-1    0123/23456
2  C/3  0123/4455-10
3  D/7  0123/4455-22

Probably not the best or fastest way, still I feel more comfortable with it since I don't know regex yet.

Hope that was helpful.


问:
Detect Change in Active Worksheet - OfficeJS
I know that I can monitor the active selection by adding an event handler with workbook.onSelectionChanged and deriving the worksheet from the selection address, but this seems to slow down / diminish UX in Excel Online. Is there a way for me to specifically monitor when the active worksheet is changed, as opposed to every change in selection? I'm not able to find any clear documentation online for the available event handlers I can use with OfficeJS.

答:
There isn't currently a different way to monitor selection for specific types of selections. Today it's necessary to use workbook.onSelectionChanged for any selection-change detection. We're working on improvements here but I don't have a specific timeline to share.

-Michael (PM for add-ins)


问:
Dummy filters in Django
How do I make a dummy filter query in Django (a filter that is always matched) and an exclude query that is never matched.  The reason is because I have cases where my query is None, and in those cases I want to use a dummy filter.  This is the code:

```<code>MyModel.objects.filter(filterQuery).exclude(excludeQuery)
</code>```

In cases where filterQuery or excludeQuery is None I get an error, so I want to add the following conditional before that query:

```<code>if filterQuery == None: filterQuery = ???
if excludeQuery == None: excludeQuery = ???
MyModel.objects.filter(filterQuery).exclude(excludeQuery)
</code>```

答:
Another alternative to my answer above is to use Q() expressions, particularly if you need and/or logic:</p>

```<code>filterQuery = Q()

filterQuery = filterQuery | Q(agent='John')
filterQuery = filterQuery & Q(time__gte=timezone.now())

...

MyModel.objects.filter(filterQuery)
</code>```

Title: Dummy filters in Django

Body:
How do I make a dummy filter query in Django (a filter that is always matched) and an exclude query that is never matched.  The reason is because I have cases where my query is None, and in those cases I want to use a dummy filter.  This is the code:

MyModel.objects.filter(filterQuery).exclude(excludeQuery)

In cases where filterQuery or excludeQuery is None I get an error, so I want to add the following conditional before that query:

if filterQuery == None: filterQuery = ???
if excludeQuery == None: excludeQuery = ???
MyModel.objects.filter(filterQuery).exclude(excludeQuery)

Body:
Another alternative to my answer above is to use Q() expressions, particularly if you need and/or logic:

filterQuery = Q()

filterQuery = filterQuery | Q(agent='John')
filterQuery = filterQuery & Q(time__gte=timezone.now())

...

MyModel.objects.filter(filterQuery)


问:
Change highlighting of results in the FitNesse wiki
Currently the output looks like

Is there a way to make the comparison all or nothing without making some custom style or comparator or some other plugin?

答:
If you mean out of the box, the answer is no. There is no setting for the highlighting of the differences. There could be a plugin changing this, but I haven't found it yet.

So if you really want it changed, you will have to dive into the source.


问:
Cloudera CDH 5.7.2 / HBase: How to Set hfile.format.version?
With CDH 5.7.2-1.cdh5.7.2.po.18, I am trying to use Cloudera Manager to configure HBase to use visibility labels and authorizations, as described in the Cloudera Community post below:

Cloudera Manager Hbase Visibility Labels

Using Cloudera Manager, I have successfully updated the values of the following properties:

hbase.coprocessor.region.classes: Set to org.apache.hadoop.hbase.security.visibility.VisibilityController

hbase.coprocessor.master.classes: Set to org.apache.hadoop.hbase.security.visibility.VisibilityController

hbase.security.authorization: Set to true

Unfortunately, for whatever reason, Cloudera Manager doesn't expose the hfile.format.version variable, so I am unable to set it to 3.

When I restart HBase after updating only the three aforementioned variables, errors such as the following appear in the role log:

ERROR org.apache.hadoop.hbase.coprocessor.CoprocessorHost: The coprocessor org.apache.hadoop.hbase.security.visibility.VisibilityController threw java.lang.RuntimeException: A minimum HFile version of 3 is required to persist security labels. Consider setting hfile.format.version accordingly.

I'd love to set hfile.format.version accordingly, but... how would I do that, when it's not exposed in Cloudera Manager? For example, is there some config file on the file system that I can modify? Cloudera Manager has to be getting the current settings from somewhere.

Thanks!

答:
Cloudera Manager has a configuration section it calls the Safety Valve for exactly this purpose.  It will let you set arbitrary properties to whatever value you need.  See this doc for the following example:

Go to the HBase service.

Click the Configuration tab.

Select Scope > RegionServer.

Select Category > Advanced.

Locate the HBase Service Advanced Configuration Snippet (Safety Valve) for hbase-site.xml property, or search for it by typing its name in the Search box.

Add your custom XML (e.g.):

<property>
  <name>property-name</name>
  <value>property-value</value>
 </property>


问:
Capture string that only has n words
In my case, I need n=2.

Can this be done with a regular expression? Looking for how many words there are in a string of text and capturing only the strings with 2 words?

Example:

```<code>this is a test string
another one
and another one
</code>```

Output:

```<code>another one
</code>```

For what I need, looking for strings where there is only one space should work, it's capturing the ones with only 2 words (or one space) that i don't know how to do.

答:
The most literal way to go would be

```<code>^\S+ \S+$
</code>```

Using anchors and matching two groups of non-whitespaces separated by a space.

Title: Capture string that only has n words

Body:
In my case, I need n=2.

Can this be done with a regular expression? Looking for how many words there are in a string of text and capturing only the strings with 2 words?

Example:

this is a test string
another one
and another one

Output:

another one

For what I need, looking for strings where there is only one space should work, it's capturing the ones with only 2 words (or one space) that i don't know how to do.

Body:
The most literal way to go would be

^\S+ \S+$

Using anchors and matching two groups of non-whitespaces separated by a space.


问:
Are parameters Thread Safe?
I have read a number of posts on this subject, but I'm still just a little fuzzy how C# handles parameters in methods when called from multiple threads.

I have a series of utility methods that need to be called from about 60+ threads.  It's a process that downloads patient data for roughly 20,000-30,000 patients every day.  For the most part, the methods look like this.

```<code>
    Public Static SomeClass
    {
        public static string StringToSQLBool(string s)
        {
           if (s.Trim() == "")
           {
              return "Null";
           }
           else
           {
              if (s.ToLower() == "true")
              {
                 return "1";
              }
              {
                 return "0";
              }
           }
        }

        public static string DateToSQLAnsiStr(string ADate)
        {
            try
            {
               if (ADate.Trim() != "")
               {
                  DateTime d = Convert.ToDateTime(ADate);
                  return "{d '" + d.Year.ToString() + "-" +
                          d.Month.ToString().PadLeft(2, '0') + "-" +
                          d.Day.ToString().PadLeft(2, '0') + "'}";
               }
               else
               {
                  return "Null";
               }
            }
            catch
            {
               return "Null";
            }
        }
    }
</code>
```

As I understand it, as long as the parameters are used in the method that are singular to the calling thread, then it would be considered safe.

Are these thread-safe without locking?

答:
TL;DR - According to how the question was asked, yes. Parameters are thread safe in the sense that two threads can call the same method at the same time passing different parameters.

Each call to a method from a different thread has its own stack. Value types passed to the method are stored on the stack. Pointers to reference types passed to the method are stored on the stack. Either way it's on the stack.

Because each thread has its own stack, multiple calls to a method from different threads don't "overwrite" each others' parameters.

As I understand it, as long as the parameters are used in the method that are singular to the calling thread, then it would be considered safe.

There's a tendency to pick statements like this apart like a lawyer (especially since it involves what sounds like medical records.) Your understanding is correct.

I'm not saying that it's wrong to pick questions apart like a lawyer. Details matter. But you asked your question very clearly so I get what you mean.

How do I say this without sounding somehow patronizing, because you're likely a very experienced programmer and this just happens to be your first time working with multithreading specifically using .NET. Please be careful. I'm horrified at the thought of medical records going to the wrong person, claims being denied, or someone accidentally getting chemotherapy or gender reassignment because of a threading error. I think in this case the community should be highly motivated to assist with all of your multithreading questions.

Title: Are parameters Thread Safe?

Body:
I have read a number of posts on this subject, but I'm still just a little fuzzy how C# handles parameters in methods when called from multiple threads.

I have a series of utility methods that need to be called from about 60+ threads.  It's a process that downloads patient data for roughly 20,000-30,000 patients every day.  For the most part, the methods look like this.

    Public Static SomeClass
    {
        public static string StringToSQLBool(string s)
        {
           if (s.Trim() == "")
           {
              return "Null";
           }
           else
           {
              if (s.ToLower() == "true")
              {
                 return "1";
              }
              {
                 return "0";
              }
           }
        }

        public static string DateToSQLAnsiStr(string ADate)
        {
            try
            {
               if (ADate.Trim() != "")
               {
                  DateTime d = Convert.ToDateTime(ADate);
                  return "{d '" + d.Year.ToString() + "-" +
                          d.Month.ToString().PadLeft(2, '0') + "-" +
                          d.Day.ToString().PadLeft(2, '0') + "'}";
               }
               else
               {
                  return "Null";
               }
            }
            catch
            {
               return "Null";
            }
        }
    }

As I understand it, as long as the parameters are used in the method that are singular to the calling thread, then it would be considered safe.

Are these thread-safe without locking?

ContentLicense: CC BY-SA 4.0


问:
Ruby Code to verify AAD token in correct
I have a scenario of calling Rubi API which is AAD authenticated

I have the code to generate AAD token from Client ID and Secret.

But need to code to verify the token is correct or not when it reaches the Ruby API.

答:
AAD token is usually JWT, so you can use any JWT library, like: https://github.com/jwt/ruby-jwt

There is also an omniauth - AAD provider: https://github.com/AzureAD/omniauth-azure-activedirectory


问:
How to achieve better clustering for indoor map on mapbox?
I am using some default mapbox clustering, which is not enough for indoor map of building. Here is my example

```<code>                map.addSource('maintenance_events_on_map', {
                    type: 'geojson',
                    cluster: true,
                    clusterMaxZoom: 22, // Max zoom to cluster points on
                    clusterRadius: 1, // Radius
                    data: JSON.parse(maintenance_events_on_map)

                }).addLayer({
                    id: 'clusters',
                    type: 'circle',
                    source: 'maintenance_events_on_map',
                    paint: {
                        'circle-radius': 20,
                        'circle-color': '#973901'
                    }
                  }).addLayer({
                    id: 'cluster-label',
                    type:'symbol',
                    source:'maintenance_events_on_map',
                    layout:{
                        'text-field': "{point_count}"
                    }
                  });
</code>```

The output is following:

I need it to be on the level of indoor building:

答: The only way achieving this is using Mapbox Studio, where you can upload custom icons, which easily can be called in the layer properties, while creating a layer. These icons are clusterable and this works much more better.</p>

Body:
I am using some default mapbox clustering, which is not enough for indoor map of building. Here is my example

                map.addSource('maintenance_events_on_map', {
                    type: 'geojson',
                    cluster: true,
                    clusterMaxZoom: 22, // Max zoom to cluster points on
                    clusterRadius: 1, // Radius
                    data: JSON.parse(maintenance_events_on_map)

                }).addLayer({
                    id: 'clusters',
                    type: 'circle',
                    source: 'maintenance_events_on_map',
                    paint: {
                        'circle-radius': 20,
                        'circle-color': '#973901'
                    }
                  }).addLayer({
                    id: 'cluster-label',
                    type:'symbol',
                    source:'maintenance_events_on_map',
                    layout:{
                        'text-field': "{point_count}"
                    }
                  });

The output is following:

I need it to be on the level of indoor building:


问:
Trouble locating my serial ports using bash on Windows 10
I want to be able to read from serial ports on my computer and write to a file.  Inside /dev (using Bash shell on Windows 10) I can't seem to locate my USB serial ports (I have tty, tty0, tty1, and that's it for tty).

Is it located somewhere else, or even accessible through the bash shell? I just want to be able to know how to access it at this point.

In device manager, COM4 shows up under ports when I plug in my USB. I also ran the command wmic path Win32_SerialPort in the Windows command prompt and it said "No Instance(s) Available." So I'm very confused as to how I can view my Serial Ports and why they aren't showing up in certain instances.

Any clarification on how serial ports work, especially with USB, would be greatly appreciated, as I am pretty new with this stuff.

答:
Soon, Windows will officially support serial on the Windows Subsystem for Linux (WSL). The COM_n_ ports will be available at /dev/ttyS_n_

Mapping:

```<code>COM1 >> /dev/ttyS0
COM2 >> /dev/ttyS1
...
COM192 >> /dev/ttyS191
</code>```

A good functional description can be found here:

https://blogs.msdn.microsoft.com/wsl/2017/04/14/serial-support-on-the-windows-subsystem-for-linux/

NOTE: At time of writing this feature is only available on the insider builds.

Body:
Soon, Windows will officially support serial on the Windows Subsystem for Linux (WSL). The COM_n_ ports will be available at /dev/ttyS_n_

Mapping:

COM1 >> /dev/ttyS0
COM2 >> /dev/ttyS1
...
COM192 >> /dev/ttyS191

A good functional description can be found here:

https://blogs.msdn.microsoft.com/wsl/2017/04/14/serial-support-on-the-windows-subsystem-for-linux/

NOTE: At time of writing this feature is only available on the insider builds.


问:
SQL: Add a new column based on CASE expression and looking up values from another table
I am trying to add a new column called Multiplier to an existing table called Trades. The row values of this column will depend on another column on the Trades table called Type. If the Type is anything other than "Equity", "Corp" or "Option, then the value needs to be looked up from another table called ContractSize. Lastly, I want the data type of the Multiplier column to be decimal (7,3). The code I had was:

```<code>ALTER TABLE Portfolio.Trades
ADD Multiplier decimal(7,3) AS
(
CASE
 WHEN Type = 'Equity' Then 1
 WHEN Type = 'Corp' Then 0.1
 WHEN Type = 'Option' Then 100
ELSE
 (SELECT ContractSize FROM Portfolio.ContractSize CS
 JOIN Portfolio.Trades T
 ON T.Identifier = CS.ContractSize)
)
</code>```

I am getting two errors on this code:

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'AS'.

Msg 102, Level 15, State 1, Line 12
Incorrect syntax near ')'.

Some guidance is much appreciated.

答:
Why add column to the table? You can create a view alternatively.</p>

```<code>CREATE VIEW myView AS
    SELECT *, -- your real column list here
        CAST(CASE
         WHEN Type = 'Equity' Then 1
         WHEN Type = 'Corp' Then 0.1
         WHEN Type = 'Option' Then 100
         ELSE
           (SELECT ContractSize
            FROM Portfolio.ContractSize CS
            WHERE T.Identifier = CS.ContractSize)
         END AS decimal(7,3)) AS  Multiplier
    FROM
    Portfolio.Trades T;
</code>```

Body:
I am trying to add a new column called Multiplier to an existing table called Trades. The row values of this column will depend on another column on the Trades table called Type. If the Type is anything other than "Equity", "Corp" or "Option, then the value needs to be looked up from another table called ContractSize. Lastly, I want the data type of the Multiplier column to be decimal (7,3). The code I had was:

ALTER TABLE Portfolio.Trades
ADD Multiplier decimal(7,3) AS
(
CASE
 WHEN Type = 'Equity' Then 1
 WHEN Type = 'Corp' Then 0.1
 WHEN Type = 'Option' Then 100
ELSE
 (SELECT ContractSize FROM Portfolio.ContractSize CS
 JOIN Portfolio.Trades T
 ON T.Identifier = CS.ContractSize)
)

I am getting two errors on this code:

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'AS'.

Msg 102, Level 15, State 1, Line 12
Incorrect syntax near ')'.

Some guidance is much appreciated.

Body:
Why add column to the table? You can create a view alternatively.

CREATE VIEW myView AS
    SELECT *, -- your real column list here
        CAST(CASE
         WHEN Type = 'Equity' Then 1
         WHEN Type = 'Corp' Then 0.1
         WHEN Type = 'Option' Then 100
         ELSE
           (SELECT ContractSize
            FROM Portfolio.ContractSize CS
            WHERE T.Identifier = CS.ContractSize)
         END AS decimal(7,3)) AS  Multiplier
    FROM
    Portfolio.Trades T;


答:
I will expand my comment. This is the right way:

```<code><div class="container-fluid">
  <div class="row">
    <div class="col-md-12">

      <form method="POST">
        {{csrf_field()}}

      <div class="form-group text-center">
        <button type="submit" class="btn btn-primary submit">
          Submit
        </button>
      </div>
      </form>
    </div>
  </div>
</div>
</code>```

Here you have a working fiddle https://jsfiddle.net/en15xrh6/1/

A row should be always followed by some col-* class. Touching the css of row or col classes, for margin or padding almost always ends up breaking bootstrap. To do that you have to go to bootstrap source and modify the right variable.

Finally, bootstrap has utility classes: text-right, text-center, text-left

Title: How to make Responsive button with Bootstrap

Body:
I'm Trying to have submit button center the page.
my code in html is:

<form method="POST"
      action="https://api.instagram.com/oauth/authorize/redirect_uri=http://hanie-asemi.ir/laravel/public/instagram/test&response_type=code">
    {{csrf_field()}}

    <button type="submit" class="btn btn-primary submit">Submit</button>
</form>

I give the submit button center in desktop but this button Not at the center in mobile!what can I do to centered button in mobile?

Body:
I will expand my comment. This is the right way:

<div class="container-fluid">
  <div class="row">
    <div class="col-md-12">

      <form method="POST">
        {{csrf_field()}}

      <div class="form-group text-center">
        <button type="submit" class="btn btn-primary submit">
          Submit
        </button>
      </div>
      </form>
    </div>
  </div>
</div>

Here you have a working fiddle https://jsfiddle.net/en15xrh6/1/

A row should be always followed by some col-* class. Touching the css of row or col classes, for margin or padding almost always ends up breaking bootstrap. To do that you have to go to bootstrap source and modify the right variable.

Finally, bootstrap has utility classes: text-right, text-center, text-left


问:
Laravel session based auth:api middleware not working
I tried using the Auth Scaffolding of Laravel 5.3 including the api routes. I wanted to use the session driver for the api guard, but apparently this has no impact whatsoever. After I log into the application with a valid user (so I get from /login to /home) I tried entering the path /api/user, but it always redirects me to /home. The RedirectIfAuthenticated middleware redirects the user.

Here is what I tried and a quick overview of the test application:

```<code>// In "app\Http\Middleware\RedirectIfAuthenticated.php"
if (Auth::guard($guard)->check()) {
    return redirect('/home');
}
</code>```

$guard is null, and the if is true when browsing to /api/user.

```<code>// In "config\auth.php"
'api' => [
    'driver' => 'session', // changed from token to session
    'provider' => 'users',
],
</code>```

I changed the driver of the api guard to session.

```<code>// In "app\Http\Kernel.php"
'api' => [
    'throttle:60,1',
    'bindings',
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Session\Middleware\StartSession::class,
],
</code>```

I added the middlewares to support cookies in the api middleware

```<code>// In "routes\api.php"
Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');
</code>```

This is an example that comes with a new Laravel installation.

```<code>// In "app\Providers\RouteServiceProvider.php"
Route::group([
    'middleware' => 'api',
    'namespace' => $this->namespace,
    'prefix' => 'api',
], function ($router) {
    require base_path('routes/api.php');
});
</code>```

The api middleware is applied to all the routes defined in the api.php file.

I want to be able to query my API after a user has logged in without using tokens, etc. The app I wrote with Laravel 5.2 had basically the same route but only the web middleware group and auth middleware applied to it. In Laravel 5.3, adding the auth middleware leads to the described problem.

edit: With my configuration I tried the following:

```<code>// In "routes\web.php"
Route::get('/test', function (Request $request) {
    return "test";
})->middleware(['auth']);
</code>```

This works perfectly fine, but this doesn't, although the web and the api guard are exactly the same inside the auth.php.

```<code>Route::get('/test', function (Request $request) {
    return "test";
})->middleware(['auth:api']);
</code>```

答:
I had the same issue of getting redirected to the /home while accessing my API routes even if I was already logged in.
Try changing the order of your api middlewares in App\Http\Kernel.php and place bindings in last position so your custom middlewares are executed first.

Body:
I tried using the Auth Scaffolding of Laravel 5.3 including the api routes. I wanted to use the session driver for the api guard, but apparently this has no impact whatsoever. After I log into the application with a valid user (so I get from /login to /home) I tried entering the path /api/user, but it always redirects me to /home. The RedirectIfAuthenticated middleware redirects the user.

Here is what I tried and a quick overview of the test application:

// In "app\Http\Middleware\RedirectIfAuthenticated.php"
if (Auth::guard($guard)->check()) {
    return redirect('/home');
}

$guard is null, and the if is true when browsing to /api/user.

// In "config\auth.php"
'api' => [
    'driver' => 'session', // changed from token to session
    'provider' => 'users',
],

I changed the driver of the api guard to session.

// In "app\Http\Kernel.php"
'api' => [
    'throttle:60,1',
    'bindings',
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Session\Middleware\StartSession::class,
],

I added the middlewares to support cookies in the api middleware

// In "routes\api.php"
Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');

This is an example that comes with a new Laravel installation.

// In "app\Providers\RouteServiceProvider.php"
Route::group([
    'middleware' => 'api',
    'namespace' => $this->namespace,
    'prefix' => 'api',
], function ($router) {
    require base_path('routes/api.php');
});

The api middleware is applied to all the routes defined in the api.php file.

I want to be able to query my API after a user has logged in without using tokens, etc. The app I wrote with Laravel 5.2 had basically the same route but only the web middleware group and auth middleware applied to it. In Laravel 5.3, adding the auth middleware leads to the described problem.

edit: With my configuration I tried the following:

// In "routes\web.php"
Route::get('/test', function (Request $request) {
    return "test";
})->middleware(['auth']);

This works perfectly fine, but this doesn't, although the web and the api guard are exactly the same inside the auth.php.

Route::get('/test', function (Request $request) {
    return "test";
})->middleware(['auth:api']);


问:
How to export result of select statement in prestodb.io
Two things.

How can I execute an sql statement without "presto-cli-0.56-executable.jar", for example I want to provide a web interface where people could write query and see the output on web

How to export the result of the select statement into a file?

答:
For completeness, you can run the presto cli client like so

```<code>presto --server {server_name}:{server_port} --catalog {catalog_name} --schema {schema_name} --user {user_name} --execute "SELECT * FROM table_name LIMIT 1" --output-format CSV > output_fname.csv
</code>```

And if you want the header to be included, use the following as hinted by answers above

```<code>--output-format CSV_HEADER
</code>```

Hope this helps.

Body:
For completeness, you can run the presto cli client like so

presto --server {server_name}:{server_port} --catalog {catalog_name} --schema {schema_name} --user {user_name} --execute "SELECT * FROM table_name LIMIT 1" --output-format CSV > output_fname.csv

And if you want the header to be included, use the following as hinted by answers above

--output-format CSV_HEADER

Hope this helps.


问:
Convert fixed and byte* from c# to vb.net
I have the following code in c# and would like to convert it in VB.NET. I'm not sure what fixed and byte* are and how they can be converted. The telerik converter does not provide any help on this.

```<code>fixed (byte* ptrShapeBufferPtr = pointerInfo.PtrShapeBuffer)
{
    mDeskDupl.GetFramePointerShape(
           frameInfo.PointerShapeBufferSize,
           (IntPtr)ptrShapeBufferPtr,
           out pointerInfo.BufferSize,
           out pointerInfo.ShapeInfo);
}
</code>```

Any ideas?

答:
Since VB.NET doesn't support pointers you have to use an IntPtr instead. The most simple way to do so is to mark the object as not getting Garbage Collected using a GCHandle. Then you use the AddrOfPinnedObject method to get its pointer as an IntPtr.

Dim handle As GCHandle

Try
    handle = GCHandle.Alloc(pointerInfo.PtrShapeBuffer, GCHandleType.Pinned)
    Dim ptrShapeBufferPtr As IntPtr = handle.AddrOfPinnedObject()

    mDeskDupl.GetFramePointerShape(frameInfo.PointerShapeBufferSize, ptrShapeBufferPtr, pointerInfo.BufferSize, pointerInfo.ShapeInfo)
Finally
    If handle.IsAllocated = True Then handle.Free()
End Try
```

Note that this is a more of a quick and dirty solution. GCHandle isn't expected to be used like this, but it works and is (AFAIK) still okay to use. There are other (longer) ways of doing this which were more specifically designed for these kinds of things.

Body:
I have the following code in c# and would like to convert it in VB.NET. I'm not sure what fixed and byte* are and how they can be converted. The telerik converter does not provide any help on this.

fixed (byte* ptrShapeBufferPtr = pointerInfo.PtrShapeBuffer)
{
    mDeskDupl.GetFramePointerShape(
           frameInfo.PointerShapeBufferSize,
           (IntPtr)ptrShapeBufferPtr,
           out pointerInfo.BufferSize,
           out pointerInfo.ShapeInfo);
}

Any ideas?

Body:
Since VB.NET doesn't support pointers you have to use an IntPtr instead. The most simple way to do so is to mark the object as not getting Garbage Collected using a GCHandle. Then you use the AddrOfPinnedObject method to get its pointer as an IntPtr.

Dim handle As GCHandle

Try
    handle = GCHandle.Alloc(pointerInfo.PtrShapeBuffer, GCHandleType.Pinned)
    Dim ptrShapeBufferPtr As IntPtr = handle.AddrOfPinnedObject()

    mDeskDupl.GetFramePointerShape(frameInfo.PointerShapeBufferSize, ptrShapeBufferPtr, pointerInfo.BufferSize, pointerInfo.ShapeInfo)
Finally
    If handle.IsAllocated = True Then handle.Free()
End Try

Note that this is a more of a quick and dirty solution. GCHandle isn't expected to be used like this, but it works and is (AFAIK) still okay to use. There are other (longer) ways of doing this which were more specifically designed for these kinds of things.


问:
Woocommerce List All Previously Ordered Products
I'm trying to set up a page that a user can go on and they can see all the products they have bought in the standard Woocommerce format so they can add a number of them to the cart.

I've tried this but only 1 is showing up at each time annoyingly:

```<code><ul class="products">
[insert_php]
        $user_id        = get_current_user_id();
        $current_user   = wp_get_current_user();
        $customer_email = $current_user->email;
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => 12
        );
        $loop = new WP_Query( $args );
        if ( $loop->have_posts() ) {
            while ( $loop->have_posts() ) :
                $loop->the_post();
                $_product = get_product( $loop->post->ID );
                if (wc_customer_bought_product($customer_email, $user_id,$_product->id)){
                     woocommerce_get_template_part( 'content', 'product' );
                }
            endwhile;
        } else {
            echo __( 'No products found' );
        }
        wp_reset_postdata();
[/insert_php]
</ul><!--/.products-->
</code>```

答:
Your code is working (WP 4.8, WooCommerce 3.1.0, Insert PHP 1.3).

I wanna clear one moment:

If you client buy one product more than time, anyway you got one product in list.

Big chance that problem is with testing data. Can you check again, please.

Body:
I'm trying to set up a page that a user can go on and they can see all the products they have bought in the standard Woocommerce format so they can add a number of them to the cart.

I've tried this but only 1 is showing up at each time annoyingly:

[insert_php]
        $user_id        = get_current_user_id();
        $current_user   = wp_get_current_user();
        $customer_email = $current_user->email;
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => 12
        );
        $loop = new WP_Query( $args );
        if ( $loop->have_posts() ) {
            while ( $loop->have_posts() ) :
                $loop->the_post();
                $_product = get_product( $loop->post->ID );
                if (wc_customer_bought_product($customer_email, $user_id,$_product->id)){
                     woocommerce_get_template_part( 'content', 'product' );
                }
            endwhile;
        } else {
            echo __( 'No products found' );
        }
        wp_reset_postdata();
[/insert_php]


问:
Dynamically import classes
Now i have script like this:

```<code>class threadEnum():
    pass

class first(threadEnum):
    pass

class second(threadEnum):
    pass

class third(threadEnum):
    pass

enums = [enum(domain, [], q=subdomains_queue, silent=silent, verbose=verbose) for enum in chosenEnums]
    for enum in enums:
        enum.start()
    for enum in enums:
        enum.join()
</code>```

which classes is very long and takes a lot of lines. I need to move each class to separate file and then import all classes into main script. So i create folder engines and put inside three files with classes first.py, second.py and third.py also file __init__.py

I think must be something like that:

```<code>import importlib

class threadEnum():
    pass

chosenEnums = []
chosenEnums = ['first', 'second', 'third']

# Load classes from engines folder
for enumm in chosenEnums:
    module = 'engines'
    # create a global object containging our module
    mymethod = getattr(importlib.import_module('engines'), enumm)

enums = [enum(domain, [], q=subdomains_queue, silent=silent, verbose=verbose) for enum in chosenEnums]
    for enum in enums:
        enum.start()
    for enum in enums:
        enum.join()
</code>```

But i get error:

AttributeError: 'module' object has no attribute 'first'

What is wrong? Python 2.7.6

答: by using a simple if statement and haveing a set variable name to be the object and use the dir() to detect the objects within the named object (class).

Title: Dynamically import classes

Body:
Now i have script like this:

class threadEnum():
    pass

class first(threadEnum):
    pass

class second(threadEnum):
    pass

class third(threadEnum):
    pass

enums = [enum(domain, [], q=subdomains_queue, silent=silent, verbose=verbose) for enum in chosenEnums]
    for enum in enums:
        enum.start()
    for enum in enums:
        enum.join()

which classes is very long and takes a lot of lines. I need to move each class to separate file and then import all classes into main script. So i create folder engines and put inside three files with classes first.py, second.py and third.py also file __init__.py

I think must be something like that:

import importlib

class threadEnum():
    pass

chosenEnums = []
chosenEnums = ['first', 'second', 'third']

# Load classes from engines folder
for enumm in chosenEnums:
    module = 'engines'
    # create a global object containging our module
    mymethod = getattr(importlib.import_module('engines'), enumm)

enums = [enum(domain, [], q=subdomains_queue, silent=silent, verbose=verbose) for enum in chosenEnums]
    for enum in enums:
        enum.start()
    for enum in enums:
        enum.join()

But i get error:

AttributeError: 'module' object has no attribute 'first'

What is wrong? Python 2.7.6


问:
Name of a symmetric matrix with zeroes in the diagonal
I am looking for a term that can be used for a matrix with the diagonal line equal to zeros and the upper and lower triangles are symmetric.

for example if I have a matrix of size 5 by 5 the matrix will be as following:

```<code>0 1 2 3 4
1 0 5 6 7
2 5 0 8 9
3 6 8 0 10
4 7 9 10 0
</code>```

Is there a term for this matrix?

答:
There is also an entry for Hollow Matrix
https://en.wikipedia.org/wiki/Hollow_matrix</p>

Body:
I am looking for a term that can be used for a matrix with the diagonal line equal to zeros and the upper and lower triangles are symmetric.

for example if I have a matrix of size 5 by 5 the matrix will be as following:

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

Is there a term for this matrix?


问:
Aurelia-Kendo multiselect - how get selected values in viewmodel?
I has the following code in html-file:

```<code><ak-multiselect k-data-text-field="name"
  k-data-value-field="id"
  k-data-source.bind="corporateGroupDataSource"
  k-on-change.delegate="SetGroupFilter($event, 'GroupId')"
  data-placeholder="Select corporate group...">
</ak-multiselect>
</code>```

By button press I will create filter from all existing multiselects on the html-page and will send request to database.
But how I can get selected values of multiselect in my viewmodel? I mean js-file...

I can't use id of multiselect.

答: Use k-value.two-way="yourVMVariableName" to bind to the value. More information can be found here: http://aurelia-ui-toolkits.github.io/demo-kendo/#/samples/multiselect-basic-use

Body:
I has the following code in html-file:

<ak-multiselect k-data-text-field="name"
  k-data-value-field="id"
  k-data-source.bind="corporateGroupDataSource"
  k-on-change.delegate="SetGroupFilter($event, 'GroupId')"
  data-placeholder="Select corporate group...">
</ak-multiselect>

By button press I will create filter from all existing multiselects on the html-page and will send request to database.
But how I can get selected values of multiselect in my viewmodel? I mean js-file...

I can't use id of multiselect.


问:
Encode Decode using python
I have this function in python

```<code>Str = "Ã¼";
print Str

def correctText( str ):
  str = str.upper()
  correctedText = str.decode('UTF8').encode('Windows-1252')
  return correctedText;

corText = correctText(Str);
print corText
</code>```

It works and converts characters like Ã¼ and Ã© however it fails when i try Ã? and Â¶

Is there a way i can fix it?

答:
What you are trying to do is to compose valid UTF-8 codes by several consecutive Windows-1252 codes.

For example, for Ã¼, the Windows-1252 code of Ã is C3 and for ¼ it's BC. Together the code C3BC happens to be the UTF-8 code of ü.

Now, for Ã?, the Windows-1252 code is C33F, which is not a valid UTF-8 code (because the second byte does not start with 10).

Are you sure this sequence occurs in your text? For example, for à, the Windows-1252 decoding of the UTF-8 code (C3A0) is Ã followed by a non-printable character (non-breaking space). So, if this second character is not printed, the ? might be a regular character of the text.

For Â¶ the Windows-1252 encoding is C2B6. Shouldn't it be Ã¶, for which the Windows-1252 encoding is C3B6, which equals the UTF-8 code of ö?

Title: Encode Decode using python

Body:
I have this function in python

Str = "Ã¼";
print Str

def correctText( str ):
  str = str.upper()
  correctedText = str.decode('UTF8').encode('Windows-1252')
  return correctedText;

corText = correctText(Str);
print corText

It works and converts characters like Ã¼ and Ã© however it fails when i try Ã? and Â¶

Is there a way i can fix it?


问:
Azure CLI in Git Bash
I am trying to use a bash (sh) script on windows to run a test deployment. I am running the script from the gitbash console so that I have a copy of bash, but doing so means that the azure clie is not available (i.e. azure command is not found). Does anyone know how I can get the Azure cli working in GitBash (I am assuming I just install it somewhere else) or should I change to a different way of using bash  </p>

答:
In other words Azure CLI for Windows is not compatible with Git Bash for Windows

https://github.com/Azure/azure-cli/issues/3445

Title: Azure CLI in Git Bash


问:
Jasmine real AJAX request test
I need to make a test with a real ajax request with jasmine,

So far I have this:

```<code>function login(){
    $.ajax({
        method: 'GET',
        url: url,
        dataType: "json",
        contentType: "application/json; charset=utf-8"
    });
}
</code>```

I need to get the login success response, but for that, jasmine needs to wait for the request to end before iteration trough the 'its'.
How can I do that?

答:
Shouldn't it be more like

```<code>function(done){
 $.ajax({
    method: 'GET',
    url: url,
    dataType: "json",
    contentType: "application/json; charset=utf-8"
 })
 .then(done);
}
</code>```

or replace done with a method that actually checks

```<code>.then(function(response){
   //do your asserts here
   done();
});
</code>```

Title: Jasmine real AJAX request test

Body:
I need to make a test with a real ajax request with jasmine,

So far I have this:

function login(){
    $.ajax({
        method: 'GET',
        url: url,
        dataType: "json",
        contentType: "application/json; charset=utf-8"
    });
}

I need to get the login success response, but for that, jasmine needs to wait for the request to end before iteration trough the 'its'.
How can I do that?

Body:
Shouldn't it be more like

function(done){
 $.ajax({
    method: 'GET',
    url: url,
    dataType: "json",
    contentType: "application/json; charset=utf-8"
 })
 .then(done);
}

or replace done with a method that actually checks

.then(function(response){
   //do your asserts here
   done();
});


问:
Regular Expressions and JavaScript: Find digits in last part of string
I need to extract the ID number from a string. The results are given to me in the following format:
"Something with some kind of title (ID: 300)"
"1, 3, 4 - Something that starts with numbers (ID: 400)"
etc..

These values are passed into javascript, which then needs to extract the ID number only, i.e. 300, or 400 in the above example.

I am still struggling with regex, so any help is greatly appreciated. I can easily do this with string operations, but would really like to get my feet wet with RegEx on some actual examples I can use. The online tutorials I've read so far have proven fruitless.

Thank you

答:
If your number is always in the form (ID: ###) then \(ID: ([0-9]+)\) should do as your regex. The brackets around ID and the number are escaped, otherwise they would be considered a matching group (as the brackets around [0-9]+ are. The [0-9] means check for any character than is between 0 and 9 and the + means 'one or more of'.

```<code>var regex = new RegExp(/\(ID: ([0-9]+)\)/);
var test = "Some kind of title (ID: 3456)";

var match = regex.exec(test);
alert('Found: ' + match[1]);
</code>```

Example: http://jsfiddle.net/jonathon/FUmhR/

http://www.regular-expressions.info/javascript.html is a useful resource

ContentLicense: CC BY-SA 2.5

Body:
If your number is always in the form (ID: ###) then \(ID: ([0-9]+)\) should do as your regex. The brackets around ID and the number are escaped, otherwise they would be considered a matching group (as the brackets around [0-9]+ are. The [0-9] means check for any character than is between 0 and 9 and the + means 'one or more of'.

var regex = new RegExp(/\(ID: ([0-9]+)\)/);
var test = "Some kind of title (ID: 3456)";

var match = regex.exec(test);
alert('Found: ' + match[1]);

Example: http://jsfiddle.net/jonathon/FUmhR/

http://www.regular-expressions.info/javascript.html is a useful resource


问:
SonarLint plugin IntelliJ with no authentication
Is it possible to connect to a remote SonarQube 5.6.1 server using the SonarLint 3.0.0 plugin for IntelliJ 2017.1 without using authentication by default? Currently the plugin seems to want either username/password OR token

答:
There is a hack which you can use:

Normally sonarLint stores the information in your IntelliJConfiguration-directory in config/options/sonarlint.xml - you can simply paste following configuration into that file:

```<code><application>
  <component name="SonarLintGlobalSettings">
    <option name="sonarQubeServers">
      <list>
        <SonarQubeServer>
          <option name="hostUrl" value="<your-server-url>" />
          <option name="name" value="test" />
          <option name="login" value="" />
          <password />
          <organizationKey />
        </SonarQubeServer>
      </list>
    </option>
  </component>
</application>
</code>```

which is the basic configuration for a server without authentication.

// EDIT: It seems like this was an intended change by sonarSource to sonarLint - https://groups.google.com/forum/#!topic/sonarlint/xnpQmXN8NEo - is the mailing list discussion about this

Body:
There is a hack which you can use:

Normally sonarLint stores the information in your IntelliJConfiguration-directory in config/options/sonarlint.xml - you can simply paste following configuration into that file:

<application>
  <component name="SonarLintGlobalSettings">
    <option name="sonarQubeServers">
      <list>
        <SonarQubeServer>
          <option name="hostUrl" value="<your-server-url>" />
          <option name="name" value="test" />
          <option name="login" value="" />
          <password />
          <organizationKey />
        </SonarQubeServer>
      </list>
    </option>
  </component>
</application>

which is the basic configuration for a server without authentication.

// EDIT: It seems like this was an intended change by sonarSource to sonarLint - https://groups.google.com/forum/#!topic/sonarlint/xnpQmXN8NEo - is the mailing list discussion about this


问:
UIGestureRecognizer on UIImageView
I have a UIImageView, which I want to be able to resize and rotate etc.

Can a UIGestureRecognizer be added to the UIImageView?

I would want to add a rotate and pinch recognizer to a UIImageView which would be created at runtime.

How does one add these recognizers?

答:
I just done this with swift4 by adding 3 gestures together in single view

UIPinchGestureRecognizer : Zoom in and zoom out view.

UIRotationGestureRecognizer : Rotate the view.

UIPanGestureRecognizer : Dragging the view.

Here my sample code

```<code>class ViewController: UIViewController: UIGestureRecognizerDelegate{
      //your image view that outlet from storyboard or xibs file.
     @IBOutlet weak var imgView: UIImageView!
     // declare gesture recognizer
     var panRecognizer: UIPanGestureRecognizer?
     var pinchRecognizer: UIPinchGestureRecognizer?
     var rotateRecognizer: UIRotationGestureRecognizer?

     override func viewDidLoad() {
          super.viewDidLoad()
          // Create gesture with target self(viewcontroller) and handler function.
          self.panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.handlePan(recognizer:)))
          self.pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(self.handlePinch(recognizer:)))
          self.rotateRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(self.handleRotate(recognizer:)))
          //delegate gesture with UIGestureRecognizerDelegate
          pinchRecognizer?.delegate = self
          rotateRecognizer?.delegate = self
          panRecognizer?.delegate = self
          // than add gesture to imgView
          self.imgView.addGestureRecognizer(panRecognizer!)
          self.imgView.addGestureRecognizer(pinchRecognizer!)
          self.imgView.addGestureRecognizer(rotateRecognizer!)
     }

     // handle UIPanGestureRecognizer
     @objc func handlePan(recognizer: UIPanGestureRecognizer) {
          let gview = recognizer.view
          if recognizer.state == .began || recognizer.state == .changed {
               let translation = recognizer.translation(in: gview?.superview)
               gview?.center = CGPoint(x: (gview?.center.x)! + translation.x, y: (gview?.center.y)! + translation.y)
               recognizer.setTranslation(CGPoint.zero, in: gview?.superview)
          }
     }

     // handle UIPinchGestureRecognizer
     @objc func handlePinch(recognizer: UIPinchGestureRecognizer) {
          if recognizer.state == .began || recognizer.state == .changed {
               recognizer.view?.transform = (recognizer.view?.transform.scaledBy(x: recognizer.scale, y: recognizer.scale))!
               recognizer.scale = 1.0
         }
     }

     // handle UIRotationGestureRecognizer
     @objc func handleRotate(recognizer: UIRotationGestureRecognizer) {
          if recognizer.state == .began || recognizer.state == .changed {
               recognizer.view?.transform = (recognizer.view?.transform.rotated(by: recognizer.rotation))!
               recognizer.rotation = 0.0
           }
     }

     // mark sure you override this function to make gestures work together
     func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
         return true
     }

}
</code>```

Any question, just type to comment. thank you

Title: UIGestureRecognizer on UIImageView

Body:
I just done this with swift4 by adding 3 gestures together in single view

UIPinchGestureRecognizer : Zoom in and zoom out view.

UIRotationGestureRecognizer : Rotate the view.

UIPanGestureRecognizer : Dragging the view.

Here my sample code

class ViewController: UIViewController: UIGestureRecognizerDelegate{
      //your image view that outlet from storyboard or xibs file.
     @IBOutlet weak var imgView: UIImageView!
     // declare gesture recognizer
     var panRecognizer: UIPanGestureRecognizer?
     var pinchRecognizer: UIPinchGestureRecognizer?
     var rotateRecognizer: UIRotationGestureRecognizer?

     override func viewDidLoad() {
          super.viewDidLoad()
          // Create gesture with target self(viewcontroller) and handler function.
          self.panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.handlePan(recognizer:)))
          self.pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(self.handlePinch(recognizer:)))
          self.rotateRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(self.handleRotate(recognizer:)))
          //delegate gesture with UIGestureRecognizerDelegate
          pinchRecognizer?.delegate = self
          rotateRecognizer?.delegate = self
          panRecognizer?.delegate = self
          // than add gesture to imgView
          self.imgView.addGestureRecognizer(panRecognizer!)
          self.imgView.addGestureRecognizer(pinchRecognizer!)
          self.imgView.addGestureRecognizer(rotateRecognizer!)
     }

     // handle UIPanGestureRecognizer
     @objc func handlePan(recognizer: UIPanGestureRecognizer) {
          let gview = recognizer.view
          if recognizer.state == .began || recognizer.state == .changed {
               let translation = recognizer.translation(in: gview?.superview)
               gview?.center = CGPoint(x: (gview?.center.x)! + translation.x, y: (gview?.center.y)! + translation.y)
               recognizer.setTranslation(CGPoint.zero, in: gview?.superview)
          }
     }

     // handle UIPinchGestureRecognizer
     @objc func handlePinch(recognizer: UIPinchGestureRecognizer) {
          if recognizer.state == .began || recognizer.state == .changed {
               recognizer.view?.transform = (recognizer.view?.transform.scaledBy(x: recognizer.scale, y: recognizer.scale))!
               recognizer.scale = 1.0
         }
     }

     // handle UIRotationGestureRecognizer
     @objc func handleRotate(recognizer: UIRotationGestureRecognizer) {
          if recognizer.state == .began || recognizer.state == .changed {
               recognizer.view?.transform = (recognizer.view?.transform.rotated(by: recognizer.rotation))!
               recognizer.rotation = 0.0
           }
     }

     // mark sure you override this function to make gestures work together
     func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
         return true
     }

}

Any question, just type to comment. thank you


问:
Could not load file or assembly System.Net.Http version 4.1.1.0
I'm porting a Net Framework 4 dll to Net Core.
When porting my unit tests project I get an exception running some specific tests (not all).

System.IO.FileLoadException: Could not load file or assembly 'System.Net.Http, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

This is the project.json for my dll

```<code> {
  "version": "1.0.0-*",

  "dependencies": {
    "log4net": "2.0.7",
    "NETStandard.Library": "1.6.1",
    "Newtonsoft.Json": "9.0.1",
    "StackExchange.Redis": "1.2.1"
  },

  "frameworks": {
    "netstandard1.6": {
      "imports": "dnxcore50"
    }
  }
}
</code>```

And this is Packages.config for the unit tests project

```<code><packages>
  <package id="Castle.Core" version="4.0.0" targetFramework="net462" />
  <package id="log4net" version="2.0.7" targetFramework="net462" />
  <package id="Microsoft.Win32.Primitives" version="4.0.1" targetFramework="net462" />
  <package id="Moq" version="4.7.1" targetFramework="net462" />
  <package id="Newtonsoft.Json" version="9.0.1" targetFramework="net462" />
  <package id="StackExchange.Redis" version="1.2.1" targetFramework="net462" />
  <package id="System.Diagnostics.DiagnosticSource" version="4.0.0" targetFramework="net462" />
  <package id="System.IO" version="4.1.0" targetFramework="net462" />
  <package id="System.IO.FileSystem" version="4.0.1" targetFramework="net462" />
  <package id="System.IO.FileSystem.Primitives" version="4.0.1" targetFramework="net462" />
  <package id="System.IO.FileSystem.Watcher" version="4.0.0" targetFramework="net462" />
  <package id="System.Linq" version="4.1.0" targetFramework="net462" />
  <package id="System.Net.Http" version="4.1.1" targetFramework="net462" />
  <package id="System.Net.NameResolution" version="4.0.0" targetFramework="net462" />
  <package id="System.Runtime" version="4.1.0" targetFramework="net462" />
  <package id="System.Runtime.Extensions" version="4.1.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.Algorithms" version="4.2.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.Encoding" version="4.0.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.Primitives" version="4.0.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.X509Certificates" version="4.1.0" targetFramework="net462" />
  <package id="System.Text.RegularExpressions" version="4.1.0" targetFramework="net462" />
  <package id="System.Threading.Thread" version="4.0.0" targetFramework="net462" />
</packages>
</code>```

答:
I got the issue, and realized that it was because I had two different references.
one reference was from my project library, and the second one was a dependency of a .Net Standard library, and therefore a Nuget package.
The steps to solve were the following:

Remove the reference to System.Net.Http (project => add reference => remove the reference).

Keep the System.Net and System.Net.Http Nuget packages

Run Update-Package –reinstall System.Net.Http to bring back the reference.

Now it works again. :)

Body:
I'm porting a Net Framework 4 dll to Net Core.
When porting my unit tests project I get an exception running some specific tests (not all).

System.IO.FileLoadException: Could not load file or assembly 'System.Net.Http, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

This is the project.json for my dll

 {
  "version": "1.0.0-*",

  "dependencies": {
    "log4net": "2.0.7",
    "NETStandard.Library": "1.6.1",
    "Newtonsoft.Json": "9.0.1",
    "StackExchange.Redis": "1.2.1"
  },

  "frameworks": {
    "netstandard1.6": {
      "imports": "dnxcore50"
    }
  }
}

And this is Packages.config for the unit tests project

<packages>
  <package id="Castle.Core" version="4.0.0" targetFramework="net462" />
  <package id="log4net" version="2.0.7" targetFramework="net462" />
  <package id="Microsoft.Win32.Primitives" version="4.0.1" targetFramework="net462" />
  <package id="Moq" version="4.7.1" targetFramework="net462" />
  <package id="Newtonsoft.Json" version="9.0.1" targetFramework="net462" />
  <package id="StackExchange.Redis" version="1.2.1" targetFramework="net462" />
  <package id="System.Diagnostics.DiagnosticSource" version="4.0.0" targetFramework="net462" />
  <package id="System.IO" version="4.1.0" targetFramework="net462" />
  <package id="System.IO.FileSystem" version="4.0.1" targetFramework="net462" />
  <package id="System.IO.FileSystem.Primitives" version="4.0.1" targetFramework="net462" />
  <package id="System.IO.FileSystem.Watcher" version="4.0.0" targetFramework="net462" />
  <package id="System.Linq" version="4.1.0" targetFramework="net462" />
  <package id="System.Net.Http" version="4.1.1" targetFramework="net462" />
  <package id="System.Net.NameResolution" version="4.0.0" targetFramework="net462" />
  <package id="System.Runtime" version="4.1.0" targetFramework="net462" />
  <package id="System.Runtime.Extensions" version="4.1.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.Algorithms" version="4.2.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.Encoding" version="4.0.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.Primitives" version="4.0.0" targetFramework="net462" />
  <package id="System.Security.Cryptography.X509Certificates" version="4.1.0" targetFramework="net462" />
  <package id="System.Text.RegularExpressions" version="4.1.0" targetFramework="net462" />
  <package id="System.Threading.Thread" version="4.0.0" targetFramework="net462" />
</packages>


问:
UnicodeEncodeError in Mako Template
I have the following files

dummy.py

```<code>#!c:/Python27/python.exe -u

from mako import exceptions
from mako.template import Template

print "Content-type: text/html"
print

#VARIABLE = "WE"
VARIABLE = "我们"
template = Template(filename='../template/dummy.html', output_encoding='utf8')
try:
    print template.render(VARIABLE=VARIABLE)
except:
    print exceptions.html_error_template().render()
</code>```

dummy.html (Saved in UTF-8 format)

```<code>hello world
哈罗世界
${VARIABLE}
</code>```

I had refereed to the instruction from http://www.makotemplates.org/docs/unicode.html

However, I still get error

UnicodeDecodeError: 'ascii' codec
  can't decode byte 0xe6 in position 0:
  ordinal not in range(128)

Anything I had missed out?

答:
Yes, because you are trying to render it to ASCII, which doesn't work. You need to say what output_encoding to use:

```<code>Template(filename='../template/dummy.html', output_encoding='utf8')
</code>```

And please don't have bare excepts. Add what exceptions you expect to catch.

Title: UnicodeEncodeError in Mako Template

Body:
I have the following files

dummy.py

#!c:/Python27/python.exe -u

from mako import exceptions
from mako.template import Template

print "Content-type: text/html"
print

#VARIABLE = "WE"
VARIABLE = "我们"
template = Template(filename='../template/dummy.html', output_encoding='utf8')
try:
    print template.render(VARIABLE=VARIABLE)
except:
    print exceptions.html_error_template().render()

dummy.html (Saved in UTF-8 format)

hello world
哈罗世界
${VARIABLE}

I had refereed to the instruction from http://www.makotemplates.org/docs/unicode.html

However, I still get error

UnicodeDecodeError: 'ascii' codec
  can't decode byte 0xe6 in position 0:
  ordinal not in range(128)

Anything I had missed out?

Body:
Yes, because you are trying to render it to ASCII, which doesn't work. You need to say what output_encoding to use:

Template(filename='../template/dummy.html', output_encoding='utf8')

And please don't have bare excepts. Add what exceptions you expect to catch.


答: Hollow symmetric matrix. Hollow means the main diagonal has all zeroes. Symmetric means the upper triangle and lower triangle are "equal."</p>

Title: Name of a symmetric matrix with zeroes in the diagonal


问:
LibreOffice Command Line Convert CSV to DBF
I am working on a workflow where I need to be able to batch convert CSV files into DBF files. The data in the CSV files can all be output as TEXT fields and then saved as a DBF. I have tried to get any output possible using the command line in both Mac OS and Windows 7. While I was a little more successful in Windows, I was not able to get any conversion.

```<code>   "C:\Program Files (x86)\LibreOffice 5\program\scalc.exe" --convert-to dbf --

infilter="csv:44,34,76,1,1/2/2/2/3/2/4/2/5/2/6/2/7/2/8/2/9/2/10/2/11/2/12/2/13/2/14/2/15/2/16/2/17/2/18/2/19/2/20/2/21/2/22/2/23/2/24/2/25/2/26/2/27/2/28/2/29/2/30/2/31/2/32/2

/33/2/34/2/35/2/36/2/37/2/38/2/39/2/40/2/41/2/42/2/43/2/44/2/45/2/46/2/47/2/48/2/49/2/50/2/51/2/52/2/53/2/54/2/55/2/56/2/57/2/58/2/59/2/60/2/61/2/62/2/63/2/64/2/65/2/66/2/67/2

/68/2/69/2/70/2/71/2,0,false,false" C:\Users\jdavidson\Desktop\DBFCONVERT\*.csv --outdir C:\Users\jdavidson\desktop\complete
</code>```

So, I needed to have an --infilter on the command line to be able to do the conversion, but now it will only process 1 file and not batch file when using *.csv So, my next hurdle is to get over that.

The below helps to explain --infilters in more detail:

https://wiki.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Filter_Options#Filter_Options_for_Lotus.2C_dBase_and_DIF_Filters

Any easier way to find the filter sequence you need is by following the below listed steps:

Open the CSV Manually using LibreOffice and Specify Every Detail in the import Wizard

Run the below macro and it will show you the filter options in an input box, so you can copy the string in to your own code

Sub showFilterOptions
Dim args(),i%
   args() = thisComponent.getArgs
   for i = 0 to uBound(Args())
      if args(i).Name = "FilterOptions" then inputbox "","",args(i).value
   next
End Sub

Credit to code: https://forum.openoffice.org/en/forum/viewtopic.php?f=44&t=14018

答:
The parameters need to be reversed.  From https://ask.libreoffice.org/en/question/2641/convert-to-command-line-parameter/:

soffice --headless --convert-to <TargetFileExtension>:<NameOfFilter> file_to_convert.xxx

Using the old windows command prompt:

```<code>"C:\Program Files (x86)\LibreOffice 5\program\scalc.exe" --headless --convert-to dbf C:\Users\jdavidson\Desktop\DBFCONVERT\test.csv
</code>```

This will create test.dbf in the current directory, which is perhaps C:\Users\jdavidson or, if running as administrator, C:\Windows\system32.  To print the working directory, enter pwd, and then dir to see the file.

In powershell, add "& " in front to execute LibreOffice.  Then enter gci or ls to see the file.

Be sure that a LibreOffice process is not already running in the background.

Body:
I am working on a workflow where I need to be able to batch convert CSV files into DBF files. The data in the CSV files can all be output as TEXT fields and then saved as a DBF. I have tried to get any output possible using the command line in both Mac OS and Windows 7. While I was a little more successful in Windows, I was not able to get any conversion.

   "C:\Program Files (x86)\LibreOffice 5\program\scalc.exe" --convert-to dbf --

infilter="csv:44,34,76,1,1/2/2/2/3/2/4/2/5/2/6/2/7/2/8/2/9/2/10/2/11/2/12/2/13/2/14/2/15/2/16/2/17/2/18/2/19/2/20/2/21/2/22/2/23/2/24/2/25/2/26/2/27/2/28/2/29/2/30/2/31/2/32/2

/33/2/34/2/35/2/36/2/37/2/38/2/39/2/40/2/41/2/42/2/43/2/44/2/45/2/46/2/47/2/48/2/49/2/50/2/51/2/52/2/53/2/54/2/55/2/56/2/57/2/58/2/59/2/60/2/61/2/62/2/63/2/64/2/65/2/66/2/67/2

/68/2/69/2/70/2/71/2,0,false,false" C:\Users\jdavidson\Desktop\DBFCONVERT\*.csv --outdir C:\Users\jdavidson\desktop\complete

So, I needed to have an --infilter on the command line to be able to do the conversion, but now it will only process 1 file and not batch file when using *.csv So, my next hurdle is to get over that.

The below helps to explain --infilters in more detail:

https://wiki.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Filter_Options#Filter_Options_for_Lotus.2C_dBase_and_DIF_Filters

Any easier way to find the filter sequence you need is by following the below listed steps:

Open the CSV Manually using LibreOffice and Specify Every Detail in the import Wizard

Run the below macro and it will show you the filter options in an input box, so you can copy the string in to your own code

Sub showFilterOptions
Dim args(),i%
   args() = thisComponent.getArgs
   for i = 0 to uBound(Args())
      if args(i).Name = "FilterOptions" then inputbox "","",args(i).value
   next
End Sub

Credit to code: https://forum.openoffice.org/en/forum/viewtopic.php?f=44&t=14018

Body:
The parameters need to be reversed.  From https://ask.libreoffice.org/en/question/2641/convert-to-command-line-parameter/:

soffice --headless --convert-to <TargetFileExtension>:<NameOfFilter> file_to_convert.xxx

Using the old windows command prompt:

"C:\Program Files (x86)\LibreOffice 5\program\scalc.exe" --headless --convert-to dbf C:\Users\jdavidson\Desktop\DBFCONVERT\test.csv

This will create test.dbf in the current directory, which is perhaps C:\Users\jdavidson or, if running as administrator, C:\Windows\system32.  To print the working directory, enter pwd, and then dir to see the file.

In powershell, add "& " in front to execute LibreOffice.  Then enter gci or ls to see the file.

Be sure that a LibreOffice process is not already running in the background.


问:
What is the purpose of encrypting data at rest with AWS KMS?
I'm currently going about setting up encryption on AWS DynamoDB for individual columns on a table that are deemed sensitive. From my research, I've decided that the best way of doing this is likely with AWS KMS. From this sprouted a (perhaps very basic) question about the fundamental workings of doing this.

The true purpose, I would suppose, of me encrypting this data is to prevent people from accessing my data via a compromised AWS account (and perhaps AWS itself being compromised, but I'd imagine that's secondary). However, if my AWS account is compromised... doesn't the attacker have access to my KMS key (not directly, but the ability to use the API to encrypt and decrypt data?)

This is a really basic question, I'm sure, but I feel like I can't move forward with a hole in my knowledge this big.

答:
The purpose of having KMS is to protect your data while the key is never visible to your application since the key never leaves KMS. You submit data to AWS KMS to be encrypted, or decrypted, under keys that you control. You set usage policies on these keys that determine which users can use them to encrypt and decrypt data. All requests to use these keys are logged in AWS CloudTrail so you can understand who used which key when.

Having KMS makes it impossible for an attacker to get the encryption keys. Even if an attacker get on hold of your AWS Account(Assuming he gets Admin Access and KMS Access) and use KMS to decrypt a message, you will be able to see that through the logs in accessing these keys which is a necessary security steps to identify these threats.

So in general, if you provide least privilege to users(Not allowing everyone to access KMS), while keeping root account safe with MFA, it will be really difficult for an attacker to access KMS.


问:
iOS app got killed with "Message from debugger: Terminated due to signal 9" after 2 minutes running in background
I am developing a navigation like app. It works fine for the location manager to get the device's current location both in foreground and background.

In foreground it works fine for however long. However, when the app goes to background mode, initially the location manager works well. But after around 2 minutes, the app exited and the console shows the error message saying: "Message from debugger: Terminated due to signal 9."

I searched the error message, but still could not find the solution to it.
Quitting app causes error "Message from debugger: Terminated due to signal 9"

I noticed the CPU usage is very high, around 105% in background mode. This could be the reason that the OS send the KILL signal. But even if I decrease the location manager's accuracy (but for navigation purpose I still need the highest accuracy ultimately), the problem is still there.

So I am really wondering how those fitness apps managed to track user's locations in the background for however long without being killed by the OS.

答:
I think your problem is due to a complex graphical user interface which was refreshed every second even if the app was in background

To prevent the app to be killed while in background, stop doing high CPU using things, like rendering images, when the app is in background mode.