问:
Dispatch Redux action in React
I'm trying to fetch test API using FetchAPI and Redux.

The problem is with dispatch redux action.

Here's my code:

```<code>ProductList.js
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as productActions from '../actions/product';
import RaisedButton from 'material-ui/RaisedButton';

function fetchProductsWithRedux() {
    console.log("fetchProductsWithRedux-1");
    return (dispatch) => {
        console.log("fetchProductsWithRedux-2");
        dispatch(this.props.action.fetchProdutcsRequest());
        return fetchProdutcs().then(([response, json]) => {
            if (response.status === 200) {
                console.log("success");
                dispatch(this.props.action.fetchProductsSucesss(json))
            }
            else {
                console.log("error");
                dispatch(this.props.action.fetchProductsError())
            }
        })
    }
}

function fetchProdutcs() {
    const URL = "https://jsonplaceholder.typicode.com/posts";
    return fetch(URL, { method: 'GET' })
        .then(response => Promise.all([response, response.json()]));
}

class ProductList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            productList: [
                'product 1',
                'product 2',
                'product 3'
            ]
        }
    }
    componentDidMount() {
        fetchProductsWithRedux();
    }
    render() {
        return (
            <div className="ProductList">
                <h2>Products</h2>
                <ul>
                    {
                        this.props.posts &&
                        this.props.posts.map((post) => {
                            return (
                                <li>{post.title}</li>
                            )
                        })
                    }
                </ul>

                <ol>
                    <RaisedButton label="Get Products Action" onClick={this.props.action.getProducts} />
                </ol>
            </div>
        );
    }
}

function mapStateToProps(state, props) {
    return {
        product: state.product,
        posts: state.posts
    };
}
function mapDispatchToProps(dispatch) {
    return {
        action: bindActionCreators(productActions, dispatch)
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(ProductList);
</code>```

product.js (actions)

```<code>export function fetchProductsRequest() {
  console.log('fetchProductsRequest');
  return {
    type: 'FETCH_PRODUCTS_REQUEST'
  }
}

export function fetchProductsSuccess(payload) {
  console.log('fetchProductsSuccess');
  return {
    type: 'FETCH_PRODUCTS_SUCCESS'
  }
}

export function fetchProductsError() {
  console.log('fetchProductsError');
  return {
    type: 'FETCH_PRODUCTS_ERROR'
  }
}
</code>```

product.js (reducer)

```<code>export default(state = [], payload) => {
    switch (payload.type) {
        case 'FETCH_PRODUCTS_REQUEST':
            console.log('FETCH_PRODUCTS_REQUEST action');
            return state;
        case 'FETCH_PRODUCTS_SUCCESS':
            console.log('FETCH_PRODUCTS_SUCCES action');
            return {...state, posts: payload.payload}
        default:
            return state;
    }
};
</code>```

store.js

```<code>import { createStore } from 'redux';
import rootReducer from './reducers';

export default(initialState) => {
    return createStore(rootReducer, initialState);
}

Product.js (pages, component)
import React, { Component } from 'react';
import ProductList from '../../components/ProductList';
import RaisedButton from 'material-ui/RaisedButton';
//import './Product.css';

class Product extends Component {
    render() {
        return (
            <div className="Product">
                <h1>ProductList Page</h1>
                <RaisedButton label="Default" />
                <ProductList />
            </div>
        );
    }
}
export default Product;
</code>```

The line console.log("fetchProductsWithRedux-2"); in ProductList.js has never been reached.

What's wrong? Any ideas? Thanks in advance.

答:
There are a few issues with your code.

Firstly, fetchProductsWithRedux is an action, so you would need to dispatch it rather than calling it directly. As Bjoern mentioned, the way you are calling it, the function call just returns a function, which is never called.

Now, you cannot dispatch it in the current scenario, as it returns a function, rather than object. To fix that, you will have to use redux-thunk, which will allow it to dispatch a function.

You can add it to mapDispatchToProps, as you did for getProducts, but there is a shorthand for that. In your mapDispatchToProps, you can do the following:-

```<code> const mapDispatchToProps = { fetchProductsWithRedux, getProducts }
</code>```

You will notice that it is just returning an object with 2 functions.

From the documentation:

If an object is passed, each function inside it is assumed to be a Redux action creator. An object with the same function names, but with every action creator wrapped into a dispatch call so they may be invoked directly, will be merged into the component’s props.

So, it will do exactly what you did earlier with bindActionCreators, but it looks more elegant. Now, instead of onClick={this.props.action.getProducts}, you can do onClick={this.props.getProducts}. Notice the missing action.

Also, your import will change to

```<code>import { getProducts } from '../actions/product';
</code>```

Now, to fix your issue, in componentDidMount, rather than calling the function directly, you will have to do:-

```<code>componentDidMount() {
   this.props.fetchProductsWithRedux();
}
</code>```

Hopefully, this will help.

Title: Dispatch Redux action in React

Body:
I'm trying to fetch test API using FetchAPI and Redux.

The problem is with dispatch redux action.

Here's my code:

ProductList.js
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as productActions from '../actions/product';
import RaisedButton from 'material-ui/RaisedButton';

function fetchProductsWithRedux() {
    console.log("fetchProductsWithRedux-1");
    return (dispatch) => {
        console.log("fetchProductsWithRedux-2");
        dispatch(this.props.action.fetchProdutcsRequest());
        return fetchProdutcs().then(([response, json]) => {
            if (response.status === 200) {
                console.log("success");
                dispatch(this.props.action.fetchProductsSucesss(json))
            }
            else {
                console.log("error");
                dispatch(this.props.action.fetchProductsError())
            }
        })
    }
}

function fetchProdutcs() {
    const URL = "https://jsonplaceholder.typicode.com/posts";
    return fetch(URL, { method: 'GET' })
        .then(response => Promise.all([response, response.json()]));
}

class ProductList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            productList: [
                'product 1',
                'product 2',
                'product 3'
            ]
        }
    }
    componentDidMount() {
        fetchProductsWithRedux();
    }
    render() {
        return (

Products

                    {
                        this.props.posts &&
                        this.props.posts.map((post) => {
                            return (

{post.title}

                            )
                        })
                    }

                    <RaisedButton label="Get Products Action" onClick={this.props.action.getProducts} />

        );
    }
}

