问:
unable to select items in object in react component
in my redux action i have a fetch that works great. i'm using redux-thunk to dispatch it to my reducer. I then obviously connect my component to the store. within my reactjs component i am able to see the json object. lets say the structure is

```<code>object:{
    person: {
        name: {
            first: "first",
            last: "last"
    }
  }
}
</code>```

when I try to obtain just the first name like (person.name.first) it says "TypeError: Cannot read property 'first' of undefined" but first is defined. basically any information that is three items deep it gives me the same message.
When looking in my react component the issue is within the console.log(). the issue is happening anywhere within the component that i try to access the same location of the object not just within the console.log().

my Action:

```<code>import { WEEKWEATHER,
    TODAYWEATHER,
    SEARCH,
    LOCATIONERROR
} from './types';

//autolocate on page load
 export const autoLocate = (location) => {
 const url =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/geolookup/q/' +
 location + '.json'

 return (dispatch) => {

          fetch(url)
             .then((response) => response.json())
             .then(response => forcast(dispatch, response))
             .catch( (error) => { dispatch({ type:LOCATIONERROR }) })
};
};

//locate with search bar
 export const Locate = (location) => {
 const url =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/geolookup/q/' +
 location + '.json'

 return (dispatch) => {
 dispatch({type: SEARCH,
          payload: location
          });

          fetch(url)
            .then((response) => response.json())
            .then(response => forcast(dispatch, response))
            .catch( (error) => { dispatch({ type:LOCATIONERROR }) })

};
};

//gathering forcast data from either auto or typed info
 const forcast = (dispatch, response) => {
 const location = response.location.zip
 const tenDayUrl =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/forecast10day/q/'
 + location + '.json'
    const todayUrl =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/hourly/q/' +
 location + '.json'

 fetch(todayUrl)
   .then((response) => response.json())
   .then(response => dispatch({
                               type: TODAYWEATHER,
                               payload: response.hourly_forecast[0]
                             }))
   .catch( (error) => { dispatch({ type:LOCATIONERROR }) })

   fetch(tenDayUrl)
     .then((response) => response.json())
     .then(response => dispatch({
                                 type: WEEKWEATHER,
                                 payload:
 response.forecast.simpleforecast.forecastday[0]
                               }))
   .catch( (error) => { dispatch({ type:LOCATIONERROR }) })

 };
</code>```

my reducer:

```<code>import { TODAYWEATHER,  WEEKWEATHER, LOCATIONERROR, SEARCH } from
'../Actions/types';

const INITIAL_STATE =  {
    week:[],
};
export default (state = INITIAL_STATE, action) => {
    switch (action.type){
        case WEEKWEATHER:
        return{ ...state, week:action.payload, loading:false }
                return state;
        }

    };
</code>```

my react componenet:

```<code>import React, { Component }     from 'react';
import { connect }              from 'react-redux';
import { Locate, autoLocate }   from '../Actions';
import {Card} from './Common'

class Weather extends Component{
    constructor(props){
        super(props);
        this.state={

         };
    }
    render() {
        const Loading = <Card>Loading...</Card>

        const Weather =  <div style={styles.PositionColumn}>
                            <div>tuesday</div>
                                <Card>
                                    <div style={styles.flexColumn}>
                                        <div style={styles.flexRow}>
                                            <div>jklsjdfkls</div>
                                            <div>2jlsfjle</div>
                                        </div>
                                        <div style={styles.flexRow}>
                                           <div>11</div>
                                            <div>22</div>
                                        </div>
                                    </div>
                                </Card>
                            </div>

        const displayWeather = (this.props.loading === true)? Loading
: Weather;

        console.log(this.props.week.date.day)

        return(
           <div>
                <img style={styles.Background} src=
{this.state.background} alt=''/>

                    {displayWeather}

            </div>
        );
    }
}

const mapStateToProps = state => {
    const week = state.locate.week;

        return{ week };
}

export default connect(mapStateToProps, {Locate, autoLocate})(Weather)
</code>```

答:
You need to initialise your default state with reducers.</p>

```<code>const INITIAL_STATE= {person : { name : {} }}
</code>```

Body:
in my redux action i have a fetch that works great. i'm using redux-thunk to dispatch it to my reducer. I then obviously connect my component to the store. within my reactjs component i am able to see the json object. lets say the structure is

object:{
    person: {
        name: {
            first: "first",
            last: "last"
    }
  }
}

when I try to obtain just the first name like (person.name.first) it says "TypeError: Cannot read property 'first' of undefined" but first is defined. basically any information that is three items deep it gives me the same message.
When looking in my react component the issue is within the console.log(). the issue is happening anywhere within the component that i try to access the same location of the object not just within the console.log().

my Action:

import { WEEKWEATHER,
    TODAYWEATHER,
    SEARCH,
    LOCATIONERROR
} from './types';

//autolocate on page load
 export const autoLocate = (location) => {
 const url =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/geolookup/q/' +
 location + '.json'

 return (dispatch) => {

          fetch(url)
             .then((response) => response.json())
             .then(response => forcast(dispatch, response))
             .catch( (error) => { dispatch({ type:LOCATIONERROR }) })
};
};

//locate with search bar
 export const Locate = (location) => {
 const url =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/geolookup/q/' +
 location + '.json'

 return (dispatch) => {
 dispatch({type: SEARCH,
          payload: location
          });

          fetch(url)
            .then((response) => response.json())
            .then(response => forcast(dispatch, response))
            .catch( (error) => { dispatch({ type:LOCATIONERROR }) })

};
};

//gathering forcast data from either auto or typed info
 const forcast = (dispatch, response) => {
 const location = response.location.zip
 const tenDayUrl =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/forecast10day/q/'
 + location + '.json'
    const todayUrl =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/hourly/q/' +
 location + '.json'

 fetch(todayUrl)
   .then((response) => response.json())
   .then(response => dispatch({
                               type: TODAYWEATHER,
                               payload: response.hourly_forecast[0]
                             }))
   .catch( (error) => { dispatch({ type:LOCATIONERROR }) })

   fetch(tenDayUrl)
     .then((response) => response.json())
     .then(response => dispatch({
                                 type: WEEKWEATHER,
                                 payload:
 response.forecast.simpleforecast.forecastday[0]
                               }))
   .catch( (error) => { dispatch({ type:LOCATIONERROR }) })

 };

my reducer:

import { TODAYWEATHER,  WEEKWEATHER, LOCATIONERROR, SEARCH } from
'../Actions/types';

const INITIAL_STATE =  {
    week:[],
};
export default (state = INITIAL_STATE, action) => {
    switch (action.type){
        case WEEKWEATHER:
        return{ ...state, week:action.payload, loading:false }
                return state;
        }

    };

my react componenet:

import React, { Component }     from 'react';
import { connect }              from 'react-redux';
import { Locate, autoLocate }   from '../Actions';
import {Card} from './Common'

class Weather extends Component{
    constructor(props){
        super(props);
        this.state={

         };
    }
    render() {
        const Loading = <Card>Loading...</Card>

        const Weather =

tuesday

                                <Card>

jklsjdfkls

2jlsfjle

11

22

                                </Card>

        const displayWeather = (this.props.loading === true)? Loading
: Weather;

        console.log(this.props.week.date.day)

        return(

                    {displayWeather}

        );
    }
}

const mapStateToProps = state => {
    const week = state.locate.week;

        return{ week };
}

export default connect(mapStateToProps, {Locate, autoLocate})(Weather)

Body:
You need to initialise your default state with reducers.

const INITIAL_STATE= {person : { name : {} }}


来源: stackexchange

问:
Draw dashed and dotted rectangles on canvas in the same way css border works: draw 4 same edges
My use-case is to mimic css border rendering. Is it possible, using the CanvasRenderingContext2D::rect method with CanvasRenderingContext2D::setLineDash to simulate same border drawing as css renderer does, like border: 5px dashed red. Consider this example:

let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
ctx.lineWidth = 5
ctx.strokeStyle = 'red'
ctx.lineCap = 'square'
ctx.setLineDash([10, 10]);
ctx.beginPath();
ctx.moveTo(2.5,2.5);
ctx.rect(2.5, 2.5, 195, 65);
ctx.stroke();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  border: 5px dashed red;
  width: 200px;
  height: 70px;
  box-sizing: border-box;
  margin-bottom: 5px;
}

canvas {
  display: block;
  width: 200px;
  height: 70px;
}</code>```

<canvas width=200 height=70></canvas>```

You may notice the problem is on edges.

I was trying to modify the gaps and dash sizes, but it seems impossible to get the same behaviour as in the css example: the lines on edges are bigger then the lines on the sides. As a workaround I can imagine to draw every side with a line, but I would like to use the rect method to draw in one stroke.

Thank you in advance.

答:
CSS border-style: dashed algorithm is not tied by specs, so it will be impossible to render exactly the same in the canvas API.

Then, you've got to know that even CSS renders it line by line: border is a shorthand for all the border-top-XXX, border-right-XXX, border-bottom-XXX, border-left-XXX.

And that's why it behaves like that : each border has its line-dash set independently of the others.

Anyway, if you want to do it with the canvas API, the easiest solution is to do the same, using four lines, and setting their line-dash separately.

Here is a rough attempt at normalizing the dashes in order to get them always start and end at edges:

var ctx = c.getContext('2d');
ctx.lineCap = 'square';

// returns a normalized dashArray per segment
// This in no way does the same as any browser's implementation,
// this is just a lazy way to always get dashes start and end at edges
function getLineDash(x1, y1, x2, y2) {
  var length = Math.hypot((x2 - x1), (y2 - y1));
  var dash_length = length / 8;
  var nb_of_dashes = length / dash_length;
  var dash_gap = (dash_length * 0.66);
  dash_length -= dash_gap * 0.33;
  return [dash_length, dash_gap];
}

function draw() {
  ctx.lineWidth = lineWidth_.value;
  ctx.clearRect(0, 0, c.width, c.height);

  var points = [
    [x1_.value, y1_.value],
    [x2_.value, y2_.value],
    [x3_.value, y3_.value],
    [x4_.value, y4_.value]
  ];

  points.forEach(function(pt, i) {
    var next = points[(i + 1) % points.length];
    ctx.beginPath();
    ctx.moveTo(pt[0], pt[1]);
    ctx.lineTo(next[0], next[1]);
    ctx.setLineDash(getLineDash(pt[0], pt[1], next[0], next[1]));
    ctx.stroke();
  });

}

