问:
MySQL Query with multiple AND statements seems to be ignoring one
I'm trying to run a query on a MySQL database, but I found that it seems to be ignoring the 'status' item.

```<code>SELECT * FROM  `posts`
WHERE
      `tags` LIKE '%gda%'
   OR `tags` LIKE '%contests%'
   OR `tags` LIKE '%merch%'
  AND `newsID` != '2134'
  AND `status` > '1'
ORDER BY  `postDate` DESC  LIMIT 5
</code>```

In that example, it's still pulling items even if 'status' is set to 0. What am I doing wrong?

答:
The problem is with the priority of OR/AND conditions. AND has a higher priority than OR, that's why it firstly evaluates all conditions connected by AND (tags-merch, newsID-2134 and status-1) and then evaluates the both tags-gda and tags-contests).

Try to add the brackets:

```<code>SELECT *
  FROM  `posts`
 WHERE (`tags` LIKE  '%gda%'
    OR  `tags` LIKE  '%contests%'
    OR  `tags` LIKE  '%merch%')
   AND  `newsID` !=  '2134'
   AND `status` > '1'
ORDER BY  `postDate` DESC
LIMIT 5
</code>```

Body:
I'm trying to run a query on a MySQL database, but I found that it seems to be ignoring the 'status' item.

SELECT * FROM  `posts`
WHERE
      `tags` LIKE '%gda%'
   OR `tags` LIKE '%contests%'
   OR `tags` LIKE '%merch%'
  AND `newsID` != '2134'
  AND `status` > '1'
ORDER BY  `postDate` DESC  LIMIT 5

In that example, it's still pulling items even if 'status' is set to 0. What am I doing wrong?

Body:
The problem is with the priority of OR/AND conditions. AND has a higher priority than OR, that's why it firstly evaluates all conditions connected by AND (tags-merch, newsID-2134 and status-1) and then evaluates the both tags-gda and tags-contests).

Try to add the brackets:

SELECT *
  FROM  `posts`
 WHERE (`tags` LIKE  '%gda%'
    OR  `tags` LIKE  '%contests%'
    OR  `tags` LIKE  '%merch%')
   AND  `newsID` !=  '2134'
   AND `status` > '1'
ORDER BY  `postDate` DESC
LIMIT 5


来源: stackexchange

问:
Selenium Compound Class Name [unable to insert a value]
I am currently having a hard time inserting a value into a field which is within a Frame, I have tried removing the spaces in the class name but it didn't work

class="ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched"

<textarea ng-if="$ctrl.fieldType.isTextarea($ctrl.field.fieldType, $ctrl.field.isHtmlFormatted)" ng-model="$ctrl.field.value" ng-change="$ctrl.onChange()" ng-required="$ctrl.field.isRequired" ng-class="{
    'input-sm': true,
    'form-control': true,
    'nc-pristine': $ctrl.getPristine(),
    'nc-not-pristine': $ctrl.getNotPristine()
   }" class="ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched"></textarea>```
</div>
</div>
</p>

<p>I have tried in Chrome Developer tool and it worked with this javascript code</p>

<p><strong>Chrome Console Developper Javascript</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].value='Hello World';</code>```

In Selenium I tried with these 2 ways none of them work:

Using Javascript

```<code>IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].value='Hello World';");
</code>```

Error Message:

```<code> System.InvalidOperationException occurred
  HResult=0x80131509
  Message=unknown error: Cannot set property 'value' of undefined
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScriptCommand(String script, String commandName, Object[] args)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScript(String script, Object[] args)
   at ConsoleApp5.Program.Main(String[] args)
</code>```

Using cssSelector, removing the spacing in the Class Name and replacing it with dots

```<code>driver.FindElement(By.CssSelector("ng-pristine.ng-valid.ng-scope.ng-empty.input-sm.form-control.nc-pristine.ng-valid-required.ng-touched")).SendKeys("Hello World");
</code>```

Error Message

```<code>  OpenQA.Selenium.NoSuchElementException occurred
  HResult=0x80131500
  Message=no such element: Unable to locate element: {"method":"css selector","selector":"ng-pristine.ng-valid.ng-scope.ng-empty.input-sm.form-control.nc-pristine.ng-valid-required.ng-touched"}
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElementByCssSelector(String cssSelector)
   at OpenQA.Selenium.By.<>c__DisplayClass23_0.<CssSelector>b__0(ISearchContext context)
   at OpenQA.Selenium.By.FindElement(ISearchContext context)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(By by)
</code>```

答:
Given the html provided try this:

```<code>driver.findElement(By.cssSelector("div > div > nc-editable-field > textarea"));
</code>```

Also, you stated that the element is in Frame, are you sure that you are switching to that frame correctly?

ContentLicense: CC BY-SA 3.0

Body:
I am currently having a hard time inserting a value into a field which is within a Frame, I have tried removing the spaces in the class name but it didn't work

class="ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched"

<textarea ng-if="$ctrl.fieldType.isTextarea($ctrl.field.fieldType, $ctrl.field.isHtmlFormatted)" ng-model="$ctrl.field.value" ng-change="$ctrl.onChange()" ng-required="$ctrl.field.isRequired" ng-class="{
    'input-sm': true,
    'form-control': true,
    'nc-pristine': $ctrl.getPristine(),
    'nc-not-pristine': $ctrl.getNotPristine()
   }" class="ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched"></textarea>

I have tried in Chrome Developer tool and it worked with this javascript code

Chrome Console Developper Javascript

document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].value='Hello World';

In Selenium I tried with these 2 ways none of them work:

Using Javascript

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("document.getElementsByClassName('ng-pristine ng-valid ng-scope ng-empty input-sm form-control nc-pristine ng-valid-required ng-touched')[0].value='Hello World';");

Error Message:

 System.InvalidOperationException occurred
  HResult=0x80131509
  Message=unknown error: Cannot set property 'value' of undefined
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScriptCommand(String script, String commandName, Object[] args)
   at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScript(String script, Object[] args)
   at ConsoleApp5.Program.Main(String[] args)

Using cssSelector, removing the spacing in the Class Name and replacing it with dots

driver.FindElement(By.CssSelector("ng-pristine.ng-valid.ng-scope.ng-empty.input-sm.form-control.nc-pristine.ng-valid-required.ng-touched")).SendKeys("Hello World");

Error Message

  OpenQA.Selenium.NoSuchElementException occurred
  HResult=0x80131500
  Message=no such element: Unable to locate element: {"method":"css selector","selector":"ng-pristine.ng-valid.ng-scope.ng-empty.input-sm.form-control.nc-pristine.ng-valid-required.ng-touched"}
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)
  Source=WebDriver
  StackTrace:
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElementByCssSelector(String cssSelector)
   at OpenQA.Selenium.By.<>c__DisplayClass23_0.<CssSelector>b__0(ISearchContext context)
   at OpenQA.Selenium.By.FindElement(ISearchContext context)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(By by)

Body:
Given the html provided try this:

driver.findElement(By.cssSelector("div > div > nc-editable-field > textarea"));

Also, you stated that the element is in Frame, are you sure that you are switching to that frame correctly?


问:
SQLSTATE[42S02]: Base table or view not found Error with laravel curl
I have written two laravel apps. FirstApp and CryptoApp ( name of apps respectively )

In which I send encrypted text to a function called ( Decrypt ) in CryptoApp that is supposed to return decrypted text

In FirstApp i am sending a curl POST request with the encrypted text to CryptoApp

cURL post code: inside FirstApp

```<code>private function DecryptApi($data)
{

    $ch = curl_init();                    // initiate curl
    $url = "http://crypto.dev/Decrypt"; // where you want to post data
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POST, true);  // tell curl you want to post something
    curl_setopt($ch, CURLOPT_POSTFIELDS, "data=".$data); // define what you want to post
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return the output in string format
    $output = curl_exec ($ch); // execute

    curl_close ($ch); // close curl handle

    return $output; // show output

}
</code>```

The Route : Route::post('/Decrypt','CryptoController@Decrypt');

The Function :

```<code>public function Decrypt(Request $request)
{
    $crypt =  Crypto::find(1);

    return openssl_decrypt($request['data'],"AES-256-CBC",$crypt->secretKey,0,$crypt->iv);

}
</code>```

the Error i am getting is  : "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel_firstapp.crypto' doesn't exist (SQL: select * from crypto where crypto.id = 1 limit 1)"

this error has confused me because i know that FirstApp does not have a table named 'crypto' but CryptoApp does, why is laravel not returning the text i want ?

答:
You have to check if the crypto table already exists in your CryptoApp, also  check .env file in your CryptoApp, maybe it's configured with FirstApp database, it should be:

CryptoApp .env file

```<code>...
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=CryptoApp_database
DB_USERNAME=user
DB_PASSWORD=****
...
</code>```

Body:
I have written two laravel apps. FirstApp and CryptoApp ( name of apps respectively )

In which I send encrypted text to a function called ( Decrypt ) in CryptoApp that is supposed to return decrypted text

In FirstApp i am sending a curl POST request with the encrypted text to CryptoApp

cURL post code: inside FirstApp

private function DecryptApi($data)
{

    $ch = curl_init();                    // initiate curl
    $url = "http://crypto.dev/Decrypt"; // where you want to post data
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POST, true);  // tell curl you want to post something
    curl_setopt($ch, CURLOPT_POSTFIELDS, "data=".$data); // define what you want to post
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return the output in string format
    $output = curl_exec ($ch); // execute

    curl_close ($ch); // close curl handle

    return $output; // show output

}

The Route : Route::post('/Decrypt','CryptoController@Decrypt');

The Function :

public function Decrypt(Request $request)
{
    $crypt =  Crypto::find(1);

    return openssl_decrypt($request['data'],"AES-256-CBC",$crypt->secretKey,0,$crypt->iv);

}

the Error i am getting is  : "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel_firstapp.crypto' doesn't exist (SQL: select * from crypto where crypto.id = 1 limit 1)"

this error has confused me because i know that FirstApp does not have a table named 'crypto' but CryptoApp does, why is laravel not returning the text i want ?

Body:
You have to check if the crypto table already exists in your CryptoApp, also  check .env file in your CryptoApp, maybe it's configured with FirstApp database, it should be:

CryptoApp .env file

...
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=CryptoApp_database
DB_USERNAME=user
DB_PASSWORD=****
...


问:
python lossless audio recording+http streaming library
I am working on a simple service to remotely record line input from an audio interface attached to a server, via REST API request.

My current solution, using PyAudio to manage the audio interface:

1) send HTTP request to start recording to a file on server filesystem.

2) send HTTP request to stop recording and pull the recorded audio file from the server filesystem

Instead, I would like to be able to just "stream" the line input to any http client who wants to download the audio stream.

Is there any simple python library solution to lossless http audio streaming directly from any audio interface's input?

More importantly, does this make sense or should I use RTSP instead? (More than efficiency I would like to focus on being able to download the audio stream by a simple http link on a browser or even via curl or simple programmatic request, and I'll usually not have more than one connected client at a time, that's why I'd prefer to avoid RTSP.)

答: I have done this using Python flask to provide the REST endpoint to stream audio, and the pyfaac module to pack PCM frames into the AAC format (this format is needed for streaming).  Then, for example, you use the standard HTML5 audio tag with src set to your streaming endpoint.</p>


问:
Angular Material: mat-select not selecting default
I have a mat-select where the options are all objects defined in an array.  I am trying to set the value to default to one of the options, however it is being left selected when the page renders.

My typescript file contains:

```<code>  public options2 = [
    {"id": 1, "name": "a"},
    {"id": 2, "name": "b"}
  ]
  public selected2 = this.options2[1].id;