function mapStateToProps(state, props) {
    return {
        product: state.product,
        posts: state.posts
    };
}
function mapDispatchToProps(dispatch) {
    return {
        action: bindActionCreators(productActions, dispatch)
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(ProductList);

product.js (actions)

export function fetchProductsRequest() {
  console.log('fetchProductsRequest');
  return {
    type: 'FETCH_PRODUCTS_REQUEST'
  }
}

export function fetchProductsSuccess(payload) {
  console.log('fetchProductsSuccess');
  return {
    type: 'FETCH_PRODUCTS_SUCCESS'
  }
}

export function fetchProductsError() {
  console.log('fetchProductsError');
  return {
    type: 'FETCH_PRODUCTS_ERROR'
  }
}

product.js (reducer)

export default(state = [], payload) => {
    switch (payload.type) {
        case 'FETCH_PRODUCTS_REQUEST':
            console.log('FETCH_PRODUCTS_REQUEST action');
            return state;
        case 'FETCH_PRODUCTS_SUCCESS':
            console.log('FETCH_PRODUCTS_SUCCES action');
            return {...state, posts: payload.payload}
        default:
            return state;
    }
};

store.js

import { createStore } from 'redux';
import rootReducer from './reducers';

export default(initialState) => {
    return createStore(rootReducer, initialState);
}

Product.js (pages, component)
import React, { Component } from 'react';
import ProductList from '../../components/ProductList';
import RaisedButton from 'material-ui/RaisedButton';
//import './Product.css';

class Product extends Component {
    render() {
        return (

ProductList Page

                <RaisedButton label="Default" />
                <ProductList />

        );
    }
}
export default Product;

The line console.log("fetchProductsWithRedux-2"); in ProductList.js has never been reached.

What's wrong? Any ideas? Thanks in advance.

Body:
There are a few issues with your code.

Firstly, fetchProductsWithRedux is an action, so you would need to dispatch it rather than calling it directly. As Bjoern mentioned, the way you are calling it, the function call just returns a function, which is never called.

Now, you cannot dispatch it in the current scenario, as it returns a function, rather than object. To fix that, you will have to use redux-thunk, which will allow it to dispatch a function.

You can add it to mapDispatchToProps, as you did for getProducts, but there is a shorthand for that. In your mapDispatchToProps, you can do the following:-

 const mapDispatchToProps = { fetchProductsWithRedux, getProducts }

You will notice that it is just returning an object with 2 functions.

From the documentation:

If an object is passed, each function inside it is assumed to be a Redux action creator. An object with the same function names, but with every action creator wrapped into a dispatch call so they may be invoked directly, will be merged into the component’s props.

So, it will do exactly what you did earlier with bindActionCreators, but it looks more elegant. Now, instead of onClick={this.props.action.getProducts}, you can do onClick={this.props.getProducts}. Notice the missing action.

Also, your import will change to

import { getProducts } from '../actions/product';

Now, to fix your issue, in componentDidMount, rather than calling the function directly, you will have to do:-

componentDidMount() {
   this.props.fetchProductsWithRedux();
}

Hopefully, this will help.


来源: stackexchange

问:
Unable to click the element. Error: no such element: Unable to locate element:
I am practicing on flipkart.com. i am unable to click the product after the search result. The xpath is correct. I tried using scroll function,visible, find by partial linktext, wait, sleep still i am unable to do. Please find the below code.</p>

```<code>package Flipkart;

import org.openqa.selenium.By; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class TC2
{
    public static void main(String[] args) throws InterruptedException
    {
        System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.flipkart.com/");
        driver.findElement(By.name("q")).sendKeys("Bag");
        driver.findElement(By.xpath("html/body/div[1]/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[2]/button")).click();
        driver.findElement(By.xpath(".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]")).click();
    }
}

  Error:
    Starting ChromeDriver 2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed) on port 17575
    Only local connections are allowed.
    Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]"}
      (Session info: chrome=58.0.3029.81)
      (Driver info: chromedriver=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 76 milliseconds
    For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
    Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
    System info: host: 'D90T0CQ1', ip: '192.168.162.83', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_102'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed), userDataDir=C:\Users\SALUNK~1\AppData\Local\Temp\scoped_dir12552_16506}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=58.0.3029.81, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
    Session ID: a8c3432c9b1e8cce3365db9407fc310f
    *** Element info: {Using=xpath, value=.//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
        at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500)
        at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
        at Flipkart.TC2.main(TC2.java:15)
</code>```

答:
I got the same exception and added implicitly wait. It is working fine now. The code</p>

```<code>System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir") + "\\lib\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    driver.get("https://www.flipkart.com/");
    driver.findElement(By.name("q")).sendKeys("Bag");
    driver.findElement(By.xpath("html/body/div[1]/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[2]/button")).click();
    driver.findElement(By.xpath("//*[@class='_2cLu-l']")).click();`
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am practicing on flipkart.com. i am unable to click the product after the search result. The xpath is correct. I tried using scroll function,visible, find by partial linktext, wait, sleep still i am unable to do. Please find the below code.

package Flipkart;

import org.openqa.selenium.By; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class TC2
{
    public static void main(String[] args) throws InterruptedException
    {
        System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.flipkart.com/");
        driver.findElement(By.name("q")).sendKeys("Bag");
        driver.findElement(By.xpath("html/body/div[1]/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[2]/button")).click();
        driver.findElement(By.xpath(".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]")).click();
    }
}

  Error:
    Starting ChromeDriver 2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed) on port 17575
    Only local connections are allowed.
    Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]"}
      (Session info: chrome=58.0.3029.81)
      (Driver info: chromedriver=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 76 milliseconds
    For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
    Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
    System info: host: 'D90T0CQ1', ip: '192.168.162.83', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_102'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed), userDataDir=C:\Users\SALUNK~1\AppData\Local\Temp\scoped_dir12552_16506}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=58.0.3029.81, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
    Session ID: a8c3432c9b1e8cce3365db9407fc310f
    *** Element info: {Using=xpath, value=.//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
        at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500)
        at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
        at Flipkart.TC2.main(TC2.java:15)

Body:
I got the same exception and added implicitly wait. It is working fine now. The code

System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir") + "\\lib\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    driver.get("https://www.flipkart.com/");
    driver.findElement(By.name("q")).sendKeys("Bag");
    driver.findElement(By.xpath("html/body/div[1]/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[2]/button")).click();
    driver.findElement(By.xpath("//*[@class='_2cLu-l']")).click();`


问:
How to check different conditions into if statement based on different scenario
I want to check different conditions into if statement based on different scenario (Will get the $status value as 'Y' or 'N'). Please check the code below and let me know the issue here.

```<code>$fstrto = "10";
$cstrto = "7";
if($status == 'N')
{
    $cond = "$fstrto <= $cstrto";
}
else
{
    $cond = "$fstrto >= $cstrto";
}
if($cond)
{
    echo "Success";
}
</code>```

This code is not working as it takes the "$fstrto <= $cstrto" as variable.

答:
```<code>$fstrto = "10";
$cstrto = "7";
$cond = false;
if($status == 'N')
{
    if($fstrto <= $cstrto){
        $cond = true;
    }

}
else
{
    if($fstrto >= $cstrto){
        $cond = false;
    }
}
if($cond)
{
echo "Success";
}
</code>```

Body:
I want to check different conditions into if statement based on different scenario (Will get the $status value as 'Y' or 'N'). Please check the code below and let me know the issue here.

$fstrto = "10";
$cstrto = "7";
if($status == 'N')
{
    $cond = "$fstrto <= $cstrto";
}
else
{
    $cond = "$fstrto >= $cstrto";
}
if($cond)
{
    echo "Success";
}

This code is not working as it takes the "$fstrto <= $cstrto" as variable.


问:
What's the point of throwing an exception?
I'm writing a login class in c#, and I'm trying to be diligent about throwing exceptions for null passwords, insufficiant password characters, etc. The thing that suddenly occured to me was - What do I do with these exception? What/who are they for? Whether I handle the exception or not, the app will still fail at that point. Is the exception for other developers, the customer!? </p>

答: If your function will throw an exception if it can't log in, then code which calls your function can assume that if your function returns, it's logged in.  This will ease the amount of work the code has to do to handle the "login succeeded" scenario, in exchange for requiring more work in the "login failed" scenario.  If code will sometimes be used in cases where failure is semi-expected (e.g. try logging in with one set of credentials; if that doesn't work, try some other set) and sometimes used when failure would be unexpected and unrecoverable, it may be helpful to either have a "throw on error" boolean flag, or else have separate "Login" and "TryLogin" methods.</p>

ContentLicense: CC BY-SA 2.5


问:
How to replace accented characters?
My output looks like 'àéêöhello!'. I need change my output like this  'aeeohello', Just replacing the character à as a like this.

答:
Please Use the below code:</p>
```<code>import unicodedata

def strip_accents(text):
    try:
        text = unicode(text, 'utf-8')
    except NameError: # unicode is a default on python 3
        pass

    text = unicodedata.normalize('NFD', text)\
           .encode('ascii', 'ignore')\
           .decode("utf-8")

    return str(text)

s = strip_accents('àéêöhello')

print s
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to replace accented characters?

Body:
Please Use the below code:

import unicodedata

def strip_accents(text):
    try:
        text = unicode(text, 'utf-8')
    except NameError: # unicode is a default on python 3
        pass

    text = unicodedata.normalize('NFD', text)\
           .encode('ascii', 'ignore')\
           .decode("utf-8")

    return str(text)

s = strip_accents('àéêöhello')

print s


问:
How to Update a column in all rows of a table based on a function call with existing value in that same column
I have a column in my user_table called password.
Now I want to update all password fields in all rows by passing the existing value of password field and update it using the return value from the function. How to achieve it?

```<code>╔════╦══════════════╦══════╗
║ id ║  username    ║ pwd  ║
╠════╬══════════════╬══════╣
║  1 ║ Jeff Atwood  ║ 5636 ║
║  2 ║ Geoff Dalgas ║  148 ║
║  3 ║ Jarrod Dixon ║  101 ║
║  4 ║ Joel Spolsky ║  959 ║
╚════╩══════════════╩══════╝
</code>```

my function is as follows:

```<code>function encryptPassword(password)
{
// $new password = my encryption logic here
   return $password;
}
</code>```

How can I update all password cloumn in every row one by one?

答:
You can use a query like:

```<code>" UPDATE `your_table` SET `pwd` = '$NEW_PASSWORD'
    WHERE `pwd` =
        (SELECT `pwd` FROM `table` WHERE `pwd`= '$OLD_PASSWORD')
";
</code>```

that's if you want to use a sql query

if you want php

$Query = "SELECT * FROM your_table";

assuming you already have a sql db connection ready, and assuming you get the data through get command

```<code>$Results = $DB->query($Query)->get();

// Loop through rows
foreach ($results as $result){
     $ID = $result->id;
     $NEW_PWD = ''; // your pwd logic here
     $DB->query("UPDATE `your_table` SET `pwd` = '$NEW_PWD' WHERE `id` = '$ID'")->execute();
}
</code>```

again i am assuming that you already have your db connection ready using mysql_connect or PDO

the logic behind it is simple.

Body:
I have a column in my user_table called password.
Now I want to update all password fields in all rows by passing the existing value of password field and update it using the return value from the function. How to achieve it?

╔════╦══════════════╦══════╗
║ id ║  username    ║ pwd  ║
╠════╬══════════════╬══════╣
║  1 ║ Jeff Atwood  ║ 5636 ║
║  2 ║ Geoff Dalgas ║  148 ║
║  3 ║ Jarrod Dixon ║  101 ║
║  4 ║ Joel Spolsky ║  959 ║
╚════╩══════════════╩══════╝

my function is as follows:

function encryptPassword(password)
{
// $new password = my encryption logic here
   return $password;
}

How can I update all password cloumn in every row one by one?

Body:
You can use a query like:

" UPDATE `your_table` SET `pwd` = '$NEW_PASSWORD'
    WHERE `pwd` =
        (SELECT `pwd` FROM `table` WHERE `pwd`= '$OLD_PASSWORD')
";

that's if you want to use a sql query

if you want php

$Query = "SELECT * FROM your_table";

assuming you already have a sql db connection ready, and assuming you get the data through get command

$Results = $DB->query($Query)->get();

// Loop through rows
foreach ($results as $result){
     $ID = $result->id;
     $NEW_PWD = ''; // your pwd logic here
     $DB->query("UPDATE `your_table` SET `pwd` = '$NEW_PWD' WHERE `id` = '$ID'")->execute();
}

again i am assuming that you already have your db connection ready using mysql_connect or PDO

the logic behind it is simple.


问:
How to know everytime how to define my variables/placeholders shape in Tensorflow
I am trying to learn tensorflow, I already did some exercises with simple perceptron with datas like, one features, one output.

I'm now trying with more features but, I have a problem with my variable/placeholder shape.
I thought I learned how it works, but it seems that I was wrong.
I would like to know how to get the good values in general so I won't get this kind of problem anymore.

Here's my code :

[in]:

```<code>print(inputX.shape)
print(inputY.shape)
</code>```

[out]:

(50, 9)
(50, 1)

[in]:

```<code>x = tf.placeholder(tf.float32,[None, 9]) #features
y = tf.placeholder(tf.float32, [None, 1]) #labels
W = tf.Variable(tf.random_normal([1, 9])) #Weights, nb of labels[x,x]nb of features
b = tf.Variable(tf.zeros([1])) #[x]nb of features
Y = tf.nn.relu(tf.add(tf.matmul(x, W),b))
</code>```

[out]:

Dimensions must be equal, but are 9 and 1 for 'MatMul_21' (op: 'MatMul') with input shapes: [?,9], [1,9].

I gess the problem is the 1 but I don't get where it come from.

Thanks for your help !

答:
The problem here, as I see that, you are trying to do a wrong Matrix Multiplication. The basic rules of which can be seen here

If you change your last line to

```<code>Y = tf.nn.relu(tf.add(tf.matmul(tf.transpose(x), W),b))
</code>```

Then it wont give you the error related to dimension anymore.

Body:
I am trying to learn tensorflow, I already did some exercises with simple perceptron with datas like, one features, one output.

I'm now trying with more features but, I have a problem with my variable/placeholder shape.
I thought I learned how it works, but it seems that I was wrong.
I would like to know how to get the good values in general so I won't get this kind of problem anymore.

Here's my code :

[in]:

print(inputX.shape)
print(inputY.shape)

[out]:

(50, 9)
(50, 1)

[in]:

x = tf.placeholder(tf.float32,[None, 9]) #features
y = tf.placeholder(tf.float32, [None, 1]) #labels
W = tf.Variable(tf.random_normal([1, 9])) #Weights, nb of labels[x,x]nb of features
b = tf.Variable(tf.zeros([1])) #[x]nb of features
Y = tf.nn.relu(tf.add(tf.matmul(x, W),b))

[out]:

Dimensions must be equal, but are 9 and 1 for 'MatMul_21' (op: 'MatMul') with input shapes: [?,9], [1,9].

I gess the problem is the 1 but I don't get where it come from.

Thanks for your help !

Body:
The problem here, as I see that, you are trying to do a wrong Matrix Multiplication. The basic rules of which can be seen here

If you change your last line to

Y = tf.nn.relu(tf.add(tf.matmul(tf.transpose(x), W),b))

Then it wont give you the error related to dimension anymore.


问:
calculating the difference in months between two dates
In C#/.NET TimeSpan has TotalDays, TotalMinutes, etc. but I can't figure out a formula for total months difference. Variable days per month and leap years keep throwing me off. How can I get TotalMonths?

Edit Sorry for not being more clear: I know I can't actually get this from TimeSpan but I thought using TotalDays and TotalMinutes would be a good example to express what I was looking for ... except I'm trying to get Total Months.

Example: Dec 25, 2009 - Oct 6, 2009 = 2 TotalMonths. Oct 6th to Nov 5th equals 0 months. On Nov 6th, 1 month. On Dec 6th, 2 months

答:
Way late to the game but I imagine this may be helpful to someone. The majority of people tend to measure month to month by date excluding the fact that months come in different variations. Using that frame of thought I created a one liner which compares the dates for us. Using the the following process.

Any # of years over 1 when comparing year will be multiplied by 12, there is no case where this can be equal to less than 1 full year.

If the end year is greater we need to evaluate if the current day is greater or equal to the previous day
2A. If the end day is greater or equal we take the current month and then add 12 months subtract the month of the start month
2B. If the end day is less than the start day we perform the the same as above except we add 1 to the start month before subtracting

If the end year is not greater we perform the same as 2A/2B, but without adding the 12 months because we do not need to evaluate around the year.

```<code>    DateTime date = new DateTime(2003, 11, 25);
    DateTime today = new DateTime(2004, 12, 26);
    var time = (today.Year - date.Year > 1 ? (today.Year - date.Year - 1) * 12 : 0) +  (today.Year > date.Year ? (today.Day >= date.Day ? today.Month + 12 - date.Month : today.Month + 12 - (date.Month + 1)) : (today.Day >= date.Day ? today.Month - date.Month : today.Month - (date.Month + 1)));
</code>```

Body:
Way late to the game but I imagine this may be helpful to someone. The majority of people tend to measure month to month by date excluding the fact that months come in different variations. Using that frame of thought I created a one liner which compares the dates for us. Using the the following process.

Any # of years over 1 when comparing year will be multiplied by 12, there is no case where this can be equal to less than 1 full year.

If the end year is greater we need to evaluate if the current day is greater or equal to the previous day
2A. If the end day is greater or equal we take the current month and then add 12 months subtract the month of the start month
2B. If the end day is less than the start day we perform the the same as above except we add 1 to the start month before subtracting

If the end year is not greater we perform the same as 2A/2B, but without adding the 12 months because we do not need to evaluate around the year.

    DateTime date = new DateTime(2003, 11, 25);
    DateTime today = new DateTime(2004, 12, 26);
    var time = (today.Year - date.Year > 1 ? (today.Year - date.Year - 1) * 12 : 0) +  (today.Year > date.Year ? (today.Day >= date.Day ? today.Month + 12 - date.Month : today.Month + 12 - (date.Month + 1)) : (today.Day >= date.Day ? today.Month - date.Month : today.Month - (date.Month + 1)));


问:
find -exec cant find local function "find: Log: No such file or directory"
i have a piece of code that should print all files in specific dir. i use find exec for this:

```<code>find ${_di} -type f -print -exec Log "$(stat -c%y {}) - {}" \;
</code>```

Where log is function of mine defines in same file.
But id does not work and i get error message:

"find: Log: No such file or directory".

Why? What is wrong in this piece of code?

答:
Function can't be used in -exec however bash -c can be used as command.
Slightly modified to using + as -exec command terminator and {} last to allow to reduce the number of bash processes spawned.

```<code>find ${_di} -type f -print -exec bash -c "$(typeset -f Log)"$'\n''for arg; do Log "$(stat -c%y "$arg") - $arg"; done' -- {} +
</code>```

the argument -- can be replaced by anything else it is used for $0 argument of shell.

```<code>bash -c 'echo $0' hello
</code>```

Maybe -printf "%TY-%Tm-%Td %TT - %p\n" option could achieve the same result, more efficiently without launching other process.

Also using echo may be less safe than using find -print option, considering the following use case.

```<code>touch file.$'\e#8'
find . -type d ! -name . -prune -o -name file'*' -print
find . -type d ! -name . -prune -o -name file'*' -exec echo {} \;
</code>```

Body:
i have a piece of code that should print all files in specific dir. i use find exec for this:

find ${_di} -type f -print -exec Log "$(stat -c%y {}) - {}" \;

Where log is function of mine defines in same file.
But id does not work and i get error message:

"find: Log: No such file or directory".

Why? What is wrong in this piece of code?

Body:
Function can't be used in -exec however bash -c can be used as command.
Slightly modified to using + as -exec command terminator and {} last to allow to reduce the number of bash processes spawned.

find ${_di} -type f -print -exec bash -c "$(typeset -f Log)"$'\n''for arg; do Log "$(stat -c%y "$arg") - $arg"; done' -- {} +

the argument -- can be replaced by anything else it is used for $0 argument of shell.

bash -c 'echo $0' hello

Maybe -printf "%TY-%Tm-%Td %TT - %p\n" option could achieve the same result, more efficiently without launching other process.

Also using echo may be less safe than using find -print option, considering the following use case.

touch file.$'\e#8'
find . -type d ! -name . -prune -o -name file'*' -print
find . -type d ! -name . -prune -o -name file'*' -exec echo {} \;


问:
Parsing UI router states to URLs without Angular
I have a Angular 1.5.9 web application and a Node.js/Sails.js 0.12 backend.
Inside Angular runs UI router 0.4 to handle states.

The state definitions might look like this (quite vanilla, I'd say):

```<code>$stateProvider.state('dogs', {
            url: '/ourdogsarecute_{specialIDofDog}
        }).
        state('dogs.specialDogState', {
            url: '/specialinfo_{specialInfoOfDog}'
        });
</code>```

Now, the following situation arises: In the backend (i.e. outside of Angular), I have to transform an Angular UI router state link like
{stateName: 'dogs.specialDogState', stateParams: {specialIDofDog: 11212, specialInfoOfDog: 'likesbones' } } into a valid URL like https://www.our-app.dog/ourdogsarecute_11212/specialinfo_likesbones.

I have no idea how to do that without a lot of manual work. Is there a kind of parser for UI router states as a node module?

I can access the front-end code where the state definitions lie from the backend somehow. that's not the problem. The problem is the transformation from state links into URLs.

答:
For reference: my solution now looks like this.
First of all, I've put my state definitions into a separate file, making it easier to access it from outside:

```<code>var myStates = [
    {
        name: 'dogs', stateProperties: {
        url: '/ourdogsarecute_{specialIDofDog}'
    }
    }, {
        name: 'dogs.specialDogState', stateProperties: {
            url: '/specialinfo_{specialInfoOfDog}'
        }
    }];
</code>```

And then in my app.config

```<code>for(var i = 0; i < myStates.length; i++) {
            $stateProvider.state(myStates[i].name, myStates[i].stateProperties);
        }
</code>```

In the backend, I've created this function:

```<code>/**
   * @description Turns state name and state params into a URL string, using stateLinks definition synchronized from front end (being UI router state definitions)
   * @param {string}  stateName Something like 'dogs.info.specialAttributes'
   * @param {object}  stateParams Something like {dogID: 34346346, dogStatus: 'private', dogInfo: 'food'}
   * @returns {string} URL
   */
  stateLinkResolve: function(stateName, stateParams) {

    if(!(stateName && stateName.length > 0)) {
      return '/';
    }

    var resultUrl = '';

    var splittedSubStates = stateName.split('.');// split "dogs.info.specialAttributes" into ["dogs","info","specialAttributes"]

    var currentStateInHierarchy = '';
    for(var i = 0; i < splittedSubStates.length; i++) {

      /* Add dot if "in between": not the first, not the last. So that "dogs" remains "dogs", but when going to "dogs.info", we want the dot in between */
      if(i > 0 && i < (splittedSubStates.length + 1) ) {
        currentStateInHierarchy += '.';
      }
      currentStateInHierarchy += splittedSubStates[i]; // Add current splitted name (being only the last name part) to the state name in its context. I.e. when doing "info", we want to access "dogs.info"
      var currState = _.find(stateDefs,{name: currentStateInHierarchy});
      var urlRaw = currState.stateProperties.url;

      /* uiRouter URLs may contain wildcards for parameter values like /ourdogs_{dogID:int}_{dogStatus}/:dogInfo.
        We go through each of these three types and replace them with their actual content.
          */
      for(var currentParam in stateParams) {
        urlRaw = urlRaw.replace(':' + currentParam, stateParams[currentParam]); // search for ":paramName" in URL
        urlRaw = urlRaw.replace('{' + currentParam + '}', stateParams[currentParam]); // search for "{paramName}" in URL

        // search for "{paramName:paramType}" in URL
        var uiRouterParamTypes = ["hash", "string", "query", "path", "int", "bool", "date", "json", "any"];
        for(var j = 0; j < uiRouterParamTypes.length; j++) {
          urlRaw = urlRaw.replace('{' + currentParam + ':' + uiRouterParamTypes[j] + '}', stateParams[currentParam]);
        }
      }
      resultUrl += urlRaw;
    }
    return resultUrl;
  }
</code>```

The problem is: This might fail for edge cases and it will definitely fail for new features being implemented to UI state router and the way URLs are built there. So, still hoping for a solution which directly uses UI router magic.

Body:
I have a Angular 1.5.9 web application and a Node.js/Sails.js 0.12 backend.
Inside Angular runs UI router 0.4 to handle states.

The state definitions might look like this (quite vanilla, I'd say):

$stateProvider.state('dogs', {
            url: '/ourdogsarecute_{specialIDofDog}
        }).
        state('dogs.specialDogState', {
            url: '/specialinfo_{specialInfoOfDog}'
        });

Now, the following situation arises: In the backend (i.e. outside of Angular), I have to transform an Angular UI router state link like
{stateName: 'dogs.specialDogState', stateParams: {specialIDofDog: 11212, specialInfoOfDog: 'likesbones' } } into a valid URL like https://www.our-app.dog/ourdogsarecute_11212/specialinfo_likesbones.

I have no idea how to do that without a lot of manual work. Is there a kind of parser for UI router states as a node module?

I can access the front-end code where the state definitions lie from the backend somehow. that's not the problem. The problem is the transformation from state links into URLs.

Body:
For reference: my solution now looks like this.
First of all, I've put my state definitions into a separate file, making it easier to access it from outside:

var myStates = [
    {
        name: 'dogs', stateProperties: {
        url: '/ourdogsarecute_{specialIDofDog}'
    }
    }, {
        name: 'dogs.specialDogState', stateProperties: {
            url: '/specialinfo_{specialInfoOfDog}'
        }
    }];

And then in my app.config

for(var i = 0; i < myStates.length; i++) {
            $stateProvider.state(myStates[i].name, myStates[i].stateProperties);
        }

In the backend, I've created this function:

/**
   * @description Turns state name and state params into a URL string, using stateLinks definition synchronized from front end (being UI router state definitions)
   * @param {string}  stateName Something like 'dogs.info.specialAttributes'
   * @param {object}  stateParams Something like {dogID: 34346346, dogStatus: 'private', dogInfo: 'food'}
   * @returns {string} URL
   */
  stateLinkResolve: function(stateName, stateParams) {

    if(!(stateName && stateName.length > 0)) {
      return '/';
    }

    var resultUrl = '';

    var splittedSubStates = stateName.split('.');// split "dogs.info.specialAttributes" into ["dogs","info","specialAttributes"]

    var currentStateInHierarchy = '';
    for(var i = 0; i < splittedSubStates.length; i++) {

      /* Add dot if "in between": not the first, not the last. So that "dogs" remains "dogs", but when going to "dogs.info", we want the dot in between */
      if(i > 0 && i < (splittedSubStates.length + 1) ) {
        currentStateInHierarchy += '.';
      }
      currentStateInHierarchy += splittedSubStates[i]; // Add current splitted name (being only the last name part) to the state name in its context. I.e. when doing "info", we want to access "dogs.info"
      var currState = _.find(stateDefs,{name: currentStateInHierarchy});
      var urlRaw = currState.stateProperties.url;

      /* uiRouter URLs may contain wildcards for parameter values like /ourdogs_{dogID:int}_{dogStatus}/:dogInfo.
        We go through each of these three types and replace them with their actual content.
          */
      for(var currentParam in stateParams) {
        urlRaw = urlRaw.replace(':' + currentParam, stateParams[currentParam]); // search for ":paramName" in URL
        urlRaw = urlRaw.replace('{' + currentParam + '}', stateParams[currentParam]); // search for "{paramName}" in URL

        // search for "{paramName:paramType}" in URL
        var uiRouterParamTypes = ["hash", "string", "query", "path", "int", "bool", "date", "json", "any"];
        for(var j = 0; j < uiRouterParamTypes.length; j++) {
          urlRaw = urlRaw.replace('{' + currentParam + ':' + uiRouterParamTypes[j] + '}', stateParams[currentParam]);
        }
      }
      resultUrl += urlRaw;
    }
    return resultUrl;
  }

The problem is: This might fail for edge cases and it will definitely fail for new features being implemented to UI state router and the way URLs are built there. So, still hoping for a solution which directly uses UI router magic.


问:
Form Button Refreshes on Click - One page Website
I've created a contact form so that users can send us an email. However, every time I click to send the email it also refreshes the page when clicked. This is a one page website.

I've attempted the fixes suggested in: How do I make an HTML button not reload the page

by using either the <button> element or use an <input type="button"/>. and also the fixes suggested in: prevent refresh of page when button inside form clicked

by adding onclick="return false;".

Both of these fixes stop the button from refreshing the page when it is clicked, however, it also stops the contact form from actually working and no longer sends an email to us.

I also updated my PHP to reflect the name changes of the type.

My PHP is:

```<code><?php
   if(isset($_POST['submit'])){
   $to = "example@example.com"; // this is your Email address
   $from = $_POST['email']; // this is the sender's Email address
   $name = $_POST['name'];
   $subject = "Form submission";
   $subject2 = "Copy of your form submission";
   $message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
   $message2 = "Here is a copy of your message " . $name . "\n\n" . $_POST['message'];

   $headers = "From:" . $from;
   $headers2 = "From:" . $to;
   mail($to,$subject,$message,$headers);
   mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
   echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";

   }
?>
</code>```

My HTML is:

```<code><form action="" method="post" id="contactForm">
<input type="text" name="name" id="name" placeholder="Name...">
<input type="text" name="email" id="email" placeholder="Email...">
<p><br></p>
<textarea name="message" id="message" cols="40" rows="3" spellcheck="true" placeholder="Message..."></textarea>
<p><br></p>
<button type="submit" id="submit" name="submit" onclick="return false;">Send Message</button>
</form>
</code>```

This currently works for sending the email, but does not stop it from refreshing the page. Would appreciate any help as to why it is doing this..

EDIT:

I've tried a few different options using AJAX since it was suggested this was the best route to take. All successfully stopped the page from refreshing, but all the options once again, stopped my contact form from working. I tried:

1:

```<code>$(function() {
    $('#contactForm').on('submit', function(e) {
        $.post('index.php', $(this).serialize(), function (data) {
            // This is executed when the call to mail.php was succesful.
            // 'data' contains the response from the request
        }).error(function() {
            // This is executed when the call to mail.php failed.
        });
        e.preventDefault();
    });
});
</code>```

2:

```<code>$("#contactForm").submit(function(e) {
    e.preventDefault();
});
</code>```

3:

I also tried the answer offered to me by Harsh Panchal.

答:
You can try using jquery ajax method

Create New File for send Email and in form attribute to give any id

```<code><script>
$('#main-contact-form').submit(function(event){
event.preventDefault();
$.ajax({
    type:'post',
    url:'sendememail.php',
    data:$(this).serialize(),
    success:function(response){
        if(response==1)
        {

            setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-success">Review Successfully Submited......</div></center></h5>');},5);

        }
        else
        {

            setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-danger">Sorry Your Review Not Submit......</div></center></h5>');},5);

        }
    }

});
});
</script>
</code>```

Body:
I've created a contact form so that users can send us an email. However, every time I click to send the email it also refreshes the page when clicked. This is a one page website.

I've attempted the fixes suggested in: How do I make an HTML button not reload the page

by using either the <button> element or use an <input type="button"/>. and also the fixes suggested in: prevent refresh of page when button inside form clicked

by adding onclick="return false;".

Both of these fixes stop the button from refreshing the page when it is clicked, however, it also stops the contact form from actually working and no longer sends an email to us.

I also updated my PHP to reflect the name changes of the type.

My PHP is:

<?php
   if(isset($_POST['submit'])){
   $to = "example@example.com"; // this is your Email address
   $from = $_POST['email']; // this is the sender's Email address
   $name = $_POST['name'];
   $subject = "Form submission";
   $subject2 = "Copy of your form submission";
   $message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
   $message2 = "Here is a copy of your message " . $name . "\n\n" . $_POST['message'];

   $headers = "From:" . $from;
   $headers2 = "From:" . $to;
   mail($to,$subject,$message,$headers);
   mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
   echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";

   }
?>

My HTML is:

<form action="" method="post" id="contactForm">
<input type="text" name="name" id="name" placeholder="Name...">
<input type="text" name="email" id="email" placeholder="Email...">

<textarea name="message" id="message" cols="40" rows="3" spellcheck="true" placeholder="Message..."></textarea>

<button type="submit" id="submit" name="submit" onclick="return false;">Send Message</button>
</form>

This currently works for sending the email, but does not stop it from refreshing the page. Would appreciate any help as to why it is doing this..

EDIT:

I've tried a few different options using AJAX since it was suggested this was the best route to take. All successfully stopped the page from refreshing, but all the options once again, stopped my contact form from working. I tried:

1:

$(function() {
    $('#contactForm').on('submit', function(e) {
        $.post('index.php', $(this).serialize(), function (data) {
            // This is executed when the call to mail.php was succesful.
            // 'data' contains the response from the request
        }).error(function() {
            // This is executed when the call to mail.php failed.
        });
        e.preventDefault();
    });
});

2:

$("#contactForm").submit(function(e) {
    e.preventDefault();
});

3:

I also tried the answer offered to me by Harsh Panchal.

Body:
You can try using jquery ajax method

Create New File for send Email and in form attribute to give any id

<script>
$('#main-contact-form').submit(function(event){
event.preventDefault();
$.ajax({
    type:'post',
    url:'sendememail.php',
    data:$(this).serialize(),
    success:function(response){
        if(response==1)
        {

            setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-success">Review Successfully Submited......</div></center></h5>');},5);

        }
        else
        {

            setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-danger">Sorry Your Review Not Submit......</div></center></h5>');},5);

        }
    }

});
});
</script>


问:
How to access the data sent via Jquery.getJSON from the server side?
I have the following $.getJSON request on the client side:

```<code>$.getJSON('/video/getToken', {classroomId: roomName}, cb);
</code>```

On the server side:

```<code>router.route('/video/getToken')
    .get(function(req, res) {
        console.log(req.body);
    });
</code>```

The console.log is returning an empty object. Shouldn't the output be
{classroomId: roomName}?

答:
You are doing a GET request, so there is no request body, instead you need to access the req.query:

Express 4.*

```<code>router.route('/video/getToken')
    .get(function(req, res) {
        console.log( req.query.classroomId );
    });
</code>```

Express 3.*

```<code>router.route('/video/getToken')
    .get(function(req, res) {
        console.log( req.query("classroomId") );
    });
</code>```

Body:
I have the following $.getJSON request on the client side:

$.getJSON('/video/getToken', {classroomId: roomName}, cb);

On the server side:

router.route('/video/getToken')
    .get(function(req, res) {
        console.log(req.body);
    });

The console.log is returning an empty object. Shouldn't the output be
{classroomId: roomName}?

Body:
You are doing a GET request, so there is no request body, instead you need to access the req.query:

Express 4.*

router.route('/video/getToken')
    .get(function(req, res) {
        console.log( req.query.classroomId );
    });

Express 3.*

router.route('/video/getToken')
    .get(function(req, res) {
        console.log( req.query("classroomId") );
    });


答:
You "$fstrto <= $cstrto" is a string now a compare statement.

```<code>$fstrto = "10";
$cstrto = "7";
if( ($status == 'N' && $fstrto <= $cstrto) || ($status != 'N' && $fstrto >= $cstrto) )
{
  echo "Success";
}
</code>```

Title: How to check different conditions into if statement based on different scenario

Body:
You "$fstrto <= $cstrto" is a string now a compare statement.

$fstrto = "10";
$cstrto = "7";
if( ($status == 'N' && $fstrto <= $cstrto) || ($status != 'N' && $fstrto >= $cstrto) )
{
  echo "Success";
}


问:
Can i extract a specific character from a string stored in a list?
str=['qIQNlQSLi', 'eOEKiVEYj', 'aZADnMCZq', 'bZUTkLYNg', 'uCNDeHSBj', 'kOIXdKBFh']

I want to extract the 5th index of each string in list i.e o/p is linked.

答:
You could do with list comprehension,

```<code>string=['qIQNlQSLi', 'eOEKiVEYj', 'aZADnMCZq', 'bZUTkLYNg', 'uCNDeHSBj', 'kOIXdKBFh']

[item[5] for item in str]
</code>```

Or you could do it much shorter like this,

```<code>>>> list(zip(*string))[5]
('Q', 'V', 'M', 'L', 'H', 'K')
>>>
</code>```

If the string is really big, then using this iterator method would be better.

Body:
You could do with list comprehension,

string=['qIQNlQSLi', 'eOEKiVEYj', 'aZADnMCZq', 'bZUTkLYNg', 'uCNDeHSBj', 'kOIXdKBFh']

[item[5] for item in str]

Or you could do it much shorter like this,

>>> list(zip(*string))[5]
('Q', 'V', 'M', 'L', 'H', 'K')
>>>

If the string is really big, then using this iterator method would be better.


问:
Javascript array length of 0
I am getting some weird behaviour with the following, it shows an array length of 0 eventhough printing it right before that shows that there clearly is a length greater than 0:

```<code>var getTopSelection = function(callback) {
    var topSelection = [];
    for(var i=0; i < markers.length; i++) {
        if(markers[i].map !== null) {
            var stationID = markers[i].id;
            getTrips(stationID, globalFromDate, globalToDate, function(response) {
                topSelection.push({
                    StationID: stationID,
                    Trips: response
                });
            }, function(error) {
                console.log(error);
            })
        }
    }
    callback(topSelection);
};

getTopSelection(function(response) {
            console.log(response); //115
            console.log(response.length); //116
})
</code>```

And this is shown in the inspector, the "length: 42" belongs to line 115.

Question: Why does it show a length of 0 eventhough it clearly says it has a length of 42 one line before?

答:
So what actually happens is that when you log your response it actually having length as 0. But after the asynchronous response is returned it has 42 items but length being a property is logged as number. But your response being an object is logged initially with zero items. But when the actual response is received the reference to the response object is updated and you see that the response is having 42 items and length is also 42. The below code is an example for that  that to show after the setTimeout is called the logged response is updated in the console.

var getTopSelection = function(callback) {
    var topSelection = [];
    markers=[1,2,3,4,5,6,7,8,9];
    for(var i=0; i < markers.length; i++) {
        if(markers[i].map !== null) {
            var stationID = markers[i].id;
            getTrips(stationID, function(response) {
                topSelection.push({
                    StationID: i,
                    Trips: response
                });
            }, function(error) {
                console.log(error);
            })
        }
    }
    callback(topSelection);
};

function getTrips(station,fun){
setTimeout(function(){
 fun(["trip1","trip2","trip3"]);
},1000)
}
getTopSelection(function(response) {
            console.log(response); //115
            console.log(response.length); //116
})```

Try executing this snippet(have modified accordingly to show what actually happens) in a Fiddle here. And observe the output in console as in stackoverflow snippet result it wont be visible. Here is snap of the Console Output

Hope it helps :)

Title: Javascript array length of 0

Body:
I am getting some weird behaviour with the following, it shows an array length of 0 eventhough printing it right before that shows that there clearly is a length greater than 0:

var getTopSelection = function(callback) {
    var topSelection = [];
    for(var i=0; i < markers.length; i++) {
        if(markers[i].map !== null) {
            var stationID = markers[i].id;
            getTrips(stationID, globalFromDate, globalToDate, function(response) {
                topSelection.push({
                    StationID: stationID,
                    Trips: response
                });
            }, function(error) {
                console.log(error);
            })
        }
    }
    callback(topSelection);
};

getTopSelection(function(response) {
            console.log(response); //115
            console.log(response.length); //116
})

And this is shown in the inspector, the "length: 42" belongs to line 115.

Question: Why does it show a length of 0 eventhough it clearly says it has a length of 42 one line before?

Body:
So what actually happens is that when you log your response it actually having length as 0. But after the asynchronous response is returned it has 42 items but length being a property is logged as number. But your response being an object is logged initially with zero items. But when the actual response is received the reference to the response object is updated and you see that the response is having 42 items and length is also 42. The below code is an example for that  that to show after the setTimeout is called the logged response is updated in the console.

var getTopSelection = function(callback) {
    var topSelection = [];
    markers=[1,2,3,4,5,6,7,8,9];
    for(var i=0; i < markers.length; i++) {
        if(markers[i].map !== null) {
            var stationID = markers[i].id;
            getTrips(stationID, function(response) {
                topSelection.push({
                    StationID: i,
                    Trips: response
                });
            }, function(error) {
                console.log(error);
            })
        }
    }
    callback(topSelection);
};

function getTrips(station,fun){
setTimeout(function(){
 fun(["trip1","trip2","trip3"]);
},1000)
}
getTopSelection(function(response) {
            console.log(response); //115
            console.log(response.length); //116
})

Try executing this snippet(have modified accordingly to show what actually happens) in a Fiddle here. And observe the output in console as in stackoverflow snippet result it wont be visible. Here is snap of the Console Output

Hope it helps :)


问:
Upload images via adjusted form and dropzone and codeigniter
Im trying to upload images via dropzone/codeigniter. Unfortantly I dont get the post data to the controller and then to the modal. obviously it's not ajax where i can insert data in order to get it.

Here is part of the form:

```<code><div class="dropzone" id="my-dropzone" name="mainFileUploader">
    <div class="fallback">
        <input name="file" type="file" multiple />
    </div>
</div>
</code>```

Here is the script:

```<code>var myDropzone = new Dropzone("#my-dropzone", {
    url: "<?=admin_url()?>invoice_items/upload_image",
    data: this,
    method: "post",
    addRemoveLinks:true,
    acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',

    init: function () {
        this.on("addedfile", function (file) {
            console.log(file);
        });
    }
});
</code>```

Here is the controller

```<code>public function upload_image(){
    if ($this->input->post()) {
        $this->invoice_items_model->add_image($this->input->post());
    }
}
</code>```

Here is the modal

```<code>public function add_image($data){
    $dat = array(
        'rel_name' => $data['name'],
        'rel_type' => 'cms_items',
        'dateadded' => date('Y-m-d H:i:s')
    );
    $this->db->insert('tblfiles', $dat);
}
</code>```

答:
For the one that need an answer:</p>

```<code>var myDropzone = new Dropzone("#my-dropzone", {
    url: "<?=admin_url()?>invoice_items/upload_image",
    files: this,
    method: "post",
    addRemoveLinks:true,
    acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',
    init: function (data) {
        this.on("sucess",function(file, xhr, formData){

        });

    },
    dictDefaultMessage: "<?=_l('drop_files_here_to_upload')?>",
    dictRemoveFile : "<?=_l('remove_file')?>"
});
</code>```

Body:
Im trying to upload images via dropzone/codeigniter. Unfortantly I dont get the post data to the controller and then to the modal. obviously it's not ajax where i can insert data in order to get it.

Here is part of the form:

        <input name="file" type="file" multiple />

Here is the script:

var myDropzone = new Dropzone("#my-dropzone", {
    url: "<?=admin_url()?>invoice_items/upload_image",
    data: this,
    method: "post",
    addRemoveLinks:true,
    acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',

    init: function () {
        this.on("addedfile", function (file) {
            console.log(file);
        });
    }
});

Here is the controller

public function upload_image(){
    if ($this->input->post()) {
        $this->invoice_items_model->add_image($this->input->post());
    }
}

Here is the modal

public function add_image($data){
    $dat = array(
        'rel_name' => $data['name'],
        'rel_type' => 'cms_items',
        'dateadded' => date('Y-m-d H:i:s')
    );
    $this->db->insert('tblfiles', $dat);
}

Body:
For the one that need an answer:

var myDropzone = new Dropzone("#my-dropzone", {
    url: "<?=admin_url()?>invoice_items/upload_image",
    files: this,
    method: "post",
    addRemoveLinks:true,
    acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',
    init: function (data) {
        this.on("sucess",function(file, xhr, formData){

        });

    },
    dictDefaultMessage: "<?=_l('drop_files_here_to_upload')?>",
    dictRemoveFile : "<?=_l('remove_file')?>"
});


问:
How to validate form field with array values[] in laravel?
I'm trying to validate form field with array value.

```<code>    $this->validate($request, [

        'includes' => 'required',
        'excludes' => 'required'
    ]);
</code>```

HTML is as follows:

```<code><input type="text" name="excludes[]" id="package_exclude"
                                                   class="form-control">
<input type="text" name="includes[]" id="package_include"
                                                   class="form-control">
</code>```

The outputted value of $request->includes gives ["Include Value One","Include Value Two"] which is working fine..
But the validation doesn't works..

答:
I suppose you want the arrays to have at least one value? In this case, you can use the min validation rule:

```<code>$this->validate($request, [
    'includes' => 'required|min:1',
    'excludes' => 'required|min:1'
]);
</code>```

Body:
I'm trying to validate form field with array value.

    $this->validate($request, [

        'includes' => 'required',
        'excludes' => 'required'
    ]);

HTML is as follows:

<input type="text" name="excludes[]" id="package_exclude"
                                                   class="form-control">
<input type="text" name="includes[]" id="package_include"
                                                   class="form-control">

The outputted value of $request->includes gives ["Include Value One","Include Value Two"] which is working fine..
But the validation doesn't works..

Body:
I suppose you want the arrays to have at least one value? In this case, you can use the min validation rule:

$this->validate($request, [
    'includes' => 'required|min:1',
    'excludes' => 'required|min:1'
]);


问:
AssetManage instantiation
How to properly instantiate AssetManage?

I have a file that I'd like to load and I am getting an error.

Here is what I have:

```<code>     AssetManager assetManager = new AssetManager(handle);

     Typeface tf = Typeface.CreateFromAsset(assetManager, "fonts/calibri.ttf");

     this._textView.SetTypeface(tf, 0); // i just need a regular calibri, I added a file into the fonts folder and set it to AndroidAsset.
</code>```

What should be a "handle" in this case?

Thank you

答:
```<code>AssetManager assetManager = getResources().getAssets();
</code>```

Title: AssetManage instantiation

Body:
How to properly instantiate AssetManage?

I have a file that I'd like to load and I am getting an error.

Here is what I have:

     AssetManager assetManager = new AssetManager(handle);

     Typeface tf = Typeface.CreateFromAsset(assetManager, "fonts/calibri.ttf");

     this._textView.SetTypeface(tf, 0); // i just need a regular calibri, I added a file into the fonts folder and set it to AndroidAsset.

What should be a "handle" in this case?

Thank you


问:
XSLT checking passed param string value in a choose/when format
I'm attempting to read in parameters from a C# program, with userPrimaryInput being a selection between the letters R or T to represent different categories of results and userSecondary input being the index of the C# array that matches the xml node number. My problem is that despite putting it all within a choose/when block based on the user input for desired html output, it only ever seems to produce the first when.

My question, then, is how do I properly use the choose/when format to check a parameter that is a string (which would be the userPrimaryInput param here)?

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
<xsl:output method="html" indent="yes"/>

<xsl:param name="userPrimaryInput"/>

<xsl:param name="userSecondaryInput"/>

<xsl:template match="/">

<xsl:choose>
  <!--IF Region select-->
   <xsl:when test="userPrimaryInput = R | userPrimaryInput = r "><!--Region
select if-->
<html>
  <body>
    <h1>

     Incidents of Crime in <xsl:value-of select="/crime-in-
         canada/region[position()=$userSecondaryInput]/@name"/>, 2013
    </h1>
    <table border="1">
      <tr>
        <th>Crime Type</th>
        <th>Incidents</th>
        <th>Rate(incidents/100,000)</th>
      </tr>
      <tr>

          <xsl:for-each select="/crime-in-
           canada/region[position()=$userSecondaryInput]/crime">
            <tr>
        <td>
          <xsl:value-of select="@type"/>
        </td>
        <td>
          <xsl:value-of select="@incidents"/>
        </td>
        <td>
          <xsl:value-of select="(@incidents div (../population-millions*1000000 div 100000))"/>
        </td>
     </tr>
        </xsl:for-each>
      </tr>
    </table>
  </body>
</html>
</xsl:when><!--End of region select if -->
<!--IF Type select-->
  <xsl:when test="userPrimaryInput = T | userPrimaryInput = t ">
    <html>
      <body>
        <h1>

          Incidents of <xsl:value-of select="/crime-in-
    canada/region/crime[position()=$userSecondaryInput]/@type"/> Across All
    Regions, 2013
        </h1>
        <table border="1">
          <tr>
            <th>Crime Type</th>
            <th>Incidents</th>
            <th>Rate(incidents/100,000)</th>
          </tr>
          <tr>

            <xsl:for-each select="/crime-in-
 canada/region/crime[position()=$userSecondaryInput]">
              <tr>
                <td>
                  <xsl:value-of select="../@name"/>
                </td>
                <td>
                  <xsl:value-of select="@incidents"/>
                </td>
                <td>
                  <xsl:value-of select="(@incidents div (../population-
 millions*1000000 div 100000))"/>
                </td>
              </tr>
            </xsl:for-each>
          </tr>
        </table>
      </body>
    </html>
  </xsl:when>
</xsl:choose>
  </xsl:template>

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

答:
I am surprised you get anything output, because I think the culprit is this line....

```<code><xsl:when test="userPrimaryInput = R | userPrimaryInput = r ">
</code>```

There are three problems here...

You have missed out the $ prefix for userPrimaryInput, so it is looking for an element called userPrimaryInput, and not the parameter

Doing userPrimaryInput = R means it is looking to compare it with an element named R. Use 'R' to compare it with a string literal

| is the union operator. It is not a logical "or" operator. Use "or" here!

So, the test should be like so

```<code><xsl:when test="$userPrimaryInput = 'R' or $userPrimaryInput = 'r'">
</code>```

And similarly for the line testing for T (or you could use xsl:otherwise here too)

Body:
I'm attempting to read in parameters from a C# program, with userPrimaryInput being a selection between the letters R or T to represent different categories of results and userSecondary input being the index of the C# array that matches the xml node number. My problem is that despite putting it all within a choose/when block based on the user input for desired html output, it only ever seems to produce the first when.

My question, then, is how do I properly use the choose/when format to check a parameter that is a string (which would be the userPrimaryInput param here)?

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
<xsl:output method="html" indent="yes"/>

<xsl:param name="userPrimaryInput"/>

<xsl:param name="userSecondaryInput"/>

<xsl:template match="/">

<xsl:choose>

   <xsl:when test="userPrimaryInput = R | userPrimaryInput = r ">

     Incidents of Crime in <xsl:value-of select="/crime-in-
         canada/region[position()=$userSecondaryInput]/@name"/>, 2013

        Crime Type
        Incidents
        Rate(incidents/100,000)

          <xsl:for-each select="/crime-in-
           canada/region[position()=$userSecondaryInput]/crime">

          <xsl:value-of select="@type"/>

          <xsl:value-of select="@incidents"/>

          <xsl:value-of select="(@incidents div (../population-millions*1000000 div 100000))"/>

        </xsl:for-each>

</xsl:when>

  <xsl:when test="userPrimaryInput = T | userPrimaryInput = t ">

          Incidents of <xsl:value-of select="/crime-in-
    canada/region/crime[position()=$userSecondaryInput]/@type"/> Across All
    Regions, 2013

            Crime Type
            Incidents
            Rate(incidents/100,000)

            <xsl:for-each select="/crime-in-
 canada/region/crime[position()=$userSecondaryInput]">

                  <xsl:value-of select="../@name"/>

                  <xsl:value-of select="@incidents"/>

                  <xsl:value-of select="(@incidents div (../population-
 millions*1000000 div 100000))"/>

            </xsl:for-each>

  </xsl:when>
</xsl:choose>
  </xsl:template>

</xsl:stylesheet>

Body:
I am surprised you get anything output, because I think the culprit is this line....

<xsl:when test="userPrimaryInput = R | userPrimaryInput = r ">

There are three problems here...

You have missed out the $ prefix for userPrimaryInput, so it is looking for an element called userPrimaryInput, and not the parameter

Doing userPrimaryInput = R means it is looking to compare it with an element named R. Use 'R' to compare it with a string literal

| is the union operator. It is not a logical "or" operator. Use "or" here!

So, the test should be like so

<xsl:when test="$userPrimaryInput = 'R' or $userPrimaryInput = 'r'">

And similarly for the line testing for T (or you could use xsl:otherwise here too)


问:
simple authorisation / login capability in php
I'm looking to implement user login onto my site for the first time.  I'm happy to either build my own solution, or implement something open source, however no package has been an obvious choice in my search so far.  Equally, I'm fully aware that as an intermediate php programmer at best, I am highly likely to miss something obvious if I roll my own solution, and leave the doors well and truly open.

Any suggestions?  We're not talking super sensitive or payment data here, but equally, I'm keen not to have people mess up my site!

requirements are
- php based
- simple as possible, not need for fancy bells and whistles
- not Zend framework, since i've now rolled my own very basic frameworkthanks to this post

Thanks for your input.

答:
I find that for some uses, building my own using http authentication is sufficient. I'd recommend this as a starting point.

Since you have your own basic framework, it should not be too difficult to include the authentication code in some place that is common.

Some advantages are

Not a lot of code.

Does not require
cookies or URL rewriting.

Disadvantages

Doesn't scale well to more granular
access control.

No easy way to "log
out".

--

bmb

OwnerDisplayName: Rob Y

OwnerDisplayName: bmb


问:
Initializing a dynamic memory array in a class
I am new to c++ programming, and this is probably a trivial problem, but I need to construct a variable sized array in a class and transfer text file data into it, see below. Here HISTORYFile >> ClusterCoord[i]; seems to take in the information fine, however when I try to get access to the info in the main program via,

```<code>cout << CoordClassExample.ClusterCoord[1] << "\n";
</code>```

I get a bus error. Please help if you can!

```<code>class CoordClass{
public:
    int Entries;
    double * ClusterCoord;
    void set_valuesCoord(ifstream &HISTORYFile,int MolAtomNum, int MolNum);
};

void CoordClass::set_valuesCoord(ifstream& HISTORYFile,int MolAtomNum, int MolNum) {
    Entries=MolAtomNum*MolNum;
    double *ClusterCoord = new double [Entries];

    for (int i=0;i<Entries;i++) {
        HISTORYFile.ignore(1000,'\n');
            HISTORYFile >> ClusterCoord[i];
        cout << ClusterCoord[i] << "\n";
            HISTORYFile.ignore(1000,'\n');
    }
}
</code>```

答:
As an exercise showing the vector way that won't leak among other things:

Further changes would be to remove Entries and use ClusterCoord.size().

```<code>class CoordClass{
public:
    int Entries;
    std::vector<double> ClusterCoord;
    void set_valuesCoord(ifstream &HISTORYFile,int MolAtomNum, int MolNum);
};

void CoordClass::set_valuesCoord(ifstream& HISTORYFile,int MolAtomNum, int MolNum) {
    Entries=MolAtomNum*MolNum;
    ClusterCoord.resize(Entries);

    for (int i=0;i<Entries;i++) {
        HISTORYFile.ignore(1000,'\n');
            HISTORYFile >> ClusterCoord[i];
        cout << ClusterCoord[i] << "\n";
            HISTORYFile.ignore(1000,'\n');
    }
}
</code>```

Body:
I am new to c++ programming, and this is probably a trivial problem, but I need to construct a variable sized array in a class and transfer text file data into it, see below. Here HISTORYFile >> ClusterCoord[i]; seems to take in the information fine, however when I try to get access to the info in the main program via,

cout << CoordClassExample.ClusterCoord[1] << "\n";

I get a bus error. Please help if you can!

class CoordClass{
public:
    int Entries;
    double * ClusterCoord;
    void set_valuesCoord(ifstream &HISTORYFile,int MolAtomNum, int MolNum);
};

void CoordClass::set_valuesCoord(ifstream& HISTORYFile,int MolAtomNum, int MolNum) {
    Entries=MolAtomNum*MolNum;
    double *ClusterCoord = new double [Entries];

    for (int i=0;i<Entries;i++) {
        HISTORYFile.ignore(1000,'\n');
            HISTORYFile >> ClusterCoord[i];
        cout << ClusterCoord[i] << "\n";
            HISTORYFile.ignore(1000,'\n');
    }
}

Body:
As an exercise showing the vector way that won't leak among other things:

Further changes would be to remove Entries and use ClusterCoord.size().

class CoordClass{
public:
    int Entries;
    std::vector<double> ClusterCoord;
    void set_valuesCoord(ifstream &HISTORYFile,int MolAtomNum, int MolNum);
};

void CoordClass::set_valuesCoord(ifstream& HISTORYFile,int MolAtomNum, int MolNum) {
    Entries=MolAtomNum*MolNum;
    ClusterCoord.resize(Entries);

    for (int i=0;i<Entries;i++) {
        HISTORYFile.ignore(1000,'\n');
            HISTORYFile >> ClusterCoord[i];
        cout << ClusterCoord[i] << "\n";
            HISTORYFile.ignore(1000,'\n');
    }
}


问:
Webpack dynamically create a module
I am writing a plugin which creates a SVG sprite. It globs over the directories, merge SVG files in one image and returns the result. The idea is to dynamically create a module (which contains merged images) so that other modules can require it as an usual module. Or maybe you can suggest a more elegant solution?

Config

```<code>{
  plugins: [
    new SvgSpritePlugin({
      sprites: {
        icons: 'images/svg/icons/*.svg',
        logos: 'images/svg/logos/*.svg',
        socials: 'images/svg/logos/{twitter,youtube,facebook}.svg',
      }
    })
  ]
}
</code>```

Somewhere in the application

```<code>var logosSprite = require('sprite/logos'); // require dynamically created module
document.body.appendChild(logoSprite);
</code>```

答:
Try taking a look at how external and delegated modules are provided in Webpack. A good place to start is the ExternalModuleFactoryPlugin or DllReferencePlugin.

Essentially, you create a plugin for the NormalModuleFactory which takes requests for modules, you match those which should resolve to the modules you are generating and you can asynchronously respond with a Module.

Title: Webpack dynamically create a module

Body:
I am writing a plugin which creates a SVG sprite. It globs over the directories, merge SVG files in one image and returns the result. The idea is to dynamically create a module (which contains merged images) so that other modules can require it as an usual module. Or maybe you can suggest a more elegant solution?

Config

{
  plugins: [
    new SvgSpritePlugin({
      sprites: {
        icons: 'images/svg/icons/*.svg',
        logos: 'images/svg/logos/*.svg',
        socials: 'images/svg/logos/{twitter,youtube,facebook}.svg',
      }
    })
  ]
}

Somewhere in the application

var logosSprite = require('sprite/logos'); // require dynamically created module
document.body.appendChild(logoSprite);


答:
you can do : </p>

```<code>5thChar=[i[5] for i in str]
</code>```

<p>which is equivalent to : </p>

```<code>5thChar=[]
for i in str:
    5thChar.append(i[5])
</code>```

Title: Can i extract a specific character from a string stored in a list?

Body:
str=['qIQNlQSLi', 'eOEKiVEYj', 'aZADnMCZq', 'bZUTkLYNg', 'uCNDeHSBj', 'kOIXdKBFh']

I want to extract the 5th index of each string in list i.e o/p is linked.

Body:
you can do :

5thChar=[i[5] for i in str]

which is equivalent to :

5thChar=[]
for i in str:
    5thChar.append(i[5])


问:
Switch Rows and Columns 2d Array
I want to swap Columns and Rows in a 2D array.

My problem is that I want the Variable "oldField" to save the oldField. The Variable I think is Pointing on the same Object as newField and so it get´s changed even tho I dont want that.

Id like to know how I can save the Variable oldField independent

```<code>public int[][] swapMatrix(int[][] pField) { // swaps the rows and columns in
                                            // a Field
    int[][] oldField = pField.clone();
    int[][] newField = pField.clone();
    for (int i = 0; i < newField.length; i++) {
        for (int j = (newField.length - 1); j >= 0; j--) {
            newField[i][(newField.length - 1) - j] = oldField[j][i];
        }
    }
    return newField;

}
</code>```

答:
When you copy in 1-D array with primitive value like int then the new array and content copy to it and there is no reference.

```<code> int row1[] = {0,1,2,3};
    int row2[] =  row1.clone();
    row2[0] = 10;
    System.out.println(row1[0] == row2[0]); // prints false
</code>```

but for 2-D array the content is object and clone method only do shallow copy not create new content if object is there .For your requirement you need to do deep copy.

```<code>int table1[][]={{0,1,2,3},{11,12,13,14}};
    int table2[][] = table1.clone();
    table2[0][0] = 100;
    System.out.println(table1[0][0] == table2[0][0]); //prints true
</code>```

Title: Switch Rows and Columns 2d Array

Body:
I want to swap Columns and Rows in a 2D array.

My problem is that I want the Variable "oldField" to save the oldField. The Variable I think is Pointing on the same Object as newField and so it get´s changed even tho I dont want that.

Id like to know how I can save the Variable oldField independent

public int[][] swapMatrix(int[][] pField) { // swaps the rows and columns in
                                            // a Field
    int[][] oldField = pField.clone();
    int[][] newField = pField.clone();
    for (int i = 0; i < newField.length; i++) {
        for (int j = (newField.length - 1); j >= 0; j--) {
            newField[i][(newField.length - 1) - j] = oldField[j][i];
        }
    }
    return newField;

}

Body:
When you copy in 1-D array with primitive value like int then the new array and content copy to it and there is no reference.

 int row1[] = {0,1,2,3};
    int row2[] =  row1.clone();
    row2[0] = 10;
    System.out.println(row1[0] == row2[0]); // prints false

but for 2-D array the content is object and clone method only do shallow copy not create new content if object is there .For your requirement you need to do deep copy.

int table1[][]={{0,1,2,3},{11,12,13,14}};
    int table2[][] = table1.clone();
    table2[0][0] = 100;
    System.out.println(table1[0][0] == table2[0][0]); //prints true


问:
How to replace missing row with a specific values in T-SQL
I need to generate a report as in the query:

```<code>select cIDNum,cvisitNo, cgender
from table detail
</code>```

Some records for a visit are not entered into the database and thus missing. Now I want to have the missing rows for the visit amended in the query so that I have it as follows:

```<code>l256T, 0,F
l256T, 1,F
l256T, 2,F
l256T, 3,F
l256T, 4,F
l256T, 5,F
l256T, 6,F
</code>```

答:
you can try something like this:</p>

```<code>;With cte1 as
( select * from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) a(n) )
,Cte2 as ( select c1.* from cte1 c1, cte1 c2, cte1 c3)
,numbers as ( select RowN = row_number() over (order by (select null))-1  from cte2 c1, cte2 c2)
Select td.cidNum, RowN as cVisitNo, td.cgender from Numbers n
    Left join tableDetail td
    on n.RowN = td.VisitNo
</code>```

Body:
I need to generate a report as in the query:

select cIDNum,cvisitNo, cgender
from table detail

Some records for a visit are not entered into the database and thus missing. Now I want to have the missing rows for the visit amended in the query so that I have it as follows:

l256T, 0,F
l256T, 1,F
l256T, 2,F
l256T, 3,F
l256T, 4,F
l256T, 5,F
l256T, 6,F

Body:
you can try something like this:

;With cte1 as
( select * from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) a(n) )
,Cte2 as ( select c1.* from cte1 c1, cte1 c2, cte1 c3)
,numbers as ( select RowN = row_number() over (order by (select null))-1  from cte2 c1, cte2 c2)
Select td.cidNum, RowN as cVisitNo, td.cgender from Numbers n
    Left join tableDetail td
    on n.RowN = td.VisitNo


问:
Excel: Avoid formula error checking when using replace all
I've been having a very annoying problem with a large excel file in which I need to replace all the ";" by ",". When I try to do this I get an error (That function isn't valid) that I've discovered that is caused by a leading "@" that is present in some of the cells, so I try to replace all the "@" by "'@" but I get this error: There is a problem with this formula..., beacause there are cells with leading "=", If I try replacing the "=" by "'=" I get the same error than before beacuse of course there are still cells with a leading "@" and I can't do the replace by "'@" again beacause then I'll start getting multiple "'" before the "@" (each time you run the "replace all" it starts from the begining of course) and I need to maintain the integrity of the data. So, is there any way to avoid the formula error checking when doing a replace? I've tryed going to more commands -> Formulas and uncheking "Enable background error checking" and setting "Workbook Calculation" to manual, but I haven't got any luck.</p>

答:
Since the problem was in fact only in a column, I created an additional one next to it and did

```<code>="'"&A1
</code>```

And then dragged the value across the column. That solved it for me.

Body:
Since the problem was in fact only in a column, I created an additional one next to it and did

="'"&A1

And then dragged the value across the column. That solved it for me.


问:
HTML Table : Overflow-x scroll if no of columns are more
I have a table with certain columns. If I add columns then the table div should scroll horizontally.

Let say I have 10 columns and I add 2 more columns.

so I want there is no scroll up to 10 columns and If there are 2 more columns , then There should be overflow-x:scroll.

.horizontal_scroll_div{

}

.horizontal_scroll_div .scroll_table_div{
  overflow-x: scroll !important;
}

.horizontal_scroll_div .scroll_table_div .table_section{
  width:1200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="horizontal_scroll_div">
    <div class="scroll_table_div b">
      <div class="table_section">
      <div class="row m-l-none m-r-none " >
          <div class="col-sm-12 col-md-12 set_padding_0">
                <div class="table-responsive m-b-none no_border">
                <table class="table b-t b-b no-footer">
                  <thead class="bg-white">
                  <tr>
                    <th>column 1</th>
                    <th>column 2</th>
                    <th>column 3</th>
                    <th>column 4</th>
                    <th>column 5</th>
                    <th>column 6</th>
                    <th>column 7</th>
                    <th>column 8</th>
                    <th>column 9</th>
                    <th>column 10</th>
                    <th>column 11</th>
                    <th>column 12</th>

                  </tr>
                  </thead>
                  <tbody>
                  <tr>
                    <td>value 1</td>
                    <td>value 2</td>
                    <td>value 3</td>
                    <td>value 4</td>
                    <td>value 5</td>
                    <td>value 6</td>
                    <td>value 7</td>
                    <td>value 8</td>
                    <td>value 9</td>
                    <td>value 10</td>
                    <td>value 11</td>
                    <td>value 12</td>
                  </tr>
                  </tbody>
                  </table>
               </div>
          </div>
       </div>
  </div>
  </div>
  </div></code>```

Any help would be great.
Thank You.

答:
you can use

When width is reach 1200px after that the scroll bar appear.

```<code>.horizontal_scroll_div .scroll_table_div{
  overflow-x: auto !important;
}
</code>```

Body:
I have a table with certain columns. If I add columns then the table div should scroll horizontally.

Let say I have 10 columns and I add 2 more columns.

so I want there is no scroll up to 10 columns and If there are 2 more columns , then There should be overflow-x:scroll.

.horizontal_scroll_div{

}

.horizontal_scroll_div .scroll_table_div{
  overflow-x: scroll !important;
}

.horizontal_scroll_div .scroll_table_div .table_section{
  width:1200px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

                    column 1
                    column 2
                    column 3
                    column 4
                    column 5
                    column 6
                    column 7
                    column 8
                    column 9
                    column 10
                    column 11
                    column 12

                    value 1
                    value 2
                    value 3
                    value 4
                    value 5
                    value 6
                    value 7
                    value 8
                    value 9
                    value 10
                    value 11
                    value 12

Any help would be great.
Thank You.

Body:
you can use

When width is reach 1200px after that the scroll bar appear.

.horizontal_scroll_div .scroll_table_div{
  overflow-x: auto !important;
}


问:
How to check different conditions into if statement based on different scenario
I want to check different conditions into if statement based on different scenario (Will get the $status value as 'Y' or 'N'). Please check the code below and let me know the issue here.

```<code>$fstrto = "10";
$cstrto = "7";
if($status == 'N')
{
    $cond = "$fstrto <= $cstrto";
}
else
{
    $cond = "$fstrto >= $cstrto";
}
if($cond)
{
    echo "Success";
}
</code>```

This code is not working as it takes the "$fstrto <= $cstrto" as variable.

答:
what is need to do is when using string as a php code use

eval — Evaluate a string as PHP code

Use below code work like charm:

```<code>    $fstrto = "10";
    $cstrto = "7";
    if($status == 'N')
    {
    $cond = "$fstrto <= $cstrto";
    }
    else
    {
    $cond = "$fstrto >= $cstrto";
    }
    if(eval("return $cond;"))
    {
    echo "Success";
    }
</code>```

IMPORTANT:

Use of eval is highly discouraged

NEVER EVER use eval with params by POST/GET without sanitize them

When is eval evil in php?

Body:
I want to check different conditions into if statement based on different scenario (Will get the $status value as 'Y' or 'N'). Please check the code below and let me know the issue here.

$fstrto = "10";
$cstrto = "7";
if($status == 'N')
{
    $cond = "$fstrto <= $cstrto";
}
else
{
    $cond = "$fstrto >= $cstrto";
}
if($cond)
{
    echo "Success";
}

This code is not working as it takes the "$fstrto <= $cstrto" as variable.

Body:
what is need to do is when using string as a php code use

eval — Evaluate a string as PHP code

Use below code work like charm:

    $fstrto = "10";
    $cstrto = "7";
    if($status == 'N')
    {
    $cond = "$fstrto <= $cstrto";
    }
    else
    {
    $cond = "$fstrto >= $cstrto";
    }
    if(eval("return $cond;"))
    {
    echo "Success";
    }

IMPORTANT:

Use of eval is highly discouraged

NEVER EVER use eval with params by POST/GET without sanitize them

When is eval evil in php?


问:
It is possible to read protected NFC tags in iOS?
News that in iOS 11 Apple now support reading NFC tags for iPhone 7/7 Plus and above.

I found some demos but don't know if there is a way to read protected NFC tags. For example, travel documents have embedded NFC tags that are protected from unsafe reading. I searched around NFC NDEF protocols in Apple documentation but there is no functions that require a challenge/handshake for NFC tags. Is there a way to interact with these types of NFC tags?

答:
Important note: The answer below was true for Core NFC in iOS 11. A lot has happened since then. In 2019, Apple added many enhancements to Core NFC. The API now provides access to lower protocol layers (such as exchanging APDUs with contactless smartcards (ISO/IEC 14443-4), and sending commands to MIFARE (and potentially, but not verified, other ISO 14443-3A tags), FeliCa, and ISO/IEC 15693 tags).

The Core NFC overview page announces that as:

Your app can also write data to tags, and interact with protocol specific tag such as ISO 7816, ISO 15693, FeliCa™, and MIFARE® tags.

Answer from 2017:

No, Core NFC only works with NFC tag that are NDEF formatted. Thus, you can only interact with NFC tags that adhere to the NDEF (NFC Data Exchange Format) hardware abstraction layer specified by the NFC Forum. Specifically, with NFC Forum tag types 1 to 5.

Core NFC overview page:

Reading NFC NDEF tags is supported on iPhone 7 and iPhone 7 Plus.

Using Core NFC, you can read Near Field Communication (NFC) tags of
  types 1 through 5 that contain data in the NFC Data Exchange Format
  (NDEF).

Contactless smartcards (like electronic passports, payment cards, etc.) and even additional protection features of NFC tags (like NTAG password protection, MIFARE DESFire or Ultralight authentication, etc.) cannot be accessed using the iOS 11 NFC API.


问:
how do u give permissions to user www-data to rw a directory?
I want to give group access to user www-data on ubuntu for a directory.  What is the proper way? thx  </p>

答:
```<code>sudo chgrp www-data dir
</code>```

add -R if you want it recursive

Body:
sudo chgrp www-data dir

add -R if you want it recursive


问:
OpenCL: Why does clCreateContext creates threads?
I am debugging a segmentation fault related to OpenCL. Using gdb I noticed that several threads are created as a result of clCreateContext

GDB output:

print Before clCreateContext

[New Thread 0x7ffff299b700 (LWP 10807)]

[New Thread 0x7ffff219a700 (LWP 10808)]

[New Thread 0x7ffff1999700 (LWP 10809)]

[New Thread 0x7ffff1198700 (LWP 10810)]

[New Thread 0x7ffff0997700 (LWP 10811)]

[New Thread 0x7fffebfff700 (LWP 10812)]

[New Thread 0x7fffeb7fe700 (LWP 10813)]

print After clCreateContext

Does somebody have a clue what is the reason for that ?

[I am using OpenCl 1.2 with NVIDIA GPU on Ubuntu]

答: OpenCL implementations need to spawn threads internally to support different features, such as monitoring device kernel execution or memory transfers, or to execute the user callbacks. This behaviour is implementation defined, so different implementations may spawn different number of threads.</p>