draw();
document.oninput = function(e) {
  if (e.target.parentNode.parentNode === inputs_) {
    draw();
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label {
  display: inline-block;
}

input {
  max-width: 50px;
}</code>```

  x1<input type="number" id="x1_" value="10">
  y1<input type="number" id="y1_" value="25">
  x2<input type="number" id="x2_" value="350">
  y2<input type="number" id="y2_" value="25">
  x3<input type="number" id="x3_" value="350">
  y3<input type="number" id="y3_" value="225">
  x4<input type="number" id="x4_" value="10">
  y4<input type="number" id="y4_" value="225">
  lineWidth<input type="number" id="lineWidth_" value="3">

<canvas id="c" width="400" height="400"></canvas>```
</div>
</div>
</p>

<hr>

<p>So now, if you only want to use <code>XXXRect</code>, you can also create a single huge dash-array containing all of the dashes...</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var ctx = c.getContext('2d');
ctx.lineCap = 'square';

function getRectDashes(width, height) {
  var w_array = getLineDashes(width, 0, 0, 0);
  var h_array = getLineDashes(0, height, 0, 0);
  dashArray = [].concat.apply([], [w_array, 0, h_array, 0, w_array, 0, h_array]);
  return dashArray;
}
// same as previous snippet except that it does return all the segment's dashes
function getLineDashes(x1, y1, x2, y2) {
  var length = Math.hypot((x2 - x1), (y2 - y1));
  var dash_length = length / 8;
  var nb_of_dashes = length / dash_length;

  var dash_gap = dash_length * 0.66666;
  dash_length -= dash_gap * 0.3333;

  var total_length = 0;
  var dasharray = [];
  var next;
  while (total_length < length) {
    next = dasharray.length % 2 ? dash_gap : dash_length;
    total_length += next;
    dasharray.push(next);
  }
  return dasharray;
}

function draw() {
  ctx.clearRect(0, 0, c.width, c.height);
  ctx.lineWidth = lineWidth_.value;
  var w = width_.value,
    h = height_.value;
  ctx.setLineDash(getRectDashes(w, h));
  ctx.strokeRect(20, 20, w, h);
}
draw();
document.oninput = function(e) {
  if (e.target.parentNode.parentNode === inputs_)
    draw();
};</code>```

label {
  display: inline-block;
}

input {
  max-width: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="inputs_">
  <label>width<input type="number" id="width_" value="200"></label>
  <label>height<input type="number" id="height_" value="225"></label>
  <label>lineWidth<input type="number" id="lineWidth_" value="3"></label>
</div>
<canvas id="c" width="400" height="400"></canvas></code>```

ContentLicense: CC BY-SA 3.0

Body:
My use-case is to mimic css border rendering. Is it possible, using the CanvasRenderingContext2D::rect method with CanvasRenderingContext2D::setLineDash to simulate same border drawing as css renderer does, like border: 5px dashed red. Consider this example:

let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
ctx.lineWidth = 5
ctx.strokeStyle = 'red'
ctx.lineCap = 'square'
ctx.setLineDash([10, 10]);
ctx.beginPath();
ctx.moveTo(2.5,2.5);
ctx.rect(2.5, 2.5, 195, 65);
ctx.stroke();

div {
  border: 5px dashed red;
  width: 200px;
  height: 70px;
  box-sizing: border-box;
  margin-bottom: 5px;
}

canvas {
  display: block;
  width: 200px;
  height: 70px;
}

<canvas width=200 height=70></canvas>

You may notice the problem is on edges.

I was trying to modify the gaps and dash sizes, but it seems impossible to get the same behaviour as in the css example: the lines on edges are bigger then the lines on the sides. As a workaround I can imagine to draw every side with a line, but I would like to use the rect method to draw in one stroke.

Thank you in advance.

Body:
CSS border-style: dashed algorithm is not tied by specs, so it will be impossible to render exactly the same in the canvas API.

Then, you've got to know that even CSS renders it line by line: border is a shorthand for all the border-top-XXX, border-right-XXX, border-bottom-XXX, border-left-XXX.

And that's why it behaves like that : each border has its line-dash set independently of the others.

Anyway, if you want to do it with the canvas API, the easiest solution is to do the same, using four lines, and setting their line-dash separately.

Here is a rough attempt at normalizing the dashes in order to get them always start and end at edges:

var ctx = c.getContext('2d');
ctx.lineCap = 'square';

// returns a normalized dashArray per segment
// This in no way does the same as any browser's implementation,
// this is just a lazy way to always get dashes start and end at edges
function getLineDash(x1, y1, x2, y2) {
  var length = Math.hypot((x2 - x1), (y2 - y1));
  var dash_length = length / 8;
  var nb_of_dashes = length / dash_length;
  var dash_gap = (dash_length * 0.66);
  dash_length -= dash_gap * 0.33;
  return [dash_length, dash_gap];
}

function draw() {
  ctx.lineWidth = lineWidth_.value;
  ctx.clearRect(0, 0, c.width, c.height);

  var points = [
    [x1_.value, y1_.value],
    [x2_.value, y2_.value],
    [x3_.value, y3_.value],
    [x4_.value, y4_.value]
  ];

  points.forEach(function(pt, i) {
    var next = points[(i + 1) % points.length];
    ctx.beginPath();
    ctx.moveTo(pt[0], pt[1]);
    ctx.lineTo(next[0], next[1]);
    ctx.setLineDash(getLineDash(pt[0], pt[1], next[0], next[1]));
    ctx.stroke();
  });

}

draw();
document.oninput = function(e) {
  if (e.target.parentNode.parentNode === inputs_) {
    draw();
  }
}

label {
  display: inline-block;
}

input {
  max-width: 50px;
}

<div id="inputs_">
  <label>x1<input type="number" id="x1_" value="10"></label>
  <label>y1<input type="number" id="y1_" value="25"></label>
  <label>x2<input type="number" id="x2_" value="350"></label>
  <label>y2<input type="number" id="y2_" value="25"></label>
  <label>x3<input type="number" id="x3_" value="350"></label>
  <label>y3<input type="number" id="y3_" value="225"></label>
  <label>x4<input type="number" id="x4_" value="10"></label>
  <label>y4<input type="number" id="y4_" value="225"></label>
  <label>lineWidth<input type="number" id="lineWidth_" value="3"></label>

</div>
<canvas id="c" width="400" height="400"></canvas>

So now, if you only want to use XXXRect, you can also create a single huge dash-array containing all of the dashes...

var ctx = c.getContext('2d');
ctx.lineCap = 'square';

function getRectDashes(width, height) {
  var w_array = getLineDashes(width, 0, 0, 0);
  var h_array = getLineDashes(0, height, 0, 0);
  dashArray = [].concat.apply([], [w_array, 0, h_array, 0, w_array, 0, h_array]);
  return dashArray;
}
// same as previous snippet except that it does return all the segment's dashes
function getLineDashes(x1, y1, x2, y2) {
  var length = Math.hypot((x2 - x1), (y2 - y1));
  var dash_length = length / 8;
  var nb_of_dashes = length / dash_length;

  var dash_gap = dash_length * 0.66666;
  dash_length -= dash_gap * 0.3333;

  var total_length = 0;
  var dasharray = [];
  var next;
  while (total_length < length) {
    next = dasharray.length % 2 ? dash_gap : dash_length;
    total_length += next;
    dasharray.push(next);
  }
  return dasharray;
}

function draw() {
  ctx.clearRect(0, 0, c.width, c.height);
  ctx.lineWidth = lineWidth_.value;
  var w = width_.value,
    h = height_.value;
  ctx.setLineDash(getRectDashes(w, h));
  ctx.strokeRect(20, 20, w, h);
}
draw();
document.oninput = function(e) {
  if (e.target.parentNode.parentNode === inputs_)
    draw();
};

label {
  display: inline-block;
}

input {
  max-width: 50px;
}

<div id="inputs_">
  <label>width<input type="number" id="width_" value="200"></label>
  <label>height<input type="number" id="height_" value="225"></label>
  <label>lineWidth<input type="number" id="lineWidth_" value="3"></label>
</div>
<canvas id="c" width="400" height="400"></canvas>


问:
Phonegap build fails with splash screen
I'm attempting to use the new phonegap build with CLI 7.0.1

The build fails with this error:

```<code>The following build commands failed:
    CompileAssetCatalog /Library/Developer/Xcode/DerivedData/Our_HNZC_Learning_space-ddfmniquktwfmabpvilymbvzreak/Build/Intermediates/ArchiveIntermediates/Our\ HNZC\ Learning\ space/InstallationBuildProductsLocation/Applications/Our\ HNZC\ Learning\ space.app Our\ HNZC\ Learning\ space/Images.xcassets
(1 failure)
Error code 65 for command: xcodebuild with args: -xcconfig,/private/project/cordova/build-release.xcconfig,-workspace,Our HNZC Learning space.xcworkspace,-scheme,Our HNZC Learning space,-configuration,Release,-destination,generic/platform=iOS,-archivePath,Our HNZC Learning space.xcarchive,archive,CONFIGURATION_BUILD_DIR=/private/project/build/device,SHARED_PRECOMPS_DIR=/private/project/build/sharedpch
</code>```

I've added these to config.png

```<code><icon src="res/icon.png" />
<splash src="res/splash.png" />
</code>```

And I've added this plugin

```<code><plugin name="cordova-plugin-splashscreen" />
</code>```

And the files are in the right place.

Splash works fine, Icon is causing the error

答:
Not sure what the exact problem is based upon the info you provided.

A starting point would be to remove the splashscreen plugin and re-add it:

```<code>cordova plugin remove cordova-plugin-splashscreen
cordova plugin add cordova-plugin-splashscreen
cordova prepare
</code>```

I would suggest using an Icon and Splashscreen generator such as this one: http://phonegap.appiq.software/

It does all of the hard work for you and gives you the exact code for your config.xml

I hope this is helpful.

Title: Phonegap build fails with splash screen

Body:
I'm attempting to use the new phonegap build with CLI 7.0.1

The build fails with this error:

The following build commands failed:
    CompileAssetCatalog /Library/Developer/Xcode/DerivedData/Our_HNZC_Learning_space-ddfmniquktwfmabpvilymbvzreak/Build/Intermediates/ArchiveIntermediates/Our\ HNZC\ Learning\ space/InstallationBuildProductsLocation/Applications/Our\ HNZC\ Learning\ space.app Our\ HNZC\ Learning\ space/Images.xcassets
(1 failure)
Error code 65 for command: xcodebuild with args: -xcconfig,/private/project/cordova/build-release.xcconfig,-workspace,Our HNZC Learning space.xcworkspace,-scheme,Our HNZC Learning space,-configuration,Release,-destination,generic/platform=iOS,-archivePath,Our HNZC Learning space.xcarchive,archive,CONFIGURATION_BUILD_DIR=/private/project/build/device,SHARED_PRECOMPS_DIR=/private/project/build/sharedpch

I've added these to config.png

<icon src="res/icon.png" />
<splash src="res/splash.png" />

And I've added this plugin

<plugin name="cordova-plugin-splashscreen" />

And the files are in the right place.

Splash works fine, Icon is causing the error

Body:
Not sure what the exact problem is based upon the info you provided.

A starting point would be to remove the splashscreen plugin and re-add it:

cordova plugin remove cordova-plugin-splashscreen
cordova plugin add cordova-plugin-splashscreen
cordova prepare

I would suggest using an Icon and Splashscreen generator such as this one: http://phonegap.appiq.software/

It does all of the hard work for you and gives you the exact code for your config.xml

I hope this is helpful.


问:
C++ loop stack allocation
While doing an assignment for a course and learning C++ while doing it, I was reading up on when to use stack allocation and dynamic allocation. I'm aware that in a lot of cases it is easier and better to use stack allocation. But there is a simple situation I'm puzzeled about.

Lets say you have a for loop:

```<code>for(int i = 0; i < 10; i++)
{
   MyObject obj(file);
   obj.doSomething();
}
</code>```

Now the problem is that if the Object contains state, it keeps it state (stays the same object) while iterating through the iterations from 1 til 10. Maybe coming from a Java/C# background gets me on the wrong path. But I only see two ways of solving this:

Using dynamic memory.

Not giving file to the constructor but instead to the method doSomething(file) but this isn't very nice if you have more than one method manipulating the file object e.g. doSomethingElse(file).

So what do you guys do in such a situation, or do you never get yourself in such a situation at all?

Update:
Turns out i misunderstood and it is working as expected. Check the awnsers below! Thanks everyone

答:
Wouldn't the following still allocate your object on the surrounding stack and accomplish what you are after?</p>

```<code>MyObject obj(file);
for (int i = 0; i < 10; i++)
{
  obj.doSomething();
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: C++ loop stack allocation

Body:
While doing an assignment for a course and learning C++ while doing it, I was reading up on when to use stack allocation and dynamic allocation. I'm aware that in a lot of cases it is easier and better to use stack allocation. But there is a simple situation I'm puzzeled about.

Lets say you have a for loop:

for(int i = 0; i < 10; i++)
{
   MyObject obj(file);
   obj.doSomething();
}

Now the problem is that if the Object contains state, it keeps it state (stays the same object) while iterating through the iterations from 1 til 10. Maybe coming from a Java/C# background gets me on the wrong path. But I only see two ways of solving this:

Using dynamic memory.

Not giving file to the constructor but instead to the method doSomething(file) but this isn't very nice if you have more than one method manipulating the file object e.g. doSomethingElse(file).

So what do you guys do in such a situation, or do you never get yourself in such a situation at all?

Update:
Turns out i misunderstood and it is working as expected. Check the awnsers below! Thanks everyone

Body:
Wouldn't the following still allocate your object on the surrounding stack and accomplish what you are after?

MyObject obj(file);
for (int i = 0; i < 10; i++)
{
  obj.doSomething();
}


问:
How to find the row number of a value in filtered sheet in only visible cells?
I used following syntax, but its not working. Please any one help on this.</p>

```<code>minrow = Application.WorksheetFunction.Match(mindat, Sheets("Inventory").Range("G2:G1000").SpecialCells(xlCellTypeVisible), 0)
</code>```

答:
Try this:</p>

```<code>On Error Resume Next
Dim SearchRange as Range
Set SearchRange = Sheets("Inventory").Range("G2:G1000").SpecialCells(xlCellTypeVisible)
On Error GoTo 0

If Not SearchRange is Nothing Then

    Dim FoundCell as Range
    Set FoundCell = SearchRange.Find(mindat, lookat:=xlWhole)

    If Not FoundCell is Nothing Then
        minrow = FoundCell.Row
    End If

End If
</code>```

Body:
I used following syntax, but its not working. Please any one help on this.

minrow = Application.WorksheetFunction.Match(mindat, Sheets("Inventory").Range("G2:G1000").SpecialCells(xlCellTypeVisible), 0)

Body:
Try this:

On Error Resume Next
Dim SearchRange as Range
Set SearchRange = Sheets("Inventory").Range("G2:G1000").SpecialCells(xlCellTypeVisible)
On Error GoTo 0

If Not SearchRange is Nothing Then

    Dim FoundCell as Range
    Set FoundCell = SearchRange.Find(mindat, lookat:=xlWhole)

    If Not FoundCell is Nothing Then
        minrow = FoundCell.Row
    End If

End If


问:
Adding Home button in html page
In my webapplication I am trying to add home button in all the sub pages which on clicking will trigger ActionResult Index()
Any suggestions?

I have simply added a button in my Sub page DetailsForm. Which is next to the submit button. After user is done saving user can click on home button to directly got to the Index.cshtml. Avoiding any Browser back button.
Below code definitely doesn't work for me!

```<code>  <input type="button" class="btn btn-lg btn-success" onclick="location.href='index.cshtml';" value="Home" />
</code>```

答:
If you have CSS enabled use the a tag so style will be consistent and try

Home

And in CSS make sure you have your button class designed.

```<code>a.button {
    -webkit-appearance: button;
    -moz-appearance: button;
    appearance: button;

    text-decoration: none;
    color: initial;
}
</code>```

EDIT

From the error code you provided, it seems like you are most likely trying to use a library you haven't installed or installed correctly. I believe you are missing the Bootstrap Buttons library which can be found here. If you need help installing, instructions can be found in their installation docs.

Title: Adding Home button in html page

Body:
In my webapplication I am trying to add home button in all the sub pages which on clicking will trigger ActionResult Index()
Any suggestions?

I have simply added a button in my Sub page DetailsForm. Which is next to the submit button. After user is done saving user can click on home button to directly got to the Index.cshtml. Avoiding any Browser back button.
Below code definitely doesn't work for me!

  <input type="button" class="btn btn-lg btn-success" onclick="location.href='index.cshtml';" value="Home" />

Body:
If you have CSS enabled use the a tag so style will be consistent and try

<a href="/link-to-index" class="button">Home</a>

And in CSS make sure you have your button class designed.

a.button {
    -webkit-appearance: button;
    -moz-appearance: button;
    appearance: button;

    text-decoration: none;
    color: initial;
}

EDIT

From the error code you provided, it seems like you are most likely trying to use a library you haven't installed or installed correctly. I believe you are missing the Bootstrap Buttons library which can be found here. If you need help installing, instructions can be found in their installation docs.


问:
Admin Panel for Laravel + Angular
Now I'm building web project using Laravel (API) + Angular.
And I need to add admin panel on my project now.
I'm thinking 2 ways to do this.

Admin Panel in Laravel

Admin Panel in Angular

Which is the recommended way to add Admin panel in my project?
And Why?

Please help me.

Thanks.

答:
You can do it in the way you want. If you have more experience with Angular, then there will be easier for you using that framework, if not, if you want to render the views and data directly from the server, you use Laravel directly isntead.

IMHO, doing it directly with Laravel is a little bit easier but you face some limitations, ok no limitations but to achieve more complex things or behaviors it will be easier to do it with Angular or Vue, with those tools you have special components and a lot of resources on the web. At the end of the day, all will be reduced to the complexity of the Admin that you want to build and to your experience withe the tools mencioned above.

As I said, this is just my opinion.

Title: Admin Panel for Laravel + Angular


问:
Dynamicimage saving black on IIS
After reinstalling my computer with new windows, an problem occurs with an existing website routine that runs in my computer/IIS.

Using the library DynamicImage (https://github.com/tgjones/dynamic-image) my routines always worked but now saves the image as an black image.

When running from Visual Studio with IIS Express still works fine, no problem.
After deploying to my IIS it generates an black image without raising an exception.

I tried to mimmic IIS Express in IIS so i configure the apppool to use my user but still saving an black image.

Looked at event viewer and no error message.

I simplified the code and made an simple form to test, still black image on IIS and ok on IIS Express

Any help, idea or what to verifiy is appreciate.

Code test:

```<code>using SoundInTheory.DynamicImage;
using SoundInTheory.DynamicImage.Filters;
using SoundInTheory.DynamicImage.Layers;

protected void Button1_Click(object sender, EventArgs e)
{
    ImageLayer layer = new ImageLayer { SourceFileName = "f:\\backdb\\a1.jpg" };
    Composition composition = new Composition();
    composition.ImageFormat = DynamicImageFormat.Bmp;
    layer.Filters.Add(new BorderFilter { Width =20, Fill = new Fill { BackgroundColor = SoundInTheory.DynamicImage.Colors.Green }});
    composition.Layers.Add(layer);
    GeneratedImage img = composition.GenerateImage();
    img.Save("f:\\backdb\\img.jpg"); // BLACK IMAGE ON IIS - Image OK on IIS EXPRESS
}
</code>```

答:
Fixed..

1st - I reinstalled IIS cleaning the directories.

2nd - The line "composition.ImageFormat = DynamicImageFormat.Bmp;" wasn't in the old instalation, was an try to fix probably mimetype, but was saying it as BMP and the filename as JPG, changed to DynamicImageFormat.Jpeg and now everything is ok.

Title: Dynamicimage saving black on IIS

Body:
After reinstalling my computer with new windows, an problem occurs with an existing website routine that runs in my computer/IIS.

Using the library DynamicImage (https://github.com/tgjones/dynamic-image) my routines always worked but now saves the image as an black image.

When running from Visual Studio with IIS Express still works fine, no problem.
After deploying to my IIS it generates an black image without raising an exception.

I tried to mimmic IIS Express in IIS so i configure the apppool to use my user but still saving an black image.

Looked at event viewer and no error message.

I simplified the code and made an simple form to test, still black image on IIS and ok on IIS Express

Any help, idea or what to verifiy is appreciate.

Code test:

using SoundInTheory.DynamicImage;
using SoundInTheory.DynamicImage.Filters;
using SoundInTheory.DynamicImage.Layers;

protected void Button1_Click(object sender, EventArgs e)
{
    ImageLayer layer = new ImageLayer { SourceFileName = "f:\\backdb\\a1.jpg" };
    Composition composition = new Composition();
    composition.ImageFormat = DynamicImageFormat.Bmp;
    layer.Filters.Add(new BorderFilter { Width =20, Fill = new Fill { BackgroundColor = SoundInTheory.DynamicImage.Colors.Green }});
    composition.Layers.Add(layer);
    GeneratedImage img = composition.GenerateImage();
    img.Save("f:\\backdb\\img.jpg"); // BLACK IMAGE ON IIS - Image OK on IIS EXPRESS
}


问:
How to add header X-XSS-Protection 1; mode=block via appcmd
I am able to add the below mentioned header via UI in IIS and other simple headers via command line (appcmd), but this one seems cryptic.. not able to get it. Throwing syntax errors whatever i try. Any help is appreciated ...

X-XSS-Protection
1; mode=block

答:
Looks like i found it </p>

<p>%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/httpProtocol /+"customHeaders.[name='X-XSS-Protection',value='1; mode=block']"</p>

Body:
Looks like i found it

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/httpProtocol /+"customHeaders.[name='X-XSS-Protection',value='1; mode=block']"


问:
Atom editor: How to jump back and forward
I'm used to PHP Storm where you can easily jump back and forwards to where the cursor previously was.
Is there such a feature in the atom editor?</p>

答:
An extra step for those who got used to toolbars in IDEs: to add "back" and "forward" actions to toolbar, I've installed these two packages in addition to last-cursor-position mentioned above:

https://atom.io/packages/tool-bar

https://atom.io/packages/flex-tool-bar

Then edited the tool bar (there is a gear button on default flex toolbar for this) by adding two buttons that refer to last-cursor-position shortcuts:

```<code>{
  type: "button"
  icon: "arrow-left"
  callback: "last-cursor-position:previous"
  tooltip: "Back"
}
{
  type: "button"
  icon: "arrow-right"
  callback: "last-cursor-position:next"
  tooltip: "Forward"
}
</code>```

Got this toolbar

Body:
An extra step for those who got used to toolbars in IDEs: to add "back" and "forward" actions to toolbar, I've installed these two packages in addition to last-cursor-position mentioned above:

https://atom.io/packages/tool-bar

https://atom.io/packages/flex-tool-bar

Then edited the tool bar (there is a gear button on default flex toolbar for this) by adding two buttons that refer to last-cursor-position shortcuts:

{
  type: "button"
  icon: "arrow-left"
  callback: "last-cursor-position:previous"
  tooltip: "Back"
}
{
  type: "button"
  icon: "arrow-right"
  callback: "last-cursor-position:next"
  tooltip: "Forward"
}

Got this toolbar


问:
Receptive fields calculous for spiking neural networks in python
I'd like to calculate the receptive fields (e.g. Gaussian) for spiking neural networks in python. Let's say that I want to encode the iris data set and transform it into spike trains. I work with Brian framework, and I'm looking for a way to encode my data sets.

Is there any way to do it automatically? Or even any site explaining the trasnformation process? I've read several papers but this process is explained partially ...

Thanks in advance

答:
For overlapping Gaussian RF, you need to know the minimum (I_min) and maximum (I_max) for each variable. Then, (again for each variable) you create an array of N input neurons located at the peaks of N overlapping Gaussians. Use the following formulas to space out the neurons evenly over the variable range (this is of course pseudocode):

```<code>range = I_max - I_min
for (i = 1..N)
    gaussian_i_mean = I_min + range * (2*i - 3) / (2 * (N - 2))
    gaussian_i_sd = range / (beta * (N - 2))
end for
</code>```

beta controls the width of the Gaussian. See this paper for more details.

Body:
For overlapping Gaussian RF, you need to know the minimum (I_min) and maximum (I_max) for each variable. Then, (again for each variable) you create an array of N input neurons located at the peaks of N overlapping Gaussians. Use the following formulas to space out the neurons evenly over the variable range (this is of course pseudocode):

range = I_max - I_min
for (i = 1..N)
    gaussian_i_mean = I_min + range * (2*i - 3) / (2 * (N - 2))
    gaussian_i_sd = range / (beta * (N - 2))
end for

beta controls the width of the Gaussian. See this paper for more details.


问:
unzipping a file in cocoa
I have a zipped file, which i want to extract the contents of it. What is the exact procedure that i should do to achieve it. Is there any framework to unzip the files in cocoa framework or objective C.    </p>

答:
If you are on iOS or don't want to use NSTask or whatever, I recommend my library SSZipArchive.

Usage:

```<code>NSString *path = @"path_to_your_zip_file";
NSString *destination = @"path_to_the_folder_where_you_want_it_unzipped";
[SSZipArchive unzipFileAtPath:path toDestination:destination];
</code>```

Pretty simple.

Title: unzipping a file in cocoa

Body:
If you are on iOS or don't want to use NSTask or whatever, I recommend my library SSZipArchive.

Usage:

NSString *path = @"path_to_your_zip_file";
NSString *destination = @"path_to_the_folder_where_you_want_it_unzipped";
[SSZipArchive unzipFileAtPath:path toDestination:destination];

Pretty simple.


问:
how to recurse over singly linked list with a function that takes no parameters
I'm trying to recursively loop over a singly linked-list but I have to use a function that takes no parameters and I'm a little confused how to do that. My thought process was that I would just keep passing in the modified list to the function but that's not what the problem asks for. This is the question:

Suppose that you have a singly linked list of ints without header, with the following class definition:

```<code>class IntList {
    int value;
    IntList next;
}
</code>```

Write a recursive, owned method l.sumOfList() which:

destructively replaces the value at each node in the list with the sum of the values of the list starting at that point.

should return the sum of the values in the original list. For instance, if l is initially the list [3,2,1], and you call l.sumOfList() then l becomes the list [6=(3+2+1), 3(=2+1), 1].

I'm just not sure how to write a recursive function with no
  parameters? Or how to work with a linked list without a header.

答:
You can keep a class variable and use it in your recursive function. Something like;</p>

```<code>class TraverseInt {
IntList node = start; // start of the linked list

public void traverse() {
    if(node == null)
        return;
    System.out.println(node.value);
    node = node.next;
    traverse();
}
}
</code>```

Body:
I'm trying to recursively loop over a singly linked-list but I have to use a function that takes no parameters and I'm a little confused how to do that. My thought process was that I would just keep passing in the modified list to the function but that's not what the problem asks for. This is the question:

Suppose that you have a singly linked list of ints without header, with the following class definition:

class IntList {
    int value;
    IntList next;
}

Write a recursive, owned method l.sumOfList() which:

destructively replaces the value at each node in the list with the sum of the values of the list starting at that point.

should return the sum of the values in the original list. For instance, if l is initially the list [3,2,1], and you call l.sumOfList() then l becomes the list [6=(3+2+1), 3(=2+1), 1].

I'm just not sure how to write a recursive function with no
  parameters? Or how to work with a linked list without a header.

Body:
You can keep a class variable and use it in your recursive function. Something like;

class TraverseInt {
IntList node = start; // start of the linked list

public void traverse() {
    if(node == null)
        return;
    System.out.println(node.value);
    node = node.next;
    traverse();
}
}


问:
Angularjs - How to prevent user from going to inner pages without logging in and how to store session upon successfull login
I am using angularjs and angularjs ui-route. I am building a login page and I  want to prevent any user to go to inner pages without logging in. I have found a similar question but it lacks information. Also I want to store session upon successful login.

Here is my homeroute.js

```<code>    'use strict';

var application = angular.module('App', ['ui.router']);

    application.config(['$stateProvider', '$urlRouterProvider',
    function($stateProvider, $urlRouterProvider) {

        // For unmatched routes
        $urlRouterProvider.otherwise('/');

        // Application routes
        $stateProvider
            .state('login', {
                url: '/login',
                templateUrl: './views/login.html',
                controller: 'logincontroller'
            })
            .state('/', {
                url: '/',
                templateUrl: './views/home.html'
            })
             .state('customerHome', {
                url: '/customerHome',
                templateUrl: './views/customerHomepage.html'
            })
            .state('signup', {
                url: '/signup',
                templateUrl: './views/register.html',
                controller: 'registercontroller'
            });
    }
]);

        application.run(function($rootScope, $location) {
        var customerHome = ['/customerHome'];
        $rootScope.$on('$routeLogin', function() {
            if(customerHome.indexOf($location.path()) != -1 && sessionStorage.getItem('userLogin')) {
                $location.path('/login');
            }
        });
    });

    application.controller('registercontroller', ['$scope', '$http', function($scope, $http) {
                $scope.formData = {};
                $scope.userform = "";
                $scope.register = function() {
                    $http({
                        method: 'POST',
                        url: './services/loginsubmit.php',
                        data: $scope.formData
                    }).then(function(response) {
                        console.log(response);
                        if(response.data.empty == true) {
                            $scope.userform = "Please fill the form.";
                        } else if(response.data.emailError == true) {
                            $scope.userform = "Invalid Email.";
                        } else if(response.data.validation == true) {
                            $scope.userform = "Username already exists.";
                        } else if(response.data.validateUsername == true) {
                            $scope.userform = "Username must be more than 5 characters.";
                        } else if(response.data.validatePassword == true) {
                            $scope.userform = "Password must be more than 5 characters.";
                        } else if(response.data.registerSuccess == false) {
                            $scope.userform = "Registration Successful.";
                            $scope.formData = {};
                        } else if(response.data.registerSuccess == true) {
                            $scope.userform = "Registration Failed";
                        }
                    });
                }
            }]);

    application.controller('logincontroller', ['$scope', '$http', '$location', '$rootScope', function($scope, $http, $location, $rootScope) {
        $scope.loginData = {};
        $scope.loginUser = "";
        $scope.login = function() {
            $http({
                method: 'POST',
                url: './services/loginservice.php',
                data: $scope.loginData
            }).then(function(response) {
                console.log(response);
                if(response.data.UsernameLogin == true) {
                    $scope.loginUser = "Invalid username or password.";
                } else {
                    sessionStorage.setItem('userLogin', response.data.usernameSession);
                    $location.path('/customerHome');
                }
            });
        }
    }]);
</code>```

Here is my loginservice.php

```<code>    <?php

    include '../connection/connect.php';

    $formLogin = json_decode(file_get_contents("php://input"));

    $data = array();
    $check_UsernameLogin = false;

    $username = $formLogin->username;
    $password = $formLogin->password;

    $login = mysqli_query($conn, "SELECT username FROM customer WHERE username='$username' AND customer_password='$password'");

    $check_username = mysqli_num_rows($login);

    if($check_username == 0) {
        $check_UsernameLogin = true;
    } else {
        $check_UsernameLogin = false;
    }

    $data["UsernameLogin"] = $check_UsernameLogin;
    $data["usernameSession"] = $login;

    echo json_encode($data);

 ?>
</code>```

Here is my login.html

```<code>    <!-- Navigation Bar -->
    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <a class="navbar-brand" href="#!/">Hostelry Service</a>
        </div>
        <ul class="nav navbar-nav">
          <li><a href="#!/">Home</a></li>
          <li><a href="#">Hostelries</a></li>
          <li><a href="#">Compare</a></li>
          <li><a href="#">About Us</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
          <li><a href="#!signup"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
          <li><a href="#!login"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
        </ul>
      </div>
    </nav>
<div class="row"  style="padding-top: 100px;">
  <div class="col-md-4 col-md-offset-4">
    <div class="panel panel-primary">
      <div class="panel-heading" style="padding-left: 190px;">Log in</div>
      <div class="panel-body">
        <form method="POST" ng-submit="login()">
          <input class="form-control" type="text" ng-model="loginData.username" placeholder="Username"><br>
          <input class="form-control" type="password" ng-model="loginData.password" placeholder="Password"><br>
          <button type="submit" class="btn btn-primary btn-block">Submit</button><br>
          <p class="alert alert-success" ng-show="loginUser">{{loginUser}}</p>
        </form>
      </div>
  </div>
</div>
</code>```

Here is my customerHomepage.html

```<code>    <!-- Navigation Bar -->
    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <a class="navbar-brand" href="#!/">Hostelry Service</a>
        </div>
        <ul class="nav navbar-nav">
          <li><a href="#!/">Home</a></li>
          <li><a href="#">Hostelries</a></li>
          <li><a href="#">Compare</a></li>
          <li><a href="#">About Us</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
          <li><a href="#!signup"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
          <li><a href="#!login"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
        </ul>
      </div>
    </nav>
<div class="row"  style="padding-top: 100px;">
  <div class="col-md-4 col-md-offset-4">
    <div class="panel panel-primary">
      <div class="panel-heading" style="padding-left: 190px;">Log in</div>
      <div class="panel-body">
        <form method="POST" ng-submit="login()">
          <input class="form-control" type="text" ng-model="loginData.username" placeholder="Username"><br>
          <input class="form-control" type="password" ng-model="loginData.password" placeholder="Password"><br>
          <button type="submit" class="btn btn-primary btn-block">Submit</button><br>
          <p class="alert alert-success" ng-show="loginUser">{{loginUser}}</p>
        </form>
      </div>
  </div>
</div>
</code>```

I am new to using .run() and $rootScope on angularjs.

答:
In the application.run() , you need to check for state change and prevent or allow state change based on whether the user is logged in or not.For ex:

```<code>        $rootScope.$on('$stateChangeStart', function (event, toState){

            if(toState.name === 'login'){
                return;
            }
            else if (!session.getAccessToken()) {
                $state.go('login');
                event.preventDefault();
            }
            else{
                return;
            }

        });
</code>```

Here session is a service.It checks if the access token is found in the session storage.If not found then it prevents user from going to inner pages.

Now,after making a call to login API from your login page,store the access token form the response into your session storage,and change the state to your desired home page.

NOTE: You might prefer using local storage instead of session storage for storing the access token.

Body:
I am using angularjs and angularjs ui-route. I am building a login page and I  want to prevent any user to go to inner pages without logging in. I have found a similar question but it lacks information. Also I want to store session upon successful login.

Here is my homeroute.js

    'use strict';

var application = angular.module('App', ['ui.router']);

    application.config(['$stateProvider', '$urlRouterProvider',
    function($stateProvider, $urlRouterProvider) {

        // For unmatched routes
        $urlRouterProvider.otherwise('/');

        // Application routes
        $stateProvider
            .state('login', {
                url: '/login',
                templateUrl: './views/login.html',
                controller: 'logincontroller'
            })
            .state('/', {
                url: '/',
                templateUrl: './views/home.html'
            })
             .state('customerHome', {
                url: '/customerHome',
                templateUrl: './views/customerHomepage.html'
            })
            .state('signup', {
                url: '/signup',
                templateUrl: './views/register.html',
                controller: 'registercontroller'
            });
    }
]);

        application.run(function($rootScope, $location) {
        var customerHome = ['/customerHome'];
        $rootScope.$on('$routeLogin', function() {
            if(customerHome.indexOf($location.path()) != -1 && sessionStorage.getItem('userLogin')) {
                $location.path('/login');
            }
        });
    });

    application.controller('registercontroller', ['$scope', '$http', function($scope, $http) {
                $scope.formData = {};
                $scope.userform = "";
                $scope.register = function() {
                    $http({
                        method: 'POST',
                        url: './services/loginsubmit.php',
                        data: $scope.formData
                    }).then(function(response) {
                        console.log(response);
                        if(response.data.empty == true) {
                            $scope.userform = "Please fill the form.";
                        } else if(response.data.emailError == true) {
                            $scope.userform = "Invalid Email.";
                        } else if(response.data.validation == true) {
                            $scope.userform = "Username already exists.";
                        } else if(response.data.validateUsername == true) {
                            $scope.userform = "Username must be more than 5 characters.";
                        } else if(response.data.validatePassword == true) {
                            $scope.userform = "Password must be more than 5 characters.";
                        } else if(response.data.registerSuccess == false) {
                            $scope.userform = "Registration Successful.";
                            $scope.formData = {};
                        } else if(response.data.registerSuccess == true) {
                            $scope.userform = "Registration Failed";
                        }
                    });
                }
            }]);

    application.controller('logincontroller', ['$scope', '$http', '$location', '$rootScope', function($scope, $http, $location, $rootScope) {
        $scope.loginData = {};
        $scope.loginUser = "";
        $scope.login = function() {
            $http({
                method: 'POST',
                url: './services/loginservice.php',
                data: $scope.loginData
            }).then(function(response) {
                console.log(response);
                if(response.data.UsernameLogin == true) {
                    $scope.loginUser = "Invalid username or password.";
                } else {
                    sessionStorage.setItem('userLogin', response.data.usernameSession);
                    $location.path('/customerHome');
                }
            });
        }
    }]);

Here is my loginservice.php

    <?php

    include '../connection/connect.php';

    $formLogin = json_decode(file_get_contents("php://input"));

    $data = array();
    $check_UsernameLogin = false;

    $username = $formLogin->username;
    $password = $formLogin->password;

    $login = mysqli_query($conn, "SELECT username FROM customer WHERE username='$username' AND customer_password='$password'");

    $check_username = mysqli_num_rows($login);

    if($check_username == 0) {
        $check_UsernameLogin = true;
    } else {
        $check_UsernameLogin = false;
    }

    $data["UsernameLogin"] = $check_UsernameLogin;
    $data["usernameSession"] = $login;

    echo json_encode($data);

 ?>

Here is my login.html

          Hostelry Service

Home

Hostelries

Compare

About Us

Contact

 Sign Up

 Login

Log in

        <form method="POST" ng-submit="login()">
          <input class="form-control" type="text" ng-model="loginData.username" placeholder="Username">

          <input class="form-control" type="password" ng-model="loginData.password" placeholder="Password">

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

{{loginUser}}

        </form>

Here is my customerHomepage.html

          Hostelry Service

Home

Hostelries

Compare

About Us

Contact

 Sign Up

 Login

Log in

        <form method="POST" ng-submit="login()">
          <input class="form-control" type="text" ng-model="loginData.username" placeholder="Username">

          <input class="form-control" type="password" ng-model="loginData.password" placeholder="Password">

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

{{loginUser}}

        </form>

I am new to using .run() and $rootScope on angularjs.

Body:
In the application.run() , you need to check for state change and prevent or allow state change based on whether the user is logged in or not.For ex:

        $rootScope.$on('$stateChangeStart', function (event, toState){

            if(toState.name === 'login'){
                return;
            }
            else if (!session.getAccessToken()) {
                $state.go('login');
                event.preventDefault();
            }
            else{
                return;
            }

        });

Here session is a service.It checks if the access token is found in the session storage.If not found then it prevents user from going to inner pages.

Now,after making a call to login API from your login page,store the access token form the response into your session storage,and change the state to your desired home page.

NOTE: You might prefer using local storage instead of session storage for storing the access token.


问:
Android Studio AVD Manager button is disabled
I'm very new to Android development and have never used Android Studio before. I set it up, got my app working on my phone and left it alone for a few weeks. Upon returning, I could not find the Android Studio executable on my computer, so I reinstalled it and restarted on the same project.

Not sure if this has to do with the AVD Manager button being grayed out. Things I have tried:

Making sure my SDK path is correct

Running Android Studio as administrator

Launching the AVD Manager executable from windows. I can create a virtual device but doesn't affect disabled AVD Manager button when restarting Android Studio.

Installing Intel X86 Atom System Image and Google APIs in SDK Manager, under API 24.Everything under API 25 is installed.

Any help is appreciated. Thank you!

答: I'v solved this issue by updating gradle.


问:
How to draw square to tag on the image

I'm building Tagging feature on photo like above using React Native (expo). Is there any such Square Listener?

Here is its essential Use Cases

User can change square size by dragging on their finger.

We can monitor square information including square width, height, x-coordinate, y-coordinate.

How can I achieve this? Do you have any idea or know any good library?

Any answer will be highly appreciated!

答: I think you're going to want to use some sort of face detection, such as by cloudinary. There are other services too, such as Google Face Detection which might be even closer to what you're looking for. These services will just give you the initial coordinates of the face, leaving you to draw the box yourself. So you can roll your own "size by dragging" feature as well. </p>

Title: How to draw square to tag on the image


问:
MS SQL Server cannot call methods on ntext
I am trying to create a view in MS SQL server from a table. The table name is Account_Plan and I am trying to create a view as Account_Plan_vw. While executing the DDL to create the view, I am getting the error as shown below.

Msg 258, Level 15, State 1, Procedure Account_Plan_vw, Line 56

  Cannot call methods on ntext

Msg 207, Level 16, State 1, Procedure Account_Plan_vw, Line 22

  Invalid column name 'How_the_CU_will_achieve_these_objective2__c'.

The error message shows the column 'How_the_CU_will_achieve_these_objective2__c' as invalid. However, this is a valid column in the Account_Plan table of ntext type.

Can someone help? I just removed the extra columns from the Create view statement.

```<code>CREATE VIEW [dbo].[Account_Plan_vw]
AS
SELECT
 Results_1.Account__c
,Results_1.How_the_CU_will_achieve_these_objectives__c
,Results_1.How_the_CU_will_achieve_these_objective2__c
FROM
(
  SELECT ROW_NUMBER() OVER (PARTITION BY apc1.Account__c ORDER BY apc1.Year__c DESC, apc1.CreatedDate DESC) AS RN_1
    ,apc1.Account__c
,apc1.How_the_CU_will_achieve_these_objectives__c
,apc1.How_the_CU_will_achieve_these_objective2__c
  FROM Account_Plan apc1
  INNER JOIN RecordType rtp1
  ON apc1.RecordTypeId=rtp1.[Id]
  AND rtp1.DeveloperName = 'Account_Plan'
  INNER JOIN Account acc1
  ON acc1.[Id] = apc1.Account__c
  WHERE apc1.Year__c <= YEAR(GETDATE())
  ) AS Results_1
  WHERE RN_1 = 1
</code>```

答:
the issue and it was somewhat cryptic to find. The salesforce object had a field as last_peer_review_date__c for which no permissions were given to anybody. As a result, DBAMP user was not able to see the field and hence missed to create this field in SQL server when I used the SF_Replicate command. The create view SQL was created by me couple of weeks ago and it did work at that time. Now, when I used the same SQL, it failed because the SQL had the last_peer_review_date field, but the Account_Plan table does not.

Balaji Pooruli

Body:
I am trying to create a view in MS SQL server from a table. The table name is Account_Plan and I am trying to create a view as Account_Plan_vw. While executing the DDL to create the view, I am getting the error as shown below.

Msg 258, Level 15, State 1, Procedure Account_Plan_vw, Line 56

  Cannot call methods on ntext

Msg 207, Level 16, State 1, Procedure Account_Plan_vw, Line 22

  Invalid column name 'How_the_CU_will_achieve_these_objective2__c'.

The error message shows the column 'How_the_CU_will_achieve_these_objective2__c' as invalid. However, this is a valid column in the Account_Plan table of ntext type.

Can someone help? I just removed the extra columns from the Create view statement.

CREATE VIEW [dbo].[Account_Plan_vw]
AS
SELECT
 Results_1.Account__c
,Results_1.How_the_CU_will_achieve_these_objectives__c
,Results_1.How_the_CU_will_achieve_these_objective2__c
FROM
(
  SELECT ROW_NUMBER() OVER (PARTITION BY apc1.Account__c ORDER BY apc1.Year__c DESC, apc1.CreatedDate DESC) AS RN_1
    ,apc1.Account__c
,apc1.How_the_CU_will_achieve_these_objectives__c
,apc1.How_the_CU_will_achieve_these_objective2__c
  FROM Account_Plan apc1
  INNER JOIN RecordType rtp1
  ON apc1.RecordTypeId=rtp1.[Id]
  AND rtp1.DeveloperName = 'Account_Plan'
  INNER JOIN Account acc1
  ON acc1.[Id] = apc1.Account__c
  WHERE apc1.Year__c <= YEAR(GETDATE())
  ) AS Results_1
  WHERE RN_1 = 1


问:
How to configure angular2 CLI in offline environment
I have used the "http://webiks.com/working-offline-with-angular-cli/" resource to setup my angular2 and use angular cli for an offline environment that does not have access to Internet.

I appreciate if you explain how I can configure angular cli to use cli commands in offline environment.

Thank you

答:
Install it in online machine and copy

%appdata%/npm/node_modules/@angular
%appdata%/npm/ng
%appdata%/npm/ng.cmd
Paste these in the same path in offline machine and run “ng -v” from cmd to verify…All doneRefer


答:
In the code above, obj is created within the scope of a single iteration of the loop, and dies at its end. This is as if, in Java, you put MyObject obj = new MyObject() at the same location. No information will transition from one iteration of the loop to the other (unless you change the state of the file).

To convince yourself, place a function call as the "body" of the loop. In that function, create the variable on the stack. The variable will only live while this function is executing.

Title: C++ loop stack allocation


问:
Bubble sort algorithm | 'str' object does not support item assignment - Python
The brief: I challenged myself to write a program, as asked in a textbook, to test my understanding and demonstrate proficiency in the 'bubble sort'. The problem asked to write a program that "allows the user to enter 20 names into a String array. Sort the array in ascending (alphabetical) order and display its contents." My initial code worked, however I wasn't satisfied and one unsuccessful attempted code change later, I am stumped for a viable solution.

The issue: I initially wrote the friendInput function with for a loop, that iterates 20 times (for listInput in range(20):), to allow for 20 individual inputs, respective to the 20 values for the user to input. Whilst this worked, I consider it quite tedious from a user perspective, especially with a range of 20, to have to keep typing, hitting return, then repeating for 20 values.

Original code:

```<code>def friendInput():
    friendList  = []
    for listInput in range(20):
        friendList.append(input("Please enter a friends name: "))
    print("You added these to the list: "+' | '.join(friendList))
    return friendList
</code>```

Attempted code re-write:

```<code>def friendInput():
    friendList = []
    separator = ","
    friendList = input("Please enter friend's names, separated with commas: ")
    print("You added these to the list:",friendList.split(separator))
    return friendList
</code>```

I did some research and learnt a lot, including the .split() function and tried to implement this, unsuccessfully it appears.
Bubble sort algorithm:

```<code>def bubbleSort(friendList):
    for friends in range (0, len(friendList) - 1):
        for x in range (0, len(friendList) - 1 - friends):
            if friendList[x] > friendList[x+1]:
                friendList[x], friendList[x+1] = friendList[x+1],  friendList[x]
    return friendList
</code>```

Error message:
Everything seemed logical in my head, until the debugger threw back a TypeError: 'str' object does not support item assignment. The  TypeError: goes on to quote part of my bubbleSort function - friendList[x], friendList[x+1] = friendList[x+1], friendList[x]

Where I need help:
I suppose the error is really just saying that I'm trying to access and change a string, which is obviously disallowed, as it's not immutible. I am struggling to find a code change that would look clear, concise and not burden the user.

Can someone kindly offer suggestions, to remedy this error?

答:
Re-read these lines:

```<code>friendList = input("Please enter friend's names, separated with commas: ")
print("You added these to the list:",friendList.split(separator))
return friendList
</code>```

You are creating a string friendList = input... and then you are returning the string (return friendList). You intend to create a list and then return the list.

Try this instead:

```<code>friendList = input("Please enter friend's names, separated with commas: ")
friendList = friendList.split(separator)
print("You added these to the list:",friendList)
return friendList
</code>```

Body:
The brief: I challenged myself to write a program, as asked in a textbook, to test my understanding and demonstrate proficiency in the 'bubble sort'. The problem asked to write a program that "allows the user to enter 20 names into a String array. Sort the array in ascending (alphabetical) order and display its contents." My initial code worked, however I wasn't satisfied and one unsuccessful attempted code change later, I am stumped for a viable solution.

The issue: I initially wrote the friendInput function with for a loop, that iterates 20 times (for listInput in range(20):), to allow for 20 individual inputs, respective to the 20 values for the user to input. Whilst this worked, I consider it quite tedious from a user perspective, especially with a range of 20, to have to keep typing, hitting return, then repeating for 20 values.

Original code:

def friendInput():
    friendList  = []
    for listInput in range(20):
        friendList.append(input("Please enter a friends name: "))
    print("You added these to the list: "+' | '.join(friendList))
    return friendList

Attempted code re-write:

def friendInput():
    friendList = []
    separator = ","
    friendList = input("Please enter friend's names, separated with commas: ")
    print("You added these to the list:",friendList.split(separator))
    return friendList

I did some research and learnt a lot, including the .split() function and tried to implement this, unsuccessfully it appears.
Bubble sort algorithm:

def bubbleSort(friendList):
    for friends in range (0, len(friendList) - 1):
        for x in range (0, len(friendList) - 1 - friends):
            if friendList[x] > friendList[x+1]:
                friendList[x], friendList[x+1] = friendList[x+1],  friendList[x]
    return friendList

Error message:
Everything seemed logical in my head, until the debugger threw back a TypeError: 'str' object does not support item assignment. The  TypeError: goes on to quote part of my bubbleSort function - friendList[x], friendList[x+1] = friendList[x+1], friendList[x]

Where I need help:
I suppose the error is really just saying that I'm trying to access and change a string, which is obviously disallowed, as it's not immutible. I am struggling to find a code change that would look clear, concise and not burden the user.

Can someone kindly offer suggestions, to remedy this error?

Body:
Re-read these lines:

friendList = input("Please enter friend's names, separated with commas: ")
print("You added these to the list:",friendList.split(separator))
return friendList

You are creating a string friendList = input... and then you are returning the string (return friendList). You intend to create a list and then return the list.

Try this instead:

friendList = input("Please enter friend's names, separated with commas: ")
friendList = friendList.split(separator)
print("You added these to the list:",friendList)
return friendList


问:
Changing elements in an HTML file using javascript onclick event
I've been learning HTML and CSS this semester and originally started to code my project in HTML and CSS, but in order for my project to work, I had to link HTML pages to each other. It ended up making a lot of HTML pages just to change one line of text. I've been trying to get a handle on JavaScript to make my project more efficient. My HTML code looks like this:

```<code><!doctype html>

<html>
<head>
    <meta charset=utf-8>
    <title>Oakwood</title>
    <meta name="viewport" content="width=device-width; initial-scale=1.0;">
    <link rel=stylesheet type=text/css href=default.css>

</head>
<body>

<div id=back></div>
<div id=drdick></div>
<div id=choice></div>

<div class="typewriter">
<script src="run.js"></script>
<p id=text>While out running someone says “Hi” causing you to trip. He helps you up.</p>
</div>

<div id=move>
<button type="button" onclick="changeThis()">Next</button>
</div>

</body>
</html>
</code>```

My Javascript Looks like this:

```<code>var quoteIndex = 0;
var quotes = [
    "Thank you.",
    "Are you ok?",
    "Yes, I’m not normally this clumsy"
];
function changeQuote() {
    ++quoteIndex;
    if (quoteIndex >= quotes.length) {
        quoteIndex = 0;
    }
    document.getElementById("text").innerHTML = quotes[quoteIndex];
}

function showPic()
{document.getElementById("drdick").src="img/drdickab.png";}

function changeThis() {
    changeQuote();
    showPic();
}
</code>```

when I test my code my quotes update how I want them to. My picture does not show up at all. Is there something I am missing when it comes to how HTML and Javascript interact? I have been looking through the forums to figure out what I have wrong, and I haven't been able to figure that out.

答:
Your image is not displaying because you did not specify your image anywhere in your markup, and your javascript is also not enough. But try this inside your body tag:

```<code><body>

<!--replace your button with this code.-->

<div id=move>
<button type="button" onclick="showMyImage();" value="Next"></button>
</div>

<!--I assumed you will display the image just below your button, note that initially your image is hidden and displayed on button click event-->
<div>
<img id="myImage" src="img/drdickab.png" style="visibility:hidden"/>
</div>
</body>
</code>```

.

```<code>  <!--There's really no need to have multiple scripts, just one will do the job-->

<script type="text/javascript">
  function showMyImage(){
     document.getElementById('myImage').style.visibility="visible";
}
</script>
</code>```

Body:
I've been learning HTML and CSS this semester and originally started to code my project in HTML and CSS, but in order for my project to work, I had to link HTML pages to each other. It ended up making a lot of HTML pages just to change one line of text. I've been trying to get a handle on JavaScript to make my project more efficient. My HTML code looks like this:

<!doctype html>

    <meta charset=utf-8>
    <title>Oakwood</title>
    <meta name="viewport" content="width=device-width; initial-scale=1.0;">
    <link rel=stylesheet type=text/css href=default.css>

While out running someone says “Hi” causing you to trip. He helps you up.

<button type="button" onclick="changeThis()">Next</button>

My Javascript Looks like this:

var quoteIndex = 0;
var quotes = [
    "Thank you.",
    "Are you ok?",
    "Yes, I’m not normally this clumsy"
];
function changeQuote() {
    ++quoteIndex;
    if (quoteIndex >= quotes.length) {
        quoteIndex = 0;
    }
    document.getElementById("text").innerHTML = quotes[quoteIndex];
}

function showPic()
{document.getElementById("drdick").src="img/drdickab.png";}

function changeThis() {
    changeQuote();
    showPic();
}

when I test my code my quotes update how I want them to. My picture does not show up at all. Is there something I am missing when it comes to how HTML and Javascript interact? I have been looking through the forums to figure out what I have wrong, and I haven't been able to figure that out.

Body:
Your image is not displaying because you did not specify your image anywhere in your markup, and your javascript is also not enough. But try this inside your body tag:

<body>

<!--replace your button with this code.-->

<div id=move>
<button type="button" onclick="showMyImage();" value="Next"></button>
</div>

<!--I assumed you will display the image just below your button, note that initially your image is hidden and displayed on button click event-->
<div>
<img id="myImage" src="img/drdickab.png" style="visibility:hidden"/>
</div>
</body>

.

  <!--There's really no need to have multiple scripts, just one will do the job-->

<script type="text/javascript">
  function showMyImage(){
     document.getElementById('myImage').style.visibility="visible";
}
</script>


问:
Is there a way in testNG to skip tests based on data provider input?
For Eg:
Below is my test method and data provider. my testmethod should be skipped if data provider input is "Two".</p>

```<code>@Test(dataprovider = "getData")
public void test(String data) {
    System.out.println(data + " Executed successfully");
}

@DataProvider
public Object[][] getData(){
    return new Object[][]{
        {"One"},
        {"Two"},
        {"Three"},
        {"Four"},
        {"Five"}
    };
}
</code>```

答:
inside your test method , you can compare the parameter data and throw a skip exception when your condition is satisfied.</p>

```<code>@Test(dataprovider = "getData")
public void test(String data) {
    if(data.equals("two")){
    throw new SkipException("Test skipped as data is:"+data);
    }
    System.out.println(data + " Executed successfully");
}
</code>```

Body:
For Eg:
Below is my test method and data provider. my testmethod should be skipped if data provider input is "Two".

@Test(dataprovider = "getData")
public void test(String data) {
    System.out.println(data + " Executed successfully");
}

@DataProvider
public Object[][] getData(){
    return new Object[][]{
        {"One"},
        {"Two"},
        {"Three"},
        {"Four"},
        {"Five"}
    };
}

Body:
inside your test method , you can compare the parameter data and throw a skip exception when your condition is satisfied.

@Test(dataprovider = "getData")
public void test(String data) {
    if(data.equals("two")){
    throw new SkipException("Test skipped as data is:"+data);
    }
    System.out.println(data + " Executed successfully");
}


问:
What to write so that when "enter" is pressed, then code proceeds further?
Please help me in the below code :

```<code>import java.util.Scanner;
class A
{
    public static void main(String args[])
    {
        Scanner Sc = new Scanner(System.in);
        System.out.print("Enter first number : ");
        a = Sc.nextInt();
        System.out.print("Enter second number : ");
        b = Sc.nextInt();
        System.out.print("Sum is : " + (a + b));
        System.out.print("Press enter to continue...");
        /* HERE IS MY DOUBT */
        /* WHAT TO WRITE HERE SO THAT WHEN "ENTER" IS PRESSED THEN CODE PROCEEDS */
    }
}
</code>```

Like in C language we can use getch() to hold a program. Is there something similar in Java too?

I have already tried Sc.nextLine(). The problem with Sc.nextLine() is that, in it first I have to enter a value and then press enter and then the code proceeds.
But what I want is to just press enter and proceed.

答:
```<code>import java.util.Scanner;
class A
{
    public static void main(String args[])
    {
        while(true) {
            Scanner Sc = new Scanner(System.in);
            System.out.print("Enter first number : ");
            int a = Sc.nextInt();
            System.out.print("Enter second number : ");
            int b = Sc.nextInt();
            System.out.println("Sum is : " + (a + b));
            System.out.println("Press enter to continue...");
        }
    }
}
</code>```

Body:
Please help me in the below code :

import java.util.Scanner;
class A
{
    public static void main(String args[])
    {
        Scanner Sc = new Scanner(System.in);
        System.out.print("Enter first number : ");
        a = Sc.nextInt();
        System.out.print("Enter second number : ");
        b = Sc.nextInt();
        System.out.print("Sum is : " + (a + b));
        System.out.print("Press enter to continue...");
        /* HERE IS MY DOUBT */
        /* WHAT TO WRITE HERE SO THAT WHEN "ENTER" IS PRESSED THEN CODE PROCEEDS */
    }
}

Like in C language we can use getch() to hold a program. Is there something similar in Java too?

I have already tried Sc.nextLine(). The problem with Sc.nextLine() is that, in it first I have to enter a value and then press enter and then the code proceeds.
But what I want is to just press enter and proceed.


问:
Fitting a function with a heavyside step function
I am trying to fit a function to a part of the following graph:

I want to find out the time the signal starts increasing exponentially. To do this I fit an exponential curve to the data, multiplied by a heavyside step function.

```<code>def fit(x, a, b, c, d, e):
    return np.heaviside(x-a, 0.5)*b*np.exp(c*x-d)+e

parameter, covariance = curve_fit(fit, fitx, fity)

x = np.linspace(min(fitx), max(fitx), 1000)
plt.plot(fitx, fity)
plt.plot(x, fit(x, *parameter), 'b-', label='fit')
plt.show()
</code>```

The result is somehow a straight line

When I fit only the exponential part I get the following graph:

I'd expect a straight line at the x-axis, followed by the exponential graph in image 2. Does anybody know where I went wrong?

答:
You say that you want to find "the time the signal starts increasing exponentially", but the signal plotted does not increase exponentially. In fact, it decreases (at least going in increasing time and left to right). and looks peak-like.   Do you mean that you want to fit some function to that drop?

I'd guess that a Gaussian might work well.  Using a step function might be OK too, but probably won't fit well above t=1e-8 or so.

You didn't include data or complete code, so it's hard to give a concrete example.  But you might find the lmfit package helpful here.  It has a builtin Step Model that can use a linear or error function or logistic curve. See http://lmfit.github.io/lmfit-py/builtin_models.html#step-like-models. This might be close to what you're trying to do.

Body:
I am trying to fit a function to a part of the following graph:

I want to find out the time the signal starts increasing exponentially. To do this I fit an exponential curve to the data, multiplied by a heavyside step function.

def fit(x, a, b, c, d, e):
    return np.heaviside(x-a, 0.5)*b*np.exp(c*x-d)+e

parameter, covariance = curve_fit(fit, fitx, fity)

x = np.linspace(min(fitx), max(fitx), 1000)
plt.plot(fitx, fity)
plt.plot(x, fit(x, *parameter), 'b-', label='fit')
plt.show()

The result is somehow a straight line

When I fit only the exponential part I get the following graph:

I'd expect a straight line at the x-axis, followed by the exponential graph in image 2. Does anybody know where I went wrong?


问:
Formatting City/State Information
I have an application which stores the user's home town, state, and country. I don't particularly need to do validation; no other part of the application relies on the data, but I would like the formatting to be consistent for vanity and to avoid later having "North Carolina", "NC", "north carolina" and so forth all in the database.

Does anyone know of a way to pass Bing maps (I would prefer Bing over Google since I've been using it on this project thus far) a search string and get given back an object with the address as interpreted by the service? (i.e. pass in "charlotte, nc" and be given back "Charlotte, North Carolina, United States")

I've looked at VEPlace (on MSDN), but I'm not sure how to ensure I get back the format I'm hoping for from the Name attribute. Anyone have an idea on how best to go about this?

Also, the back-end for the project is ASP.NET MVC, so if there's a way to do it in C# that involves a controller or something similar that's totally fine.

答:
I think I may have found the solution: The GeocodeServiceRequest.ReverseGeocodeRequest method (on MSDN) returns a GeocodeResponse class which has an Address member. This in turn has all the attributes required to form the address the way I want. So there will be a controller with an Action to take in the string form of the address, which will send back the properly formatted version.

I'm going to try this and update with code in a couple hours. It's not fully client-side, which is suboptimal, but it looks like it will work well.

Title: Formatting City/State Information


问:
Change drawable color programmatically
I'm trying to change the color on a white marker image by code. I have read that the code below should change the color, but my marker remains white.

```<code>Drawable.setColorFilter( 0xffff0000, Mode.MULTIPLY )
</code>```

Did I miss something? Is there any other way to change colors on my drawables located in my res folder?

答:
This worked for me. Make sure to put "ff" between 0x and color code. Like this 0xff2196F3</p>

```<code>Drawable mDrawable = ContextCompat.getDrawable(MainActivity.this,R.drawable.ic_vector_home);
                    mDrawable.setColorFilter(new
                            PorterDuffColorFilter(0xff2196F3,PorterDuff.Mode.SRC_IN));
</code>```

Title: Change drawable color programmatically

Body:
I'm trying to change the color on a white marker image by code. I have read that the code below should change the color, but my marker remains white.

Drawable.setColorFilter( 0xffff0000, Mode.MULTIPLY )

Did I miss something? Is there any other way to change colors on my drawables located in my res folder?

Body:
This worked for me. Make sure to put "ff" between 0x and color code. Like this 0xff2196F3

Drawable mDrawable = ContextCompat.getDrawable(MainActivity.this,R.drawable.ic_vector_home);
                    mDrawable.setColorFilter(new
                            PorterDuffColorFilter(0xff2196F3,PorterDuff.Mode.SRC_IN));


问:
Issue while invoking chrome browser with Selenium Driver
When i am trying to invoke chrome browser in eclipse using selenium driver with Java , i am getting an error.

Please help me out in resolving this issue.

Below is my code -

```<code>package packagedefault;

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

public class ChromeBrowser {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.get("https://google.com");

    }

}
</code>```

Below is the error message i am getting -

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/config/RegistryBuilder
    at org.openqa.selenium.remote.internal.HttpClientFactory.getClientConnectionManager(HttpClientFactory.java:69)
    at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:57)
    at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:60)
    at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.getDefaultHttpClientFactory(ApacheHttpClient.java:242)
    at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.<init>(ApacheHttpClient.java:219)
    at org.openqa.selenium.remote.HttpCommandExecutor.getDefaultClientFactory(HttpCommandExecutor.java:93)
    at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:72)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.<init>(DriverCommandExecutor.java:63)
    at org.openqa.selenium.chrome.ChromeDriverCommandExecutor.<init>(ChromeDriverCommandExecutor.java:36)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
    at packagedefault.ChromeBrowser.main(ChromeBrowser.java:24)
Caused by: java.lang.ClassNotFoundException: org.apache.http.config.RegistryBuilder
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 13 more
</code>```

答:
You can try using below code inside main() function

```<code>    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--test-type");
    WebDriver driver = new ChromeDriver(options);
    driver.get("https://google.com");
</code>```

Works properly here in my windows PC

Body:
When i am trying to invoke chrome browser in eclipse using selenium driver with Java , i am getting an error.

Please help me out in resolving this issue.

Below is my code -

package packagedefault;

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

public class ChromeBrowser {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.get("https://google.com");

    }

}