</code>```

My HTML file contains:

```<code>  <div>
    <mat-select
        [(value)]="selected2">
      <mat-option
          *ngFor="let option of options2"
          value="{{ option.id }}">
        {{ option.name }}
      </mat-option>
    </mat-select>
  </div>
</code>```

I have tried setting selected2 and the value in mat-option to both the object and its id, and have tried using both [(value)] and [(ngModel)] in the mat-select, but none are working.

I am using material version 2.0.0-beta.10

答:
You should be binding it as [value] in the mat-option as below,

```<code><mat-select placeholder="Panel color" [(value)]="selected2">
  <mat-option *ngFor="let option of options2" [value]="option.id">
    {{ option.name }}
  </mat-option>
</mat-select>
</code>```

LIVE DEMO

ContentLicense: CC BY-SA 4.0

Body:
I have a mat-select where the options are all objects defined in an array.  I am trying to set the value to default to one of the options, however it is being left selected when the page renders.

My typescript file contains:

  public options2 = [
    {"id": 1, "name": "a"},
    {"id": 2, "name": "b"}
  ]
  public selected2 = this.options2[1].id;

My HTML file contains:

    <mat-select
        [(value)]="selected2">
      <mat-option
          *ngFor="let option of options2"
          value="{{ option.id }}">
        {{ option.name }}
      </mat-option>
    </mat-select>

I have tried setting selected2 and the value in mat-option to both the object and its id, and have tried using both [(value)] and [(ngModel)] in the mat-select, but none are working.

I am using material version 2.0.0-beta.10

Body:
You should be binding it as [value] in the mat-option as below,

<mat-select placeholder="Panel color" [(value)]="selected2">
  <mat-option *ngFor="let option of options2" [value]="option.id">
    {{ option.name }}
  </mat-option>
</mat-select>

LIVE DEMO


问:
c# What happens if I use code a .NET 3.5 function on a machine that has .Net 2 installed
Just out of interest, if I built some code using the Enumerable.Distinct function which appeared in .Net 3.5 and then ran it on a machine with .Net 2.0 on it, what would happen?</p>

答: You will be able to compile a 3.5 Framework project and run it on the 2.0 Framework as long as you don't have any 3.5 Framework references.  In your case, you are using Enumerable.Distinct which is in the 3.5 Framework references, so your application will fail.

ContentLicense: CC BY-SA 2.5


问:
Navigate to other route if Redux action is finished (or failed)
I've got more or less the same question as this one: React-Router: how to wait for an async action before route transition

Current situation:

When I'm for example on my Home page, I click a post (e.g. /news/news-article). I immidiately navigate to the route, and I'm showing a Loader untill my Redux action has Fetched the posts content, and then I load the content. (This is also what 'jmancherje' answerred in the other question)

But this means that I have to show a loader on EVERY page my user visits, and this is not what I want.

So what I want:

When I'm on the Home, and I click to another post, I want to wait with navigation to the next route, untill my action has finished (or failed) loading the content.

This seems possible with React-Router-Redux, but I can't find out how to achieve this.

Updated question:

My action looks like this:

```<code>export function fetchPage(post_type, postSlug) {
    return function (dispatch) {
        dispatch({type: FETCH_PAGE_START});
        axios.get(`${url}/wp-json/wp/v2/${post_type}?slug=${postSlug}`)
            .then(response => {
                dispatch({
                    type: FETCH_PAGE,
                    payload: response.data
                });
                dispatch(push('/')) // do the routing here
            })
            .catch(function (error) {
              dispatch({
                    type: FAILED_PAGE
                });
            });
    }
}
</code>```

My store looks more or less like this:

```<code>const appliedMiddleware = applyMiddleware( thunk, createLogger(), routerMiddleware(history));
export default createStore(combinedReducers, appliedMiddleware);
</code>```

So I think i'm on the right way, but still I can't get it to work. It still navigates immediately instead of a delay.

答:
This is pretty much covered in details here regarding react-redux async action. But in short, one of the way is you can use redux-thunk middleware as such:

```<code>import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);
</code>```

Once you have redux-thunk middleware, in your action_post.js you can do something like this:

```<code>export function fetchPost(id) {
    return dispatch => {
        dispatch(fetchPostRequest())
        axios.get(`/api/post/${id}`)
        .then(res => {
            dispatch(fetchPostSuccess(res.data))
            dispatch(push('/postView')) // do the routing here
        })
        .catch(err => {
            dispatch(fetchPostFailure(err))
        })
    }
}

function fetchPostRequest() {
    return {
        type: "FETCH_POST_REQUEST"
    }
}

function fetchPostSuccess(data) {
    return {
        type: "FETCH_POST_SUCCESS",
        data
    }
}