Below is the error message i am getting -

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/config/RegistryBuilder
    at org.openqa.selenium.remote.internal.HttpClientFactory.getClientConnectionManager(HttpClientFactory.java:69)
    at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:57)
    at org.openqa.selenium.remote.internal.HttpClientFactory.<init>(HttpClientFactory.java:60)
    at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.getDefaultHttpClientFactory(ApacheHttpClient.java:242)
    at org.openqa.selenium.remote.internal.ApacheHttpClient$Factory.<init>(ApacheHttpClient.java:219)
    at org.openqa.selenium.remote.HttpCommandExecutor.getDefaultClientFactory(HttpCommandExecutor.java:93)
    at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:72)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.<init>(DriverCommandExecutor.java:63)
    at org.openqa.selenium.chrome.ChromeDriverCommandExecutor.<init>(ChromeDriverCommandExecutor.java:36)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
    at packagedefault.ChromeBrowser.main(ChromeBrowser.java:24)
Caused by: java.lang.ClassNotFoundException: org.apache.http.config.RegistryBuilder
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 13 more

Body:
You can try using below code inside main() function

    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--test-type");
    WebDriver driver = new ChromeDriver(options);
    driver.get("https://google.com");

Works properly here in my windows PC


问:
data frame condition multiple rows
Say one has a data frame as follows:

```<code>data <- data.frame('obs' = c('a','c','b'), 'top1' = c('a','b','c'), 'top2' = c('b', 'c', 'f'), 'top3' = c('g', 'h', 'd'))
</code>```

I wan to compute a new column topn which is a conditional that works in the following fashion: if the value of obs is in any of the top columns then topn should be equal to obs, otherwise topn can be assigned any value, say top1. Of course I know I can do this with an or and ifelse, but I'm looking for a shorter way to write it because in my table I can have up to 10 top columns.

```<code> obs top1 top2 top3 topn
   a    a    b    g  a
   c    b    c    h  c
   b    c    f    d  c
</code>```

答:
This might be helpful and quick.

```<code>f=function(a){
</code>```

if(a[1] %in% a[-1]){

```<code>    return (a[1])
  }
</code>```

else{sample(a[-1],1)}

}

data$topn=apply(data,1,f)

Title: data frame condition multiple rows

Body:
Say one has a data frame as follows:

data <- data.frame('obs' = c('a','c','b'), 'top1' = c('a','b','c'), 'top2' = c('b', 'c', 'f'), 'top3' = c('g', 'h', 'd'))

I wan to compute a new column topn which is a conditional that works in the following fashion: if the value of obs is in any of the top columns then topn should be equal to obs, otherwise topn can be assigned any value, say top1. Of course I know I can do this with an or and ifelse, but I'm looking for a shorter way to write it because in my table I can have up to 10 top columns.

 obs top1 top2 top3 topn
   a    a    b    g  a
   c    b    c    h  c
   b    c    f    d  c