function fetchPostFailure(err) {
    return {
        type: "FETCH_POST_FAILURE",
        err
    }
}
</code>```

Body:
I've got more or less the same question as this one: React-Router: how to wait for an async action before route transition

Current situation:

When I'm for example on my Home page, I click a post (e.g. /news/news-article). I immidiately navigate to the route, and I'm showing a Loader untill my Redux action has Fetched the posts content, and then I load the content. (This is also what 'jmancherje' answerred in the other question)

But this means that I have to show a loader on EVERY page my user visits, and this is not what I want.

So what I want:

When I'm on the Home, and I click to another post, I want to wait with navigation to the next route, untill my action has finished (or failed) loading the content.

This seems possible with React-Router-Redux, but I can't find out how to achieve this.

Updated question:

My action looks like this:

export function fetchPage(post_type, postSlug) {
    return function (dispatch) {
        dispatch({type: FETCH_PAGE_START});
        axios.get(`${url}/wp-json/wp/v2/${post_type}?slug=${postSlug}`)
            .then(response => {
                dispatch({
                    type: FETCH_PAGE,
                    payload: response.data
                });
                dispatch(push('/')) // do the routing here
            })
            .catch(function (error) {
              dispatch({
                    type: FAILED_PAGE
                });
            });
    }
}

My store looks more or less like this:

const appliedMiddleware = applyMiddleware( thunk, createLogger(), routerMiddleware(history));
export default createStore(combinedReducers, appliedMiddleware);

So I think i'm on the right way, but still I can't get it to work. It still navigates immediately instead of a delay.

Body:
This is pretty much covered in details here regarding react-redux async action. But in short, one of the way is you can use redux-thunk middleware as such:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

Once you have redux-thunk middleware, in your action_post.js you can do something like this:

export function fetchPost(id) {
    return dispatch => {
        dispatch(fetchPostRequest())
        axios.get(`/api/post/${id}`)
        .then(res => {
            dispatch(fetchPostSuccess(res.data))
            dispatch(push('/postView')) // do the routing here
        })
        .catch(err => {
            dispatch(fetchPostFailure(err))
        })
    }
}

function fetchPostRequest() {
    return {
        type: "FETCH_POST_REQUEST"
    }
}

function fetchPostSuccess(data) {
    return {
        type: "FETCH_POST_SUCCESS",
        data
    }
}

function fetchPostFailure(err) {
    return {
        type: "FETCH_POST_FAILURE",
        err
    }
}


问:
What is causing a segmentation fault in this function?
So, as an exercise, I am developing a code that uses a recursive function in order to make a simple mathematical expressions calculator. The problem is, I am getting a segmentation fault (6) or (11) when I run it, but I have checked a hundred times and each function call seems to be accessing memory only from the variables in the function just above it on the stack, provided by the pointer *init. Where am I getting this wrong?

Code is as follows:

```<code>int solve(char *expression, int *init) {

  int result;
  int l = strlen(expression);
  int i = *init;

  //Inicializing result:
  for (int n = 0; n <= l; n++) {
    if ((expression[n]=='1')||(expression[n]=='2')||(expression[n]=='3')||(expression[n]=='4')||(expression[n]=='5')||
    (expression[n]=='6')||(expression[n]=='7')||(expression[n]=='8')||(expression[n]=='9')) {
        result = expression[n]-48;
        break;
    }
  }

//Doing calculations:
  int j = i;
  for (j; j <= l; j++) {
    if (expression[j] == '(') {
      result = result + solve(expression, &j);
    }
    if (expression[j] == '+')
      result = result + (expression[j+1]-48);
    if (expression[j] == '-')
      result = result - (expression[j+1]-48);
    if (expression[j] == '*')
      result = result * (expression[j+1]-48);
    if (expression[j] == '/')
      result = result / (expression[j+1]-48);
    if (expression[j] == ')')
      return result;
  }
  return result;
}
</code>```

答:
There is infinite recursion in the code

```<code>int solve(char *expression, int *init) {
  /* ... */
  int j = i;
  for (j; j <= l; j++) {
    if (expression[j] == '(') {
      result = result + solve(expression, &j);
  /* ... */
</code>```

If it ever founds a '(' in expression, then the function is called over and over again with the same parameters, until the program stack is filled up. Then you get a segfault.

When using loops or recursion, you should always make sure that the construct eventually terminates, i.e. it gets demonstrably closer to the terminating condition on every iteration. It's trivial to see when doing a simple loop like for(i=0;i<x;i++), but considerably harder when the iteration and the terminating conditions are scattered over a recursive function.

It's not the only problem with your code, but arguably the most severe one.

Body:
So, as an exercise, I am developing a code that uses a recursive function in order to make a simple mathematical expressions calculator. The problem is, I am getting a segmentation fault (6) or (11) when I run it, but I have checked a hundred times and each function call seems to be accessing memory only from the variables in the function just above it on the stack, provided by the pointer *init. Where am I getting this wrong?

Code is as follows:

int solve(char *expression, int *init) {

  int result;
  int l = strlen(expression);
  int i = *init;

  //Inicializing result:
  for (int n = 0; n <= l; n++) {
    if ((expression[n]=='1')||(expression[n]=='2')||(expression[n]=='3')||(expression[n]=='4')||(expression[n]=='5')||
    (expression[n]=='6')||(expression[n]=='7')||(expression[n]=='8')||(expression[n]=='9')) {
        result = expression[n]-48;
        break;
    }
  }

//Doing calculations:
  int j = i;
  for (j; j <= l; j++) {
    if (expression[j] == '(') {
      result = result + solve(expression, &j);
    }
    if (expression[j] == '+')
      result = result + (expression[j+1]-48);
    if (expression[j] == '-')
      result = result - (expression[j+1]-48);
    if (expression[j] == '*')
      result = result * (expression[j+1]-48);
    if (expression[j] == '/')
      result = result / (expression[j+1]-48);
    if (expression[j] == ')')
      return result;
  }
  return result;
}

Body:
There is infinite recursion in the code

int solve(char *expression, int *init) {
  /* ... */
  int j = i;
  for (j; j <= l; j++) {
    if (expression[j] == '(') {
      result = result + solve(expression, &j);
  /* ... */

If it ever founds a '(' in expression, then the function is called over and over again with the same parameters, until the program stack is filled up. Then you get a segfault.

When using loops or recursion, you should always make sure that the construct eventually terminates, i.e. it gets demonstrably closer to the terminating condition on every iteration. It's trivial to see when doing a simple loop like for(i=0;i<x;i++), but considerably harder when the iteration and the terminating conditions are scattered over a recursive function.

It's not the only problem with your code, but arguably the most severe one.


问:
Checkbox not working in TCP/IP settings
I've been trying to get powershell to check boxes in the TCP/IP Settings on a printer, but not able to get it to work.  It seems that the  comes up different in these settings than the rest of it where the boxes do work.

```<code>input id="vac.255.ALLOW_DHCP_TO_UPDATE_TIMESERVER"
name="vac.255.ALLOW_DHCP_TO_UPDATE_TIMESERVER" value="1" type="checkbox"  is the info in TCP/IP.
</code>```

input name="2.system.17245" value="1" id="system.17245" checked="" type="checkbox" is the info that is in the rest of the printer.  Below is the code that works it checks and unchecks with no issues.

```<code>$adfbeep = $ie.Document.IHTMLDocument3_getElementByID("system.17245") | Where-Object {$_.type -eq "checkbox"}
$adfbeep.checked=$true
</code>```

Below is essentially the same, but doesn't work.  Not sure if it is because the name and id are the same.

```<code>$updttimeserver = $ie.Document.IHTMLDocument3_getElementByID("vac.255.ALLOW_DHCP_TO_UPDATE_TIMESERVER") | Where-Object {$_.type -eq "checkbox"}
$updttimeserver.checked=$true

The property 'checked' cannot be found on this object. Verify that the property exists
and can be set.
At C:\Scripts\CX310 Config.ps1:132 char:1
+ $updttimeserver.checked=$true
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFound
</code>```

Any help would be appreciated.  Sorry if it seems a bit over the place

答: I figured it out.  For these kind of checkboxes it required IHTMLDocument3_getElementsByName("vac.255.ALLOW_DHCP_TO_UPDATE_TIMESERVER") instead of IHTMLDocument3_getElementByID("vac.255.ALLOW_DHCP_TO_UPDATE_TIMESERVER")  The ones without vac.255 in it used getElementByID.

Title: Checkbox not working in TCP/IP settings

Body:
I've been trying to get powershell to check boxes in the TCP/IP Settings on a printer, but not able to get it to work.  It seems that the  comes up different in these settings than the rest of it where the boxes do work.

input id="vac.255.ALLOW_DHCP_TO_UPDATE_TIMESERVER"
name="vac.255.ALLOW_DHCP_TO_UPDATE_TIMESERVER" value="1" type="checkbox"  is the info in TCP/IP.

input name="2.system.17245" value="1" id="system.17245" checked="" type="checkbox" is the info that is in the rest of the printer.  Below is the code that works it checks and unchecks with no issues.

$adfbeep = $ie.Document.IHTMLDocument3_getElementByID("system.17245") | Where-Object {$_.type -eq "checkbox"}
$adfbeep.checked=$true

Below is essentially the same, but doesn't work.  Not sure if it is because the name and id are the same.

$updttimeserver = $ie.Document.IHTMLDocument3_getElementByID("vac.255.ALLOW_DHCP_TO_UPDATE_TIMESERVER") | Where-Object {$_.type -eq "checkbox"}
$updttimeserver.checked=$true

The property 'checked' cannot be found on this object. Verify that the property exists
and can be set.
At C:\Scripts\CX310 Config.ps1:132 char:1
+ $updttimeserver.checked=$true
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFound

Any help would be appreciated.  Sorry if it seems a bit over the place


问:
NSRegularExpression not evaluating correctly
I have the following regular expression for passwords which evaluates correctly on online regex testers for Password.123:

```<code>/(?!^[0-9]*$)(?!^[a-z]*$)(?!^[A-Z]*$)(?!^[\\W]*$)(^[a-zA-Z0-9\\W]).{7,}/
</code>```

When I make an NSRegularExpression in swift it evaluates incorrectly and cannot find a match for Password.123:

```<code>let password = "Password.123"

let regex = try! NSRegularExpression(pattern: "/(?!^[0-9]*$)(?!^[a-z]*$)(?!^[A-Z]*$)(?!^[\\W]*$)(^[a-zA-Z0-9\\W]).{7,}/", options: [])

let range = NSRange(location: 0, length: password.count)
print("Valid: \(regex.firstMatch(in: password, options: [], range: range) != nil)")
</code>```

This prints false but should be true. Where am I going wrong?

答:
Remove the /'s from your string. I.e.

```<code>let regex = try! NSRegularExpression(pattern: "(?!^[0-9]*$)(?!^[a-z]*$)(?!^[A-Z]*$)(?!^[\\W]*$)(^[a-zA-Z0-9\\W]).{7,}", options: [])
</code>```

Body:
I have the following regular expression for passwords which evaluates correctly on online regex testers for Password.123:

/(?!^[0-9]*$)(?!^[a-z]*$)(?!^[A-Z]*$)(?!^[\\W]*$)(^[a-zA-Z0-9\\W]).{7,}/

When I make an NSRegularExpression in swift it evaluates incorrectly and cannot find a match for Password.123:

let password = "Password.123"

let regex = try! NSRegularExpression(pattern: "/(?!^[0-9]*$)(?!^[a-z]*$)(?!^[A-Z]*$)(?!^[\\W]*$)(^[a-zA-Z0-9\\W]).{7,}/", options: [])

let range = NSRange(location: 0, length: password.count)
print("Valid: \(regex.firstMatch(in: password, options: [], range: range) != nil)")

This prints false but should be true. Where am I going wrong?

Body:
Remove the /'s from your string. I.e.

let regex = try! NSRegularExpression(pattern: "(?!^[0-9]*$)(?!^[a-z]*$)(?!^[A-Z]*$)(?!^[\\W]*$)(^[a-zA-Z0-9\\W]).{7,}", options: [])


问:
Moving commits branched from master onto a previous commit in master
I'm attempting to move commits from branch "feature" to a new branch, which is forked from an earlier commit than "feature".

Suppose my tree looks like this:

```<code>master   A - B - C
                  \
feature            D - E
</code>```

I'd like to move my feature commits D and E to a new branch derived from commit A, so that my tree looks like this:

```<code>desired    D - E
          /
master   A - B - C
                  \
feature             D - E
</code>```

I created branch "desired" from A and attempted to rebase commits in "feature" onto the tip of "desired", but doing so pulled in commits B and C. Why didn't this rebase work, and how can I move these commits?

答:
Let's redraw the commit graph in a way that better represents git's data structures.  You have

```<code>A - B - C <--(master)
         \
          D - E <--(feature)
</code>```

Then you go back to A and create the desired branch, which gives you

```<code>A <--(desired)
 \
  B - C <--(master)
       \
        D - E <--(feature)
</code>```

Now I assume you said

```<code>git rebsae desired feature
</code>```

thinking that the feature branch means "commits D and E".  But a branch isn't a set of commits; it's a pointer to one commit (hence my rearrangement of the graph).  In git commits are "reachable from refs"; there isn't a real concept of a commit being "on a branch" or "not on a branch" beyond that.

So what makes B and C different from D and E?  They're all reachable from feature; but B and C are also reachable from master (which is why you don't think of them as being "on the feature branch").

Which brings us to your first question: the rebase command didn't do what you want, because the rebase command as you issued it doesn't know or care about the master ref.  The upstream is desired (from which A is reachable) and the source branch is feature (from which A, B, C, D, and E are reachable).  So the rebase rewrites desired..feature - i.e. everything reachable from feature but not reachable from desired - and that includes B and C.

What you want is to make master your upstream, so that the command will rewrite master..feature (i.e. D and E only).  That in turn means you want the new base to be something other than the upstream, which calls for the --onto option

```<code>git rebase --onto desired master feature
</code>```

yielding

```<code>  D' - E' <--(feature)
 /
A <--(desired)
 \
  B - C <--(master)
       \
        D - E
</code>```

(I kept D and E in the picture to emphasize the reason for calling the new commits D' and E'.  The original commits are not deleted; if they're reachable from refs other than feature, those refs will still "see" the original commits.  The feature branch now reaches two new commits with identity distinct from the original D and E.)

Body:
I'm attempting to move commits from branch "feature" to a new branch, which is forked from an earlier commit than "feature".

Suppose my tree looks like this:

master   A - B - C
                  \
feature            D - E

I'd like to move my feature commits D and E to a new branch derived from commit A, so that my tree looks like this:

desired    D - E
          /
master   A - B - C
                  \
feature             D - E

I created branch "desired" from A and attempted to rebase commits in "feature" onto the tip of "desired", but doing so pulled in commits B and C. Why didn't this rebase work, and how can I move these commits?

Body:
Let's redraw the commit graph in a way that better represents git's data structures.  You have

A - B - C <--(master)
         \
          D - E <--(feature)

Then you go back to A and create the desired branch, which gives you

A <--(desired)
 \
  B - C <--(master)
       \
        D - E <--(feature)

Now I assume you said

git rebsae desired feature

thinking that the feature branch means "commits D and E".  But a branch isn't a set of commits; it's a pointer to one commit (hence my rearrangement of the graph).  In git commits are "reachable from refs"; there isn't a real concept of a commit being "on a branch" or "not on a branch" beyond that.

So what makes B and C different from D and E?  They're all reachable from feature; but B and C are also reachable from master (which is why you don't think of them as being "on the feature branch").

Which brings us to your first question: the rebase command didn't do what you want, because the rebase command as you issued it doesn't know or care about the master ref.  The upstream is desired (from which A is reachable) and the source branch is feature (from which A, B, C, D, and E are reachable).  So the rebase rewrites desired..feature - i.e. everything reachable from feature but not reachable from desired - and that includes B and C.

What you want is to make master your upstream, so that the command will rewrite master..feature (i.e. D and E only).  That in turn means you want the new base to be something other than the upstream, which calls for the --onto option

git rebase --onto desired master feature

yielding

  D' - E' <--(feature)
 /
A <--(desired)
 \
  B - C <--(master)
       \
        D - E

(I kept D and E in the picture to emphasize the reason for calling the new commits D' and E'.  The original commits are not deleted; if they're reachable from refs other than feature, those refs will still "see" the original commits.  The feature branch now reaches two new commits with identity distinct from the original D and E.)


答:
have you tried something like:</p>

```<code>SELECT * FROM  `posts`
WHERE
     ( `tags` LIKE '%gda%'
   OR `tags` LIKE '%contests%'
   OR `tags` LIKE '%merch%')
  AND `newsID` != '2134'
  AND `status` > '1'
ORDER BY  `postDate` DESC  LIMIT 5
</code>```

Title: MySQL Query with multiple AND statements seems to be ignoring one

Body:
I'm trying to run a query on a MySQL database, but I found that it seems to be ignoring the 'status' item.

SELECT * FROM  `posts`
WHERE
      `tags` LIKE '%gda%'
   OR `tags` LIKE '%contests%'
   OR `tags` LIKE '%merch%'
  AND `newsID` != '2134'
  AND `status` > '1'
ORDER BY  `postDate` DESC  LIMIT 5

In that example, it's still pulling items even if 'status' is set to 0. What am I doing wrong?

Body:
have you tried something like:

SELECT * FROM  `posts`
WHERE
     ( `tags` LIKE '%gda%'
   OR `tags` LIKE '%contests%'
   OR `tags` LIKE '%merch%')
  AND `newsID` != '2134'
  AND `status` > '1'
ORDER BY  `postDate` DESC  LIMIT 5


问:
Is possible to concatenate multible fields with one that is a conditional iif statement
I'm working on an ssrs report using Report builder 2008, currently trying to concatenate using something like this but when I do so, I receive an error for the field 'lifeamount' specifying that the expression can only refer to fields within the current dataset scope. I've tried different ways to specify the dataset which is the same for all the fields but to no avail. Is this even possible?

=rtrim(First(Fields!FRSTNAME.Value,"EmployeeInfo")) & " " & rtrim(First(Fields!MIDLNAME.Value, "EmployeeInfo")) & " " & rtrim(First(Fields!LASTNAME.Value, "EmployeeInfo")) & " " & IIF((Fields!Lifeamount.Value)> 100000.00, 100000.00, Fields!lifeamount.value, "EmployeeInfo"))

答:
If the expression is located in a cell that is within the same scope as the details you are fetching (i.e. "EmployeeInfo") then I don't think you need to specify it at all.

Also there are some brackets out of place I think. I can't test it at the moment but try this...

```<code>=rtrim(First(Fields!FRSTNAME.Value,"EmployeeInfo")) & " " &
rtrim(First(Fields!MIDLNAME.Value, "EmployeeInfo")) & " " &
rtrim(First(Fields!LASTNAME.Value, "EmployeeInfo")) & " " &
IIF((Fields!Lifeamount.Value, "EmployeeInfo")> 100000.00, 100000.00, (Fields!Lifeamount.value, "EmployeeInfo"))
</code>```

Body:
If the expression is located in a cell that is within the same scope as the details you are fetching (i.e. "EmployeeInfo") then I don't think you need to specify it at all.

Also there are some brackets out of place I think. I can't test it at the moment but try this...

=rtrim(First(Fields!FRSTNAME.Value,"EmployeeInfo")) & " " &
rtrim(First(Fields!MIDLNAME.Value, "EmployeeInfo")) & " " &
rtrim(First(Fields!LASTNAME.Value, "EmployeeInfo")) & " " &
IIF((Fields!Lifeamount.Value, "EmployeeInfo")> 100000.00, 100000.00, (Fields!Lifeamount.value, "EmployeeInfo"))


问:
How to assign value in 2 Dimensional array
Creating a tile pattern

```<code>char t1[11][11];
int i=0;
int j=0;

int size = 10;
//Putting "|" for tile1 (0,0) to (11,0)
for(i=0;i<11;i++)
{
    while(j=0)
    {
        t1[i][j] = '|';
    }
}

//Putting "-" for tile1 (0,0) to (0,11)
for(j=1;j<10;j++)
{
    while(i=0)
    {
        t1[i][j] = '-';
    }
}

//PRINTING  "|" for tile1 (0,0) to (11,0)
for(i=0;i<11;i++){
    while(j=0){
        printf("%c \n",t1[i][j]);
    }
    printf("\n");
}

//PRINTING "-" for tile1 (0,0) to (0,11)
for(j=1;j<10;j++)
{
    while(i=0)
    {
        printf("%c "), t1[i][j];
    }
}
</code>```

So basically I want the output to be like the image given.
I declared an array with 11,11 size and I am trying to use loops to assign characters in the array. But for some reason it is not working.

I know I have to use loops so I drew the pattern on a paper and write down the array location and tried to assign using loops.

答:
With a bigger 2D array you can make the code shorter:</p>

```<code>#define VSIZE 13
#define HSIZE 25

char t1[VSIZE][HSIZE];

for(int i = 0; i < VSIZE ; ++i) {
    for(int j = 1; j < HSIZE - 2; ++j) {
        // default value for odd columns:
        char c = ' ';
        // but change it to something else in an even column:
        if(!(j%2)) {
            if(i == 0 || i == VSIZE - 1)
                c = '-';
            if(i == 1 || i == VSIZE - 2 || 2 * i == j)
                c = '@';
        }
        t1[i][j] = c;
    }
    t1[i][0] = t1[i][HSIZE - 2] = '|';
    t1[i][HSIZE - 1] = '\0';   // turn the row to a string closing it with '\0'

    printf("%s\n", t1[i]);
}
</code>```

Body:
Creating a tile pattern

char t1[11][11];
int i=0;
int j=0;

int size = 10;
//Putting "|" for tile1 (0,0) to (11,0)
for(i=0;i<11;i++)
{
    while(j=0)
    {
        t1[i][j] = '|';
    }
}

//Putting "-" for tile1 (0,0) to (0,11)
for(j=1;j<10;j++)
{
    while(i=0)
    {
        t1[i][j] = '-';
    }
}

//PRINTING  "|" for tile1 (0,0) to (11,0)
for(i=0;i<11;i++){
    while(j=0){
        printf("%c \n",t1[i][j]);
    }
    printf("\n");
}

//PRINTING "-" for tile1 (0,0) to (0,11)
for(j=1;j<10;j++)
{
    while(i=0)
    {
        printf("%c "), t1[i][j];
    }
}

So basically I want the output to be like the image given.
I declared an array with 11,11 size and I am trying to use loops to assign characters in the array. But for some reason it is not working.

I know I have to use loops so I drew the pattern on a paper and write down the array location and tried to assign using loops.

Body:
With a bigger 2D array you can make the code shorter:

#define VSIZE 13
#define HSIZE 25

char t1[VSIZE][HSIZE];

for(int i = 0; i < VSIZE ; ++i) {
    for(int j = 1; j < HSIZE - 2; ++j) {
        // default value for odd columns:
        char c = ' ';
        // but change it to something else in an even column:
        if(!(j%2)) {
            if(i == 0 || i == VSIZE - 1)
                c = '-';
            if(i == 1 || i == VSIZE - 2 || 2 * i == j)
                c = '@';
        }
        t1[i][j] = c;
    }
    t1[i][0] = t1[i][HSIZE - 2] = '|';
    t1[i][HSIZE - 1] = '\0';   // turn the row to a string closing it with '\0'

    printf("%s\n", t1[i]);
}


问:
Regex to match comma separated values?
I am looking for a regular expression which accepts comma separated values(no space) of both string and numbers(especially mobile numbers, 10 digits) for client side validation.

I have gone through regexlib.com but i couldn't find good one.

UPDATE

Input patterns:

```<code>9655770780,college,8095145098,schoolmates
</code>```

Its a just a input field, users can enter group name of mobile numbers or just the numbers.

Any suggestions!

答:
Regular expressions may be overkill for this problem.

You could use:

```<code>var csv_values = csv_string.split(",");
</code>```

This would split on the commas and give you your values

Title: Regex to match comma separated values?

Body:
I am looking for a regular expression which accepts comma separated values(no space) of both string and numbers(especially mobile numbers, 10 digits) for client side validation.

I have gone through regexlib.com but i couldn't find good one.

UPDATE

Input patterns:

9655770780,college,8095145098,schoolmates

Its a just a input field, users can enter group name of mobile numbers or just the numbers.

Any suggestions!

Body:
Regular expressions may be overkill for this problem.

You could use:

var csv_values = csv_string.split(",");

This would split on the commas and give you your values


问:
Automate Azure VM server SQL job backup copy to another server?
I Have Azure VM server. In that I have a job set up for automatic backup to Azure local storage. I will need to store a copy of that backup in another server? How do I do that? Is there any way to do it automatically?</p>

答:
To automate you backup process from one server to another server using azure storage service, you have to make three batch files.

It will take backup of your db and will store it locally. here is the command to do that.

set FileName=DBName_%date:~-4,4%%date:~-10,2%%date:~-7,2%.bacpac
echo %FileName%
"C:\Program Files (x86)\Microsoft SQL Server\140\DAC\bin\sqlpackage.exe" /a:Export /ssn:your IP(00:00:00) /sdn:yourdatabaseName /tf:"D:\%FileName%" /su:username /sp:"password"

It will post your locally saved backup file to Azure storage.

"C:\AzCopy\AzCopy.exe" /Source:D: /Dest:https://youstoragedestination.link/blobname/ /DestKey:yourAzureStoragekey /Pattern:"*.bacpac" /Y
del "d:*.bacpac"

from this batch file call above two batch file
example:
call "yourpath\backupFile.bat"
call "youpath\backupFilepushing2azure.bat"

you can schedule your third batch file to automate your process.
Now you have pushed your backup file to Azure Storage, which is enough i think.
If you really want to save that backup file to another server then make another batch file that will download your backup file from blob to server using AzCopy.


问:
nullpointer in kieservices.factory.get()
I am trying to use drools 7 and kie.
I would like to understand which libraries i need to import for every line of code because probably in production we cant use maven.

Now I import only two libraries: kie-api.7.3 and kie-internal.7.3 and I have a nullpointer  in the first line of code

```<code>KieServices ks = KieServices.Factory.get();
</code>```

What could be the problem?

答:
But if you can add those .jars, why can't you add all the .jar files that are under the binaries folder inside the .zip that you download from here: https://download.jboss.org/drools/release/7.4.1.Final/droolsjbpm-tools-distribution-7.4.1.Final.zip ?

I just added them all to my project and it is running well in production

Body:
I am trying to use drools 7 and kie.
I would like to understand which libraries i need to import for every line of code because probably in production we cant use maven.

Now I import only two libraries: kie-api.7.3 and kie-internal.7.3 and I have a nullpointer  in the first line of code

KieServices ks = KieServices.Factory.get();

What could be the problem?


问:
Ad management system in PHP?
I have created a website in PHP, now I want to add ad support there. Clients request for ads at some fixed locations in the website, they provide there ad in a fixed size.

I am looking for a CMS or Script which is able to manage ads, as per the ad area in the site. It should be able to manage that if an ad needs to be run for 10 days then that ad will be displayed there for 10 days and after that it will randomly pick the ads for that particular area.

Do anyone know any such CMS which offers such kind of facility, open-source CMS will be better but if there is any paid CMS for such functionality, then that's fine.

Please help, Thanks!

答:
I recommend OpenX

Could be used community hosted or as an open source software on your server.

Title: Ad management system in PHP?


问:
pandas merge giving more rows
I have two panda dataframe that I need to join merge.

```<code>nd = cu.groupby('division')['usage'].nsmallest(5).rename('t_usage').reset_index()
nd = nd.merge(cu, left_on='level_1', right_index = True)
nd.shape
</code>```

I have basically taken top 5 elements by usage in each division but when I merge this to my main dataframe I get lot of extra row. I am inner-joining on the level_1 which is the old index in the new dataframe over "right index".

expected row count: 92, actual row count after merge: 737.

Thanks for any assistance!

Title: pandas merge giving more rows

Body:
I have two panda dataframe that I need to join merge.

nd = cu.groupby('division')['usage'].nsmallest(5).rename('t_usage').reset_index()
nd = nd.merge(cu, left_on='level_1', right_index = True)
nd.shape

I have basically taken top 5 elements by usage in each division but when I merge this to my main dataframe I get lot of extra row. I am inner-joining on the level_1 which is the old index in the new dataframe over "right index".

expected row count: 92, actual row count after merge: 737.

Thanks for any assistance!

Body:
I think your code should be simplify with apply and nsmallest:

np.random.seed(1997)

cu = pd.DataFrame({'division':np.random.choice(list('abcdef'), size=30),
                   'usage':np.random.randint(100, size=30),
                   'cols':np.random.randint(10, size=30)})

print (cu)

    cols division  usage
0      5        f      0
1      0        b     22
2      2        a     73
3      6        a     38
4      5        c     82
5      9        b     39
6      5        a      9
7      2        a     81
8      9        b     27
9      5        b     27
10     7        e     90
11     1        d     13
12     1        f     33
13     4        b     21
14     9        a     27
15     6        f     89
16     5        a     20
17     3        c     98
18     6        b     74
19     9        a     82
20     3        f     52
21     8        c     79
22     6        f     17
23     0        d     91
24     9        d     73
25     8        e     33
26     9        d      1
27     1        f     52
28     7        d     40
29     3        f     16

nd = cu.groupby('division', group_keys=False).apply(lambda x: x.nsmallest(5, 'usage'))
print (nd)

    cols division  usage
6      5        a      9
16     5        a     20
14     9        a     27
3      6        a     38
2      2        a     73
13     4        b     21
1      0        b     22
8      9        b     27
9      5        b     27
5      9        b     39
21     8        c     79
4      5        c     82
17     3        c     98
26     9        d      1
11     1        d     13
28     7        d     40
24     9        d     73
23     0        d     91
25     8        e     33
10     7        e     90
0      5        f      0
29     3        f     16
22     6        f     17
12     1        f     33
20     3        f     52


问:
XLST not ignoring namespace prefix
I have the following xmldata input, which should be transformed via xslt.
I simply want to extract the ns:something content. The dynamicNS namespace can be different during runtime.

```<code><?xml version="1.0"?>
<dynamicNS:header>
  <ns:something>
    <ns:myid>1</ns:myid>
    <ns:myvalue>2</ns:myvalue>
  </ns:something>
</dynamicNS:header>
</code>```

The output should be:

```<code><?xml version="1.0"?>
  <ns:something>
    <ns:myid>1</ns:myid>
    <ns:myvalue>2</ns:myvalue>
  </ns:something>
</code>```

I tried it with:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="*">
      <ns:something>
          <xsl:copy-of select="node()"/>
      </ns:something>
    </xsl:template>

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

But this gives me the error: The prefix "dynamicNS" for element "dynamicNS:header" is not bound.;

I don't wan't to add the namespace for the dynamicNS because it can be different for each run.

What is the correct way to get my desired output?

Thanks guys.

答:
If you want to omit the root element and its namespace declaration(s) and only copy its child elements then in XSLT 2 and later you can use

to make a copy of all child elements of the root, for instance the input

```<code><dynamicNS:header xmlns:dynamicNS="http://example.com/foo">
  <ns:something xmlns:ns="http://example.com/ns">
    <ns:myid>1</ns:myid>
    <ns:myvalue>2</ns:myvalue>
  </ns:something>
</dynamicNS:header>
</code>```

is transformed into the result

```<code><ns:something xmlns:ns="http://example.com/ns">
    <ns:myid>1</ns:myid>
    <ns:myvalue>2</ns:myvalue>
  </ns:something>
</code>```

http://xsltransform.hikmatu.com/gWcDMee

As I said already in the comments, both the input to XSLT as well as the stylesheet code need to be namespace well-formed XML documents, so the input and output you posted in the question with prefixes for which no namespace declarations exist do not allow XSLT processing.

Title: XLST not ignoring namespace prefix

Body:
I have the following xmldata input, which should be transformed via xslt.
I simply want to extract the ns:something content. The dynamicNS namespace can be different during runtime.

<?xml version="1.0"?>
<dynamicNS:header>
  <ns:something>
    <ns:myid>1</ns:myid>
    <ns:myvalue>2</ns:myvalue>
  </ns:something>
</dynamicNS:header>

The output should be:

<?xml version="1.0"?>
  <ns:something>
    <ns:myid>1</ns:myid>
    <ns:myvalue>2</ns:myvalue>
  </ns:something>

I tried it with:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="*">
      <ns:something>
          <xsl:copy-of select="node()"/>
      </ns:something>
    </xsl:template>

</xsl:stylesheet>

But this gives me the error: The prefix "dynamicNS" for element "dynamicNS:header" is not bound.;

I don't wan't to add the namespace for the dynamicNS because it can be different for each run.

What is the correct way to get my desired output?

Thanks guys.

Body:
If you want to omit the root element and its namespace declaration(s) and only copy its child elements then in XSLT 2 and later you can use

to make a copy of all child elements of the root, for instance the input

<dynamicNS:header xmlns:dynamicNS="http://example.com/foo">
  <ns:something xmlns:ns="http://example.com/ns">
    <ns:myid>1</ns:myid>
    <ns:myvalue>2</ns:myvalue>
  </ns:something>
</dynamicNS:header>

is transformed into the result

<ns:something xmlns:ns="http://example.com/ns">
    <ns:myid>1</ns:myid>
    <ns:myvalue>2</ns:myvalue>
  </ns:something>

http://xsltransform.hikmatu.com/gWcDMee

As I said already in the comments, both the input to XSLT as well as the stylesheet code need to be namespace well-formed XML documents, so the input and output you posted in the question with prefixes for which no namespace declarations exist do not allow XSLT processing.


问:
what's the difference difference between phantom.exit and .close in phantom.js?
If I'm doing web scraping using phantom.js to click some buttons and links what's the convenient one to terminate program with ?

http://phantomjs.org/api/webpage/method/close.html
http://phantomjs.org/api/phantom/method/exit.html

答:
PhantomJS .exit() is a core method of phantom Object and you can use it to quit the phantomjs program instance (like Nodejs process.exit).
This is the convenient method to terminate your program.

```<code>console.log('Quitting Phantomjs');
phantom.exit();
</code>```

.close() method is part of Web Page Module and is used to close a web page.

```<code>var webPage = require('webpage');
var page = webPage.create();

page.open('http://github.com', function (status) {
  if (status === "success") {
    // do stuff
    page.close();
  }
})
</code>```

Body:
PhantomJS .exit() is a core method of phantom Object and you can use it to quit the phantomjs program instance (like Nodejs process.exit).
This is the convenient method to terminate your program.

console.log('Quitting Phantomjs');
phantom.exit();

.close() method is part of Web Page Module and is used to close a web page.

var webPage = require('webpage');
var page = webPage.create();

page.open('http://github.com', function (status) {
  if (status === "success") {
    // do stuff
    page.close();
  }
})


问:
apache httpd mod_proxy_hcheck in VirtualHost not work
http://httpd.apache.org/docs/2.4/mod/mod_proxy_hcheck.html

```<code><VirtualHost *:80>

ProxyHCExpr ok234 {%{REQUEST_STATUS} =~ /^[234]/}
ProxyHCExpr ok23 {%{REQUEST_STATUS} =~ /^[23]/}
ProxyHCExpr in_maint {hc('body') !~ /The requested resource is not available/}

<proxy balancer://cluster>
BalancerMember http://192.168.0.1:8181/examples hcmethod=GET hcexpr=ok23 hcinterval=2 hcuri=/status
BalancerMember http://192.168.0.2:8282/examples hcmethod=GET hcexpr=in_maint hcinterval=2 hcuri=/servlet
ProxySet lbmethod=byrequests
</proxy>

ProxyPass /examples balancer://cluster
ProxyPassReverse /examples balancer://cluster

</VirtualHost>
</code>```

Put the configuration of module hcheck in the VirtualHost,back-end tomcat not accept heartbeat message?

答:
I hit the same problem and found out that this is a known bug of mod_proxy_hcheck. It seems to have been fixed in 2.4.26, even though I can't confirm as I didn't test it yet.
Older Apache releases are still common in popular Linux distributions so I thought it could be helpful to know.</p>

Body:
http://httpd.apache.org/docs/2.4/mod/mod_proxy_hcheck.html

<VirtualHost *:80>

ProxyHCExpr ok234 {%{REQUEST_STATUS} =~ /^[234]/}
ProxyHCExpr ok23 {%{REQUEST_STATUS} =~ /^[23]/}
ProxyHCExpr in_maint {hc('body') !~ /The requested resource is not available/}

<proxy balancer://cluster>
BalancerMember http://192.168.0.1:8181/examples hcmethod=GET hcexpr=ok23 hcinterval=2 hcuri=/status
BalancerMember http://192.168.0.2:8282/examples hcmethod=GET hcexpr=in_maint hcinterval=2 hcuri=/servlet
ProxySet lbmethod=byrequests
</proxy>

ProxyPass /examples balancer://cluster
ProxyPassReverse /examples balancer://cluster

</VirtualHost>

Put the configuration of module hcheck in the VirtualHost,back-end tomcat not accept heartbeat message?


问:
pod install -bash: pod: command not found
I installed pod some time ago. However, it's stopped working so I'm working through this again.

However, I almost immediately run into a problem here:

```<code>pod install
-bash: pod: command not found
</code>```

Any suggestions why this happened?

答:
Sudo-less installation

If you do not want to grant RubyGems admin privileges for this process, you can tell RubyGems to install into your user directory by passing either the --user-install flag to gem install or by configuring the RubyGems environment. The latter is in our opinion the best solution. To do this, create or edit the .profile file in your home directory and add or amend it to include these lines:

```<code>export GEM_HOME=$HOME/.gem
export PATH=$GEM_HOME/bin:$PATH
</code>```

Note that if you choose to use the --user-install option, you will still have to configure your .profile file to set the PATH or use the command prepended by the full path. You can find out where a gem is installed with gem which cocoapods. E.g.

```<code>$ gem install cocoapods --user-install
$ gem which cocoapods
/Users/eloy/.gem/ruby/2.0.0/gems/cocoapods-0.29.0/lib/cocoapods.rb
$ /Users/eloy/.gem/ruby/2.0.0/bin/pod install
</code>```

Source: https://guides.cocoapods.org/using/getting-started.html

Body:
I installed pod some time ago. However, it's stopped working so I'm working through this again.

However, I almost immediately run into a problem here:

pod install
-bash: pod: command not found

Any suggestions why this happened?

Body:
Sudo-less installation

If you do not want to grant RubyGems admin privileges for this process, you can tell RubyGems to install into your user directory by passing either the --user-install flag to gem install or by configuring the RubyGems environment. The latter is in our opinion the best solution. To do this, create or edit the .profile file in your home directory and add or amend it to include these lines:

export GEM_HOME=$HOME/.gem
export PATH=$GEM_HOME/bin:$PATH

Note that if you choose to use the --user-install option, you will still have to configure your .profile file to set the PATH or use the command prepended by the full path. You can find out where a gem is installed with gem which cocoapods. E.g.

$ gem install cocoapods --user-install
$ gem which cocoapods
/Users/eloy/.gem/ruby/2.0.0/gems/cocoapods-0.29.0/lib/cocoapods.rb
$ /Users/eloy/.gem/ruby/2.0.0/bin/pod install

Source: https://guides.cocoapods.org/using/getting-started.html


答:
Short answer: .close() clears memory, .exit() may not.

.close() belongs to phantomjs' webpage.

.exit() belongs to phantomjs process itself.

If you do a lot of automated tasks, opening pages and not closing them -
 this can cause memory leak.

So preferred way to terminate is to 1. close the page and 2. exit phantom after that.

Title: what's the difference difference between phantom.exit and .close in phantom.js?

Body:
If I'm doing web scraping using phantom.js to click some buttons and links what's the convenient one to terminate program with ?

http://phantomjs.org/api/webpage/method/close.html
http://phantomjs.org/api/phantom/method/exit.html


问:
IDE's Java runtime (1.8u111) is outdated - this may cause stability issues. Please update to 1.8.0u112 or newer while opening PhpStorm in Ubuntu 16.10
I recently updated PhpStorm to latest version 2017.1 and I get following message while starting PhpStorm

IDE's Java runtime (1.8u111) is outdated - this may cause stability
  issues. Please update to 1.8.0u112 or newer

答:
But If you don't have the latest JDK, download it from:
Download latest JAVA JDK here

And then select the "IDE BOOT JDK" like Tall Liou told.


问:
Why can't I create new classes in AX any more?
I created a new class in AX. After an AX restart the class was no longer in the AOT. If I now try to create a new class I get this error message:

"Unable to save . Unable to save Class Class2. Id 50001 already exists."

How can I fix that problem?

答:
you Just close the services of Ax and delete the .aoi file.
then restart the services.
now try to create class.
Thanks and Regards,
Deepak Kumar</p>


问:
ASP.NET MVC ADO.NET Query per table row
Here I have this table:

If I click the button, I want to pass the table per row to the controller, then perform ADO.NET Query per row, like for example, perform "UPDATE tbluser SET note='INACTIVE' WHERE id=@id" per row.

One of the main purpose of this is when i filter the table, only the visible rows will be passed.

I already have a code here to pass to controller using AJAX but I don't know what to do afterwards.

JS:

```<code>var HTMLtbl =
{
    getData: function (table) {
        var data = [];
        oTable.rows({ search: 'applied' }).every(function () {
            var cols = [];
            var rowNode = this.node();
            $(rowNode).find("td").each(function () {
                cols.push($(this).text().trim() || null);
            });
            data.push(cols);
        });
        return data;
    }
}

$("btnSubmit").on("click", function () {
    var data = HTMLtbl.getData($(".datatable"));
    var parameters = {};
    parameters.array = data;

    var request = $.ajax({
        async: true,
        cache: false,
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Home/SubmitTable",
        data: JSON.stringify(parameters),
        success: function () {
            window.location.href = "/Home/Index";
        }
    });

    request.fail(function (jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
});
</code>```

Controller:

```<code>[HttpPost]
public JsonResult SubmitTable(string[][] array)
{
    //I don't know what to do here now, please help
}
</code>```

My Solution based on Mostafa's answer:

JS:

```<code>var HTMLtbl =
{
    getData: function () {
        var data = [];
        oTable.rows({ search: 'applied' }).every(function () {
            var cols = [];
            var rowNode = this.node();
            $(rowNode).find("td").each(function () {
                cols.push($(this).text().trim() || null);
            });
            data.push(cols);
        });
        return data;
    }
}

$("#btnSubmit").on("click", function () {
    var data = HTMLtbl.getData($(".datatable"));
    var parameters = {};
    parameters.array = data;

    var request = $.ajax({
        async: true,
        cache: false,
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Home/SubmitTable",
        data: JSON.stringify(parameters),
        success: function () {
            window.location.href = "/Home/Index";
        }
    });

    request.fail(function (jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
});
</code>```

Controller:

```<code>[HttpPost]
    public JsonResult SubmitTable(string[][] array)
    {
        string result = string.Empty;
        try
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
            con.Open();
            foreach (var arr in array)
            {
                SqlCommand cmd = new SqlCommand("UPDATE tbluser SET remark='INACTIVE' WHERE id = @id", con);
                cmd.Parameters.AddWithValue("@id", arr[0]);
                cmd.ExecuteNonQuery();
            }
            con.Close();
        }
        catch (Exception ex)
        {
            result = ex.Message;
        }
        return Json("Records updated successfully.", JsonRequestBehavior.AllowGet);
    }
</code>```

I can now use this for more complicated stuff, thanks

答:
If you want to update a custom row you can add a button for each row with custom text and icon, then add a "data-" attribute to this button and path your row id,

```<code><input type="button" data-rowId="1" class="changeActivationState">activate</input>
</code>```

in this example I added a data field to my imput after that I define this javascript method:

```<code>  $(".changeActivationState").click(function(){
    $(this).data("rowId")//get the selected row id and call you service
  });
</code>```

using this code you can read first element for each row and perform a web service call for all rows

```<code>  var arr = [];
  $("#yourtable tr").each(function(){
      arr.push($(this).find("td:first").text()); //put elements into array
  });
</code>```

and using this code you can read all rows into a json object

```<code> var tbl = $('#yourtable tr').map(function() {
    return $(this).find('td').map(function() {
    return $(this).html();
   }).get();
 }).get();
</code>```

assume that you passed the list to action

```<code>  int[] passedIDsfromBrowser = ///filled with data that comes from browser;
  SqlConnection connection = ....
  SqlCommand command = new SqlCommand(connection);
  command.CommandText = "Update MYTABLENAME Set Active = true where ID in (" string.Join(",", passedIDsfromBrowser ) + ")";
   connection.Open();
   command.ExecuteNonQuery();
   connection.Close();
</code>```

this is a pseudo code.
or if you want a loop and updating each row with a loop

```<code>  SqlConnection connection = ....
  SqlCommand command = new SqlCommand(connection);
  connection.Open();
  for(int i = 0 ; i < passedIDsfromBrowser.Length; i++){
     command.CommandText = "YOURQUERY";
     command.ExecuteNonQuery();
  }
  connection.Close();
</code>```

Title: ASP.NET MVC ADO.NET Query per table row

Body:
Here I have this table:

If I click the button, I want to pass the table per row to the controller, then perform ADO.NET Query per row, like for example, perform "UPDATE tbluser SET note='INACTIVE' WHERE id=@id" per row.

One of the main purpose of this is when i filter the table, only the visible rows will be passed.

I already have a code here to pass to controller using AJAX but I don't know what to do afterwards.

JS:

var HTMLtbl =
{
    getData: function (table) {
        var data = [];
        oTable.rows({ search: 'applied' }).every(function () {
            var cols = [];
            var rowNode = this.node();
            $(rowNode).find("td").each(function () {
                cols.push($(this).text().trim() || null);
            });
            data.push(cols);
        });
        return data;
    }
}

$("btnSubmit").on("click", function () {
    var data = HTMLtbl.getData($(".datatable"));
    var parameters = {};
    parameters.array = data;

    var request = $.ajax({
        async: true,
        cache: false,
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Home/SubmitTable",
        data: JSON.stringify(parameters),
        success: function () {
            window.location.href = "/Home/Index";
        }
    });

    request.fail(function (jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
});

Controller:

[HttpPost]
public JsonResult SubmitTable(string[][] array)
{
    //I don't know what to do here now, please help
}

My Solution based on Mostafa's answer:

JS:

var HTMLtbl =
{
    getData: function () {
        var data = [];
        oTable.rows({ search: 'applied' }).every(function () {
            var cols = [];
            var rowNode = this.node();
            $(rowNode).find("td").each(function () {
                cols.push($(this).text().trim() || null);
            });
            data.push(cols);
        });
        return data;
    }
}

$("#btnSubmit").on("click", function () {
    var data = HTMLtbl.getData($(".datatable"));
    var parameters = {};
    parameters.array = data;

    var request = $.ajax({
        async: true,
        cache: false,
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Home/SubmitTable",
        data: JSON.stringify(parameters),
        success: function () {
            window.location.href = "/Home/Index";
        }
    });

    request.fail(function (jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
});

Controller:

[HttpPost]
    public JsonResult SubmitTable(string[][] array)
    {
        string result = string.Empty;
        try
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
            con.Open();
            foreach (var arr in array)
            {
                SqlCommand cmd = new SqlCommand("UPDATE tbluser SET remark='INACTIVE' WHERE id = @id", con);
                cmd.Parameters.AddWithValue("@id", arr[0]);
                cmd.ExecuteNonQuery();
            }
            con.Close();
        }
        catch (Exception ex)
        {
            result = ex.Message;
        }
        return Json("Records updated successfully.", JsonRequestBehavior.AllowGet);
    }

I can now use this for more complicated stuff, thanks

Body:
If you want to update a custom row you can add a button for each row with custom text and icon, then add a "data-" attribute to this button and path your row id,

<input type="button" data-rowId="1" class="changeActivationState">activate</input>

in this example I added a data field to my imput after that I define this javascript method:

  $(".changeActivationState").click(function(){
    $(this).data("rowId")//get the selected row id and call you service
  });

using this code you can read first element for each row and perform a web service call for all rows

  var arr = [];
  $("#yourtable tr").each(function(){
      arr.push($(this).find("td:first").text()); //put elements into array
  });

and using this code you can read all rows into a json object

 var tbl = $('#yourtable tr').map(function() {
    return $(this).find('td').map(function() {
    return $(this).html();
   }).get();
 }).get();

assume that you passed the list to action

  int[] passedIDsfromBrowser = ///filled with data that comes from browser;
  SqlConnection connection = ....
  SqlCommand command = new SqlCommand(connection);
  command.CommandText = "Update MYTABLENAME Set Active = true where ID in (" string.Join(",", passedIDsfromBrowser ) + ")";
   connection.Open();
   command.ExecuteNonQuery();
   connection.Close();

this is a pseudo code.
or if you want a loop and updating each row with a loop

  SqlConnection connection = ....
  SqlCommand command = new SqlCommand(connection);
  connection.Open();
  for(int i = 0 ; i < passedIDsfromBrowser.Length; i++){
     command.CommandText = "YOURQUERY";
     command.ExecuteNonQuery();
  }
  connection.Close();


问:
R shiny output to external file
I'm running a shiny app from the command line and I would like to redirect shiny output to an external file like for example logs.txt instead of console output:

```<code>"Loading required package: shiny
Warning: package ‘shiny’ was built under R version 3.2.4
(...)
Failed with error:  ‘Package ‘shiny’ version 0.13.1 cannot be unloaded’

Listening on http://127.0.0.1:3333" > logs.txt
</code>```

Is that even possible?

答:
You can maybe have something like this, it will create a file in the working directory and all the messages will be written into it

```<code>#Set up writing
con <- file("shiny.log")
sink(con, append=TRUE)
sink(con, append=TRUE, type="message")

library(shiny)
ui <- fluidPage(
  mainPanel()
)

server <- function(input,output,session){
  message(paste0("Logged in at ", Sys.time()))
}
shinyApp(ui, server)
</code>```

Title: R shiny output to external file

Body:
I'm running a shiny app from the command line and I would like to redirect shiny output to an external file like for example logs.txt instead of console output:

"Loading required package: shiny
Warning: package ‘shiny’ was built under R version 3.2.4
(...)
Failed with error:  ‘Package ‘shiny’ version 0.13.1 cannot be unloaded’

Listening on http://127.0.0.1:3333" > logs.txt

Is that even possible?

Body:
You can maybe have something like this, it will create a file in the working directory and all the messages will be written into it

#Set up writing
con <- file("shiny.log")
sink(con, append=TRUE)
sink(con, append=TRUE, type="message")

library(shiny)
ui <- fluidPage(
  mainPanel()
)

server <- function(input,output,session){
  message(paste0("Logged in at ", Sys.time()))
}
shinyApp(ui, server)


问:
how to get all connected users in websocket using simplebroker or rabbitMQ with java spring
how to get all connected users in websocket chat app using simplebroker or rabbitMQ with java spring</p>

答:
You can use SimpUserRegistry;</p>

```<code>@Autowired
SimpUserRegistry simpUserRegistry;
...
public void foo(){
    simpUserRegistry.getUsers();
}
</code>```

Body:
You can use SimpUserRegistry;

@Autowired
SimpUserRegistry simpUserRegistry;
...
public void foo(){
    simpUserRegistry.getUsers();
}


问:
Setting values in matrix based on values in vector
If I have a 3 x 3 matrix called tmp and vector data such that

```<code>tmp = [1,0,0;2,0,0;3,0,0];
data = [1,3];
data = transpose(data);
</code>```

In every row whose first element matches an element in data, I want to update that value in the second column to 1. This would result in tmp looking like this:

```<code>tmp = [1,1,0;2,0,0;3,1,0];
</code>```

Is there a way I can do this without a for loop?

答:
if you have really only two elements in data, this would do the trick :</p>

```<code>tmp(:,2)=or(tmp(:,1)==data(1),tmp(:,1)==data(2))
</code>```

Body:
If I have a 3 x 3 matrix called tmp and vector data such that

tmp = [1,0,0;2,0,0;3,0,0];
data = [1,3];
data = transpose(data);

In every row whose first element matches an element in data, I want to update that value in the second column to 1. This would result in tmp looking like this:

tmp = [1,1,0;2,0,0;3,1,0];

Is there a way I can do this without a for loop?

Body:
if you have really only two elements in data, this would do the trick :

tmp(:,2)=or(tmp(:,1)==data(1),tmp(:,1)==data(2))


问:
Why isn't the variable and its content visible in HTML
Okay I've tried multiple iterations of this code and its not working, I see [object Object] in the H3 tag

This is going to be fundamentally obvious and I'm just missing a core point, I've been scanning stack but can't seem to find why this is happening

So I need the item thats being retrieved from the year ID to be displayed inside the H3 tag, I used the alert function as a test to ensure the value from year was being taken correctly and it is

I've tried

```<code>var age ={};
    function ageinyear() {
        age = document.getElementById("year").value;
        var agetest = age;
    }</script>

<h3 id="userWelcome"><span id="splitColorHeading">
    Welcome <script> document.write(agetest)</script>,</span> to THE SESH</h3>
</code>```

No dice

```<code>var age;
    function ageinyear() {
        age = document.getElementById("year").value;
    }</script>

<h3 id="userWelcome"><span id="splitColorHeading">
    Welcome <script> document.write(age)</script>,</span> to THE SESH</h3>
</code>```

EDIT: I declared both variables inside the function as well as outside, both trying to make them global
Flexing my minuscule brain cells is this possibly due to no return statement, if so added one where I believed it would fit, still no luck

Still nothing,

Can anyone help a beginner out possibly showing and example or show me with my code what I'm missing as well as an explanation why

Many thanks!

More code:

```<code><div id="overlay">
<div id="text">Are you over 18 years old?</div>
<div id="off"><button onclick="off(), ageinyear()">Submit</button></div>
<div id="test"><form>
    <label>
        Name
        <input id="name" name="lblname" type="text" />
    </label>
    <label>
        Age
        <input id="year" name="lblyear" type="text" />
    </label>
</form>
</div>
</code>```

答:
Consider the sequence of events you're defining here:

```<code><script>
var age;
function ageinyear() {
    age = document.getElementById("year").value;
}
</script>

<script>document.write(age)</script>
</code>```

Defining a function doesn't invoke a function.  So essentially the above is the same as this:

```<code><script>
var age;
</script>

<script>document.write(age)</script>
</code>```

No value is being written to the page because there's no value in that variable.  It's declared, but it's undefined.

Instead of trying to output to the page immediately (as in, before the user has set the value), output to the page in the function that gets invoked by the user setting the value.  Something like this:

```<code><script>
var age;
function ageinyear() {
    age = document.getElementById("year").value;
    document.getElementById("yearOutput").textContent = age;
}
</script>

<span id="yearOutput"></span>
</code>```

Body:
Okay I've tried multiple iterations of this code and its not working, I see [object Object] in the H3 tag

This is going to be fundamentally obvious and I'm just missing a core point, I've been scanning stack but can't seem to find why this is happening

So I need the item thats being retrieved from the year ID to be displayed inside the H3 tag, I used the alert function as a test to ensure the value from year was being taken correctly and it is

I've tried

var age ={};
    function ageinyear() {
        age = document.getElementById("year").value;
        var agetest = age;
    }</script>

    Welcome , to THE SESH

No dice

var age;
    function ageinyear() {
        age = document.getElementById("year").value;
    }</script>

    Welcome , to THE SESH

EDIT: I declared both variables inside the function as well as outside, both trying to make them global
Flexing my minuscule brain cells is this possibly due to no return statement, if so added one where I believed it would fit, still no luck

Still nothing,

Can anyone help a beginner out possibly showing and example or show me with my code what I'm missing as well as an explanation why

Many thanks!

More code:

Are you over 18 years old?

<button onclick="off(), ageinyear()">Submit</button>

<form>

        Name
        <input id="name" name="lblname" type="text" />

        Age
        <input id="year" name="lblyear" type="text" />

</form>

Body:
Consider the sequence of events you're defining here:

<script>
var age;
function ageinyear() {
    age = document.getElementById("year").value;
}
</script>

<script>document.write(age)</script>

Defining a function doesn't invoke a function.  So essentially the above is the same as this:

<script>
var age;
</script>

<script>document.write(age)</script>

No value is being written to the page because there's no value in that variable.  It's declared, but it's undefined.

Instead of trying to output to the page immediately (as in, before the user has set the value), output to the page in the function that gets invoked by the user setting the value.  Something like this:

<script>
var age;
function ageinyear() {
    age = document.getElementById("year").value;
    document.getElementById("yearOutput").textContent = age;
}
</script>

<span id="yearOutput"></span>


问:
Is it better to use the column name or column index on .Net DataSets?
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

```<code>int price = (int)dr["Price"];
</code>```

While column index is just faster (I think):

```<code>int price = (int)dr[3];
</code>```

Would using column names break if you decide to obfuscate the database?

答:
Use column names for DataRow by the same token that an RDBMS won't gain speed by requiring programmers to specify the column index in SQL.  But you can perhaps mimic the way an RDBMS operate when you issue a SELECT statement, inside an RDBMS engine it query the column index/offset of columns specified in SELECT clause before it traverse the rows, so it can operate faster.

If you really want to gain speed, don't do it the const/enum way (column order might change on your database or ORM layer).  Do it as TcKs suggested(before the actual loop):

```<code>int ndxMyColumn = table.Columns.IndexOf( "MyColumn" );
foreach(DataRow record in table.Rows ) {
    record[ndxMyColumn] = 15;
}
</code>```

OwnerDisplayName: tpower

Body:
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

int price = (int)dr["Price"];

While column index is just faster (I think):

int price = (int)dr[3];

Would using column names break if you decide to obfuscate the database?

LastEditorDisplayName: tpower

Body:
Use column names for DataRow by the same token that an RDBMS won't gain speed by requiring programmers to specify the column index in SQL.  But you can perhaps mimic the way an RDBMS operate when you issue a SELECT statement, inside an RDBMS engine it query the column index/offset of columns specified in SELECT clause before it traverse the rows, so it can operate faster.

If you really want to gain speed, don't do it the const/enum way (column order might change on your database or ORM layer).  Do it as TcKs suggested(before the actual loop):

int ndxMyColumn = table.Columns.IndexOf( "MyColumn" );
foreach(DataRow record in table.Rows ) {
    record[ndxMyColumn] = 15;
}

OwnerDisplayName: Michael Buen


问:
Custom ASP.NET MVC2 HtmlHelper: How to get the instance of the object passed to it?
I am working on a ASP.NET MVC2 website. For learning. I am working with the Visual Basic language.

In a view I would like to do this:

```<code> <%: Html.EditorForEnumeracion(Function(v) v.combustible%>
</code>```

So, I created an HtmlHelper extension method:

```<code>Imports System.Runtime.CompilerServices
Imports System.Linq.Expressions
Imports System.Reflection

Public Module HtmlHelpers
    <Extension()> _
    Public Function EditorForEnumeracion(Of TModel, TValue)(ByVal html As HtmlHelper(Of TModel), ByVal expression As Expression(Of Func(Of TModel, TValue))) As MvcHtmlString
        'My stuff goes here
     End Function
End Module
</code>```

The problem is that I do not know how to get the instance of the v.combustible object that I pass to the helper. I do not care about the v object. I need to work with the combustible attribute of the v object.

Here and here seems to be how to do this, but I do not understand. Also, I work with Visual Basic, not C#.

I think that I can get the instance of the Enumeracion object through the expression parameter, but I do not understand how.

More info now.

This is my "Vehiculo" class:

```<code>Namespace Models.Automovil
    Public Class Vehiculo
        Public Property tipo As New Models.Enumeracion("TipoDeVehiculo")
        Public Property marca As String
        Public Property modelo As String
        Public Property numeroDePuertas As Integer
        Public Property combustible As New Models.Enumeracion("TipoDeCombustible")
        Public Property potencia As Integer
        Public Property fechaPrimeraMatriculacion As DateTime
        Public Property version As String
        Public Property precio As Decimal
        Public Property descripcion As String
    End Class
End Namespace
</code>```

And this is my "Enumeracion" class:

```<code>Namespace Models
    Public Class Enumeracion
        Private bd As New tarificadorasegasaEntities
        Private diccionario As New Dictionary(Of String, Integer)
        Private _nombre As String
        Private _clave As String
        Private _valor As Integer
        Public ReadOnly Property nombre As String
            Get
                Return _nombre
            End Get
        End Property
        Public ReadOnly Property clave As String
            Get
                Return _clave
            End Get
        End Property
        Public ReadOnly Property valor As Integer
            Get
                Return _valor
            End Get
        End Property

        'More stuff here. Methods.

    End Class
End Namespace
</code>```

The model is the Vehiculo class.

Still not resolving this.

Thanks in advance.

答:
Try like this:</p>

```<code><Extension()> _
Public Function EditorForMyCustomClassB(Of Vehiculo, Enumeracion)(ByVal html As HtmlHelper(Of TModel), ByVal expression As Expression(Of Func(Of Vehiculo, Enumeracion))) As MvcHtmlString
    Dim res = ModelMetadata.FromLambdaExpression(expression, html.ViewData)
    Dim e As Enumeracion = DirectCast(res.Model, Enumeracion)
    ' use e here
 End Function
</code>```

Body:
I am working on a ASP.NET MVC2 website. For learning. I am working with the Visual Basic language.

In a view I would like to do this:

 <%: Html.EditorForEnumeracion(Function(v) v.combustible%>

So, I created an HtmlHelper extension method:

Imports System.Runtime.CompilerServices
Imports System.Linq.Expressions
Imports System.Reflection

Public Module HtmlHelpers
    <Extension()> _
    Public Function EditorForEnumeracion(Of TModel, TValue)(ByVal html As HtmlHelper(Of TModel), ByVal expression As Expression(Of Func(Of TModel, TValue))) As MvcHtmlString
        'My stuff goes here
     End Function
End Module

The problem is that I do not know how to get the instance of the v.combustible object that I pass to the helper. I do not care about the v object. I need to work with the combustible attribute of the v object.

Here and here seems to be how to do this, but I do not understand. Also, I work with Visual Basic, not C#.

I think that I can get the instance of the Enumeracion object through the expression parameter, but I do not understand how.

More info now.

This is my "Vehiculo" class:

Namespace Models.Automovil
    Public Class Vehiculo
        Public Property tipo As New Models.Enumeracion("TipoDeVehiculo")
        Public Property marca As String
        Public Property modelo As String
        Public Property numeroDePuertas As Integer
        Public Property combustible As New Models.Enumeracion("TipoDeCombustible")
        Public Property potencia As Integer
        Public Property fechaPrimeraMatriculacion As DateTime
        Public Property version As String
        Public Property precio As Decimal
        Public Property descripcion As String
    End Class
End Namespace

And this is my "Enumeracion" class:

Namespace Models
    Public Class Enumeracion
        Private bd As New tarificadorasegasaEntities
        Private diccionario As New Dictionary(Of String, Integer)
        Private _nombre As String
        Private _clave As String
        Private _valor As Integer
        Public ReadOnly Property nombre As String
            Get
                Return _nombre
            End Get
        End Property
        Public ReadOnly Property clave As String
            Get
                Return _clave
            End Get
        End Property
        Public ReadOnly Property valor As Integer
            Get
                Return _valor
            End Get
        End Property

        'More stuff here. Methods.

    End Class
End Namespace

The model is the Vehiculo class.

Still not resolving this.

Thanks in advance.

Body:
Try like this:

<Extension()> _
Public Function EditorForMyCustomClassB(Of Vehiculo, Enumeracion)(ByVal html As HtmlHelper(Of TModel), ByVal expression As Expression(Of Func(Of Vehiculo, Enumeracion))) As MvcHtmlString
    Dim res = ModelMetadata.FromLambdaExpression(expression, html.ViewData)
    Dim e As Enumeracion = DirectCast(res.Model, Enumeracion)
    ' use e here
 End Function


问:
Dividing the page into columns using inline block not working
I want a solution by using inline-block not by using float:left.

    *{
     margin:0;
  padding:0;
 }
 body{
     margin:0;
  padding:0;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div style="width: 50%;background-color: #4caf50;display: inline-block;">
     Section 1
    </div>

 <div style="width: 50%;background-color: #ff5722;display: inline-block;">
     Section 2
    </div></code>```

Is there a solution ?

答:
you can try to use a container and display: flex like in the following example:

.container {display: flex}
.one {background-color: red; width: 50%}
.two {background-color: blue; width: 50%}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="one">div one</div>
   <div class="two">div one</div>
</div></code>```

Body:
I want a solution by using inline-block not by using float:left.

    *{
     margin:0;
  padding:0;
 }
 body{
     margin:0;
  padding:0;
 }

     Section 1

     Section 2

Is there a solution ?

Body:
you can try to use a container and display: flex like in the following example:

.container {display: flex}
.one {background-color: red; width: 50%}
.two {background-color: blue; width: 50%}

<div class="container">
  <div class="one">div one</div>
   <div class="two">div one</div>
</div>


答: Eliminating the the label could be done via adding + opts(legend.position = "none") option also.

Title: Why does the ggplot legend show the "colour" parameter?

Body:
I have the following example:

data <- structure(list(a = c(-1.25549186262767, -0.840855480786298, -
0.635371312524283,
-0.602907981454667, -0.472166385166945, -0.285773634866154, 0.0701427664273268,
0.138108224803923, 1.38435934347858, 1.71144087270237), b = c(-3.44400412039417,
0.675644682353751, -1.04793816522475, -7.38303347186651, 2.34519166466874,
0.334780748573386, 4.76806919070976, 4.8633533150074, 3.50106026731172,
-1.27172351054143), c = c(-3.02376206439776, -2.56390769080574,
-1.48659913867609, -1.27976202274701, -0.368725655874139, 1.08537150160227,
3.98619381956471, 4.50687017428731, 4.10341582203292, -1.61769414438858
), d = c(5.71851494232005, 2.90539833491649, 2.75195159216204,
2.73478241733301, 2.65941820902101, 2.60630235726839, 3.34836154776286,
3.62938300664006, 4.61153521538016, 5.56230567213863), e = c(8.98703236551896,
4.5660296657415, 4.32487774825464, 4.29789523068949, 4.17945528847841,
4.09598014088541, 5.26217626511884, 5.70382046327322, 7.24733897758039,
8.74153894964533)), .Names = c("a", "b", "c", "d", "e"), row.names = c(NA,
-10L), class = "data.frame")

ggplot(data, aes(x=a, y=b)) + geom_point() +
    geom_line(aes(x=a, y=c)) +
    geom_line(aes(x=a, y=(c - d), colour="red")) +
    geom_line(aes(x=a, y=(c + d), colour="red")) +
    geom_line(aes(x=a, y=(c - e), colour="blue")) +
    geom_line(aes(x=a, y=(c + e), colour="blue"))

I want the labels to be "d" and "e", but they are instead being given the value of the "colour" field.  Two questions:

1) How can I eliminate the legend entirely?
2) If I want to include the legend, how can I have it set to specific values rather than the colour?


问:
How do I integrate MSYS2 shell into Visual studio code on Window?
I tried to integrate MSYS2 shell into Visual studio Code integrated terminal. Here's my user settings:

```<code>{
    "terminal.integrated.shell.windows": "C:\\msys64\\usr\\bin\\bash.exe",
    "terminal.integrated.shellArgs.windows": ["--login", "-i"]
}
</code>```

However, I ran into a problem where --login changes the current working directory to Windows home. I want the current directory to be at the root of my workspace.

My further attempt was I tried add a flag -c 'cd ${workspaceRoot}'. However, the bash would crashed on start. I could properly get to current directory by removing --login, but without login mode, all other shell command (ls, cd, etc) are not available.

How do I properly integrate MSYS2 shell into my vscode?

答:
```<code>{
    "terminal.integrated.shell.windows": "C:\\msys64\\usr\\bin\\sh.exe",
    "terminal.integrated.shellArgs.windows": ["--login", "-i"]
}
</code>```

Worked for me.

Body:
I tried to integrate MSYS2 shell into Visual studio Code integrated terminal. Here's my user settings:

{
    "terminal.integrated.shell.windows": "C:\\msys64\\usr\\bin\\bash.exe",
    "terminal.integrated.shellArgs.windows": ["--login", "-i"]
}

However, I ran into a problem where --login changes the current working directory to Windows home. I want the current directory to be at the root of my workspace.

My further attempt was I tried add a flag -c 'cd ${workspaceRoot}'. However, the bash would crashed on start. I could properly get to current directory by removing --login, but without login mode, all other shell command (ls, cd, etc) are not available.

How do I properly integrate MSYS2 shell into my vscode?

Body:
{
    "terminal.integrated.shell.windows": "C:\\msys64\\usr\\bin\\sh.exe",
    "terminal.integrated.shellArgs.windows": ["--login", "-i"]
}

Worked for me.


问:
Is it possible to use DMEE tree for import and parsing xml file
I need to develop import of xml files with quite complicated structure into SAP.
Earlier I used DMEE format trees for export xml and it was quite easy and flexibly. And since this is called "Data Medium Exchange Engine", so I thought that this could be used in both directions, that is, for import too. But I can't find any docs or examples of how to do it.

I've read the topic
Parsing XML within SAP ABAP
but before I follow it I just want to be sure that DMEE is really useless for import.

答:
You can use the iXML library to import and parse your xml file.

As mentioned in the help page:

When XML data is saved in strings or internal tables, it is best to
  use byte strings or byte-like row types and the UTF-8 code page for
  the representation.

Therefore, if manipulating byte strings, you can use the CALL TRANSFORMATION statement to convert your XML to ABAP:

```<code>call transformation id
  source xml i_xml_string
  result ...
</code>```

The CALL TRANSFORMATION help page has a lot of examples. You can also find more info on the following SAP help portal.

DMEE does have an upload XML function. It uses the iXML library - see include LDMEE1_ABAF50

Body:
You can use the iXML library to import and parse your xml file.

As mentioned in the help page:

When XML data is saved in strings or internal tables, it is best to
  use byte strings or byte-like row types and the UTF-8 code page for
  the representation.

Therefore, if manipulating byte strings, you can use the CALL TRANSFORMATION statement to convert your XML to ABAP:

call transformation id
  source xml i_xml_string
  result ...

The CALL TRANSFORMATION help page has a lot of examples. You can also find more info on the following SAP help portal.

DMEE does have an upload XML function. It uses the iXML library - see include LDMEE1_ABAF50