Body:
This might be helpful and quick.

f=function(a){

if(a[1] %in% a[-1]){

    return (a[1])
  }

else{sample(a[-1],1)}

}

data$topn=apply(data,1,f)


问:
mysql: design practices
I have tables setup as such:

A message is sent out to a group of users.

This message is put in the parent_message table

This table contains id | sender_id | date

each message that is sent in that group is put in the child_message table

this table contains id | parent_id | message | date_sent

when a reply is received it is put into the reply_message table

this table contains id | child_id | message | date_received.

Now I have a few questions about this setup.

1) Every time the page is loaded I need to show how many child messages each parent message has.

Would you add a column to the parent_message table called child_count or work it out in your query.

why, why not?

Example query

```<code>select *,
count(select parent_id from child_message c where c.parent_id = p.parent_id ) child_count
from parent_message;
</code>```

2) If the user chooses they can view all reply messages to a parent message.

would you add the parent_id to the reply reply_message table or work it out in your query?

Why, why not?

Example query

```<code>select * from reply_message
where child_id in(select id from child_message where parent_id = '66')
</code>```

答:
You're probably better off working it out in both cases but I would rewrite the queries

```<code>SELECT
   p.*
   count(child.*) childCount
FROM
   parent_message p
   LEFT JOIN  child_message  c
   on c.parent_id = p.parent_id
</code>```

and

```<code>SELECT DISTINCT
       rm.*
    FROM
        reply_message rm
        INNER JOIN child_message  cm
        rm.child_id = cm.id
   WHERE
       parent_id = '66'
</code>```

I also would list the fields instead of doing the SELECT *

Title: mysql: design practices

Body:
I have tables setup as such:

A message is sent out to a group of users.

This message is put in the parent_message table

This table contains id | sender_id | date

each message that is sent in that group is put in the child_message table

this table contains id | parent_id | message | date_sent

when a reply is received it is put into the reply_message table

this table contains id | child_id | message | date_received.

Now I have a few questions about this setup.

1) Every time the page is loaded I need to show how many child messages each parent message has.

Would you add a column to the parent_message table called child_count or work it out in your query.

why, why not?

Example query

select *,
count(select parent_id from child_message c where c.parent_id = p.parent_id ) child_count
from parent_message;

2) If the user chooses they can view all reply messages to a parent message.

would you add the parent_id to the reply reply_message table or work it out in your query?

Why, why not?

Example query

select * from reply_message
where child_id in(select id from child_message where parent_id = '66')

Body:
You're probably better off working it out in both cases but I would rewrite the queries

SELECT
   p.*
   count(child.*) childCount
FROM
   parent_message p
   LEFT JOIN  child_message  c
   on c.parent_id = p.parent_id

and

SELECT DISTINCT
       rm.*
    FROM
        reply_message rm
        INNER JOIN child_message  cm
        rm.child_id = cm.id
   WHERE
       parent_id = '66'

I also would list the fields instead of doing the SELECT *