问:
What is the difference between updated hook and watchers in VueJS?
I'm discovering VueJS and I don't understand exactly the differences between updated and watchers.

Updated hook

It is a lifecycle hook. According to the official documentation, it is triggered whenever data changes. So whenever a prop or a data is updated (the value, not only the pointer), updated is called.

Watchers

In the documentation, watchers are compared to computed properties. But in which cases would it be best to use updated instead of watchers ?

It seems that in both cases, DOM is not updated when the callback is called (nextTick() is required if we want to manipulate the changes in the DOM). The only difference I see is that watchers are only triggered when one precise property (or data) is updated where updated is always called.

I can't figure out what are the pros of updating whenever a data changes (updating) if we can be more accurate (watchers).

Here are my thoughts.

Thanks :)

答:
I think a better analogous lifecycle hook to the watchers may be the beforeUpdate hook. The updated hook is called after the virtual DOM has re-rendered, whereas beforeUpdate is called before the virtual DOM has re-rendered. You can see a visual representation of this on the diagram you linked to.

in which cases would it be best to use updated instead of watchers ? (...) I can't figure out what are the pros of updating whenever a data changes (updated) if we can be more accurate (watch).

The documentation says that you should prefer a watcher or computed property instead of updated if it is possible to achieve your goal that way. My understanding is that the updated hook was included to allow users to watch for any changes to the virtual DOM (see below).

Here's the explanation from the Vue 2.0 release notes on watch vs. updated:

User watchers created via vm.$watch are now fired before the associated component re-renders. This gives the user a chance to further update other state before the component re-render, thus avoiding unnecessary updates. For example, you can watch a component prop and update the component's own data when the prop changes.

To do something with the DOM after component updates, just use the updated lifecycle hook.


来源: stackexchange

问:
How to comment out structure <?= ?> in Yii2
a trivial question, but all my efforts to comment out code lines like this:

```<code><?=$form->field($model, 'bew_id')->textInput(['placeholder' => 'Bew']) ?>
</code>```

failed by using PHP and/or HTML-comments.Following trys didn't success:

//

/* */

<-!- -->

Any ideas??

答:
Remove <?= at the beginning then you can comment by using
```

ContentLicense: CC BY-SA 3.0

Body:
a trivial question, but all my efforts to comment out code lines like this:

<?=$form->field($model, 'bew_id')->textInput(['placeholder' => 'Bew']) ?>

failed by using PHP and/or HTML-comments.Following trys didn't success:

//

/* */

<-!- -->

Any ideas??

Body:
Remove <?= at the beginning then you can comment by using <!-- as follows

<!---$form->field($model, 'bew_id')->textInput(['placeholder' => 'Bew']) ?>-->


问:
What does css-loader do in webpack?
According to the official webapck documentation, webpack imports specified CSS files into your JavaScript module using a loader called css-loader.

What good does this process do? How can you just not go with the old school way of linking a CSS file to your html using the link tag?

答:
I will give you a good exemple of a scenario where linking the css is not possible.

If you are developing a ASP.NET Core MVC application, and wanna use some css from the node_modules folder, it will be not possible to resolve the path to that folder. This happens because the ASP.NET serves files only from the wwwroot directory.

Because of that, you need a build system just like webpack.

With a css loader in webpack, it will check for every css reference in the js/ts files provided as entries and will generate another css file in the output directory (usually inside wwwroot).
Take a look at this example:

```<code>entry: {
vendor: [
    '@angular/animations',
    '@angular/cdk',
    '@angular/material',
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/flex-layout',
    '@angular/forms',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    '@angular/material/prebuilt-themes/pink-bluegrey.css',
    'es6-shim',
    'es6-promise',
    'event-source-polyfill',
    'jquery',
    'zone.js',
    'jwt-decode'
]}
</code>```

Here I added a theme css for angular material. Note that the css is inside the vendor js/ts bundle. The css loader will extract the css from there and generate a css file with the same name of the bundle. The generated file, placed on the wwwroot folder, will be the one that you will reference in your index.html (assuming it is a SPA application like in this example).

Of course, you can just copy the css file from the node_modules folder, and put it in the wwwroot directory so that you will be able to link it. But that approach is fragile because when another version of the css is available and you wan't the up to date version, you will have to update the packages and copy the files all over again. So, why not automate it?

Title: What does css-loader do in webpack?

Body:
I will give you a good exemple of a scenario where linking the css is not possible.

If you are developing a ASP.NET Core MVC application, and wanna use some css from the node_modules folder, it will be not possible to resolve the path to that folder. This happens because the ASP.NET serves files only from the wwwroot directory.

Because of that, you need a build system just like webpack.

With a css loader in webpack, it will check for every css reference in the js/ts files provided as entries and will generate another css file in the output directory (usually inside wwwroot).
Take a look at this example:

entry: {
vendor: [
    '@angular/animations',
    '@angular/cdk',
    '@angular/material',
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/flex-layout',
    '@angular/forms',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    '@angular/material/prebuilt-themes/pink-bluegrey.css',
    'es6-shim',
    'es6-promise',
    'event-source-polyfill',
    'jquery',
    'zone.js',
    'jwt-decode'
]}

Here I added a theme css for angular material. Note that the css is inside the vendor js/ts bundle. The css loader will extract the css from there and generate a css file with the same name of the bundle. The generated file, placed on the wwwroot folder, will be the one that you will reference in your index.html (assuming it is a SPA application like in this example).

Of course, you can just copy the css file from the node_modules folder, and put it in the wwwroot directory so that you will be able to link it. But that approach is fragile because when another version of the css is available and you wan't the up to date version, you will have to update the packages and copy the files all over again. So, why not automate it?


问:
Heroku cannot find any module
I'm trying to develop a webapp using meteor and Heroku. When I run my code locally everything is fine, but as soon as I deploy it on Heroku, i get:

Cannot find module './navbar/NavBar.js'

or if I get rid of the NavBar in my code:

Cannot find module './component/App'

My project folder looks like:

```<code>project
  client
    main.css
    main.html
    main.js
      component
        App.js
        Games.js
        Home.js
        Workbench.js
        navbar
          NavBar.js

  Server
    main.js
</code>```

And this is my code:

main.js

```<code>import React from 'react';
import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';

import App from './component/App';

Meteor.startup(() => {
  render(<App />, document.getElementById('root'));

});
</code>```

App.js

```<code>import React from 'react';
import {Container} from 'reactstrap';
import {BrowserRouter as Router, Route} from 'react-router-dom';

import Workbench from './Workbench'
import NavBar from './navbar/NavBar.js'

export default class App extends React.Component {
  render(){
    return(
      <Router>
        <div>
        <NavBar/>
          <Container fluid={true}>
            <Route path='/' component={Workbench}/>
          </Container>
        </div>
      </Router>
    )
  }
}
</code>```

NavBar.js

```<code>import React from 'react';
import {nav} from 'react-bootstrap';

export default class NavBar extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      gameList: [{}],
      gamesVisibility: false
    }
  }
  render() {
    const {gameList, gameVisibility} = this.state;

    return (
      <div className="sidenav">
          <h2 className="sidenav-header"><a href="/">Test project</a></h2>
          <ul>
            <li onClick={() => this.setState({gameVisibility: !gameVisibility})}> <a className="SideNavTitle">Games</a> {this.renderArrow(gameVisibility)} </li>
              {this.renderCollection(gameVisibility, gameList)}
            <li className="SideNavItem"><a>Channel</a></li>
            <li className="SideNavItem"><a>About</a></li>
          </ul>
      </div>
    );
  }

  renderCollection(visibility, collection){
      if (visibility){
          return collection.map((game) => <li id = 'test' className="SideNavSubItem"><a>{game.name}</a></li>)
      }
      else{
        return;
      }
  }

  renderArrow(visibility){
    if (visibility){
      return <i className="fa fa-arrow-down" aria-hidden="true" style={{color: 'white'}}/>
    }
    else{
      return <i className="fa fa-arrow-right" aria-hidden="true" style={{color: 'white'}}/>
    }
  }

}
</code>```

I used heroku run bash along with cat NavBar.js to confirm that my file was on heroku as suggested in this post. Its kind of weird since the code work perfectly locally

Edit: The build on Heroku is successful, these errors show when I try to load my page.

答:
I am assuming your project folder contains three sub folders(client,component, server).  In your main.js file use:

import App from '../component/App'

you are using single "." which searches the component folder in server folder.
  you need to traverse back with double "."

Title: Heroku cannot find any module

Body:
I'm trying to develop a webapp using meteor and Heroku. When I run my code locally everything is fine, but as soon as I deploy it on Heroku, i get:

Cannot find module './navbar/NavBar.js'

or if I get rid of the NavBar in my code:

Cannot find module './component/App'

My project folder looks like:

project
  client
    main.css
    main.html
    main.js
      component
        App.js
        Games.js
        Home.js
        Workbench.js
        navbar
          NavBar.js

  Server
    main.js

And this is my code:

main.js

import React from 'react';
import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';

import App from './component/App';

Meteor.startup(() => {
  render(<App />, document.getElementById('root'));

});

App.js

import React from 'react';
import {Container} from 'reactstrap';
import {BrowserRouter as Router, Route} from 'react-router-dom';

import Workbench from './Workbench'
import NavBar from './navbar/NavBar.js'

export default class App extends React.Component {
  render(){
    return(
      <Router>

        <NavBar/>
          <Container fluid={true}>
            <Route path='/' component={Workbench}/>
          </Container>

      </Router>
    )
  }
}

NavBar.js

import React from 'react';
import {nav} from 'react-bootstrap';

export default class NavBar extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      gameList: [{}],
      gamesVisibility: false
    }
  }
  render() {
    const {gameList, gameVisibility} = this.state;

    return (

Test project

 this.setState({gameVisibility: !gameVisibility})}> Games {this.renderArrow(gameVisibility)}

              {this.renderCollection(gameVisibility, gameList)}

Channel

About

    );
  }

  renderCollection(visibility, collection){
      if (visibility){
          return collection.map((game) =>
{game.name}
)
      }
      else{
        return;
      }
  }

  renderArrow(visibility){
    if (visibility){
      return
    }
    else{
      return
    }
  }

}

I used heroku run bash along with cat NavBar.js to confirm that my file was on heroku as suggested in this post. Its kind of weird since the code work perfectly locally

Edit: The build on Heroku is successful, these errors show when I try to load my page.


问:
Duplicated Rows with UNIQUE INDEX MySQL and NULL Columns
Table Sufix:
id, name

```<code>(3, 'com')
</code>```

Table DomainName:
id, name

```<code>(2, 'microsoft')
</code>```

Table Domain:
id, name_code, sufix

```<code>(1, 2, 3)    -- microsoft.com
</code>```

Table SubDomainName:

```<code>(4, 'windows')
</code>```

Table SubDomain:
id, name_code, domain

```<code>(7, 4, 1)     -- windows.microsoft.com
</code>```

Table Email:
id, name, atserver

```<code>(3, 'myemail', 7)    -- myemail@windows.microsoft.com
(4, 'other', 1)      -- other@microsoft.com
</code>```

Here is a problem of foreign key constraints. How can I resolve domains and subdomains to create emails correctly? I'm having problems with Unique INDEX with NULL values, for example, a solution maybe:

Table Email:
id, name, subdomain, domain

```<code>(3, 'myemail', 7, NULL)  -- myemail@windows.microsoft.com
(4, 'other', NULL, 1)    -- other@microsoft.com
</code>```

BUT

```<code>(5, 'newemail', NULL, NULL)  -- will duplicated values in the table
(6, 'newemail', NULL, NULL)
(7, 'newemail', NULL, NULL)
(8, 'newemail', NULL, NULL)
</code>```

AND

```<code>(**3**, 'myemail', 7, 1)   -- myemail@windows.microsoft.com and myemail@microsoft.com
</code>```

答:
How about (5, 'newemail', domain_id/subdomain_id, 'domain/subdomain')

So you could have

(5, 'newemail', 7, 'subdomain') or (5, 'newemail', 1, 'domain')

YOu could still LEFT JOIN SubDomain and Domain table but you will get only the data from the one that you need based on the 'domain/subdomain' field.

That is the quick solution. IMHO your DB structure is not very good and could be optimized. You should keep all domain/subdomain records in one table and use it for the emails. The table should be Table FullDomain: id, name_code, domain_name, subdomain_name

(1, 3, 2, 4)    -- windows.microsoft.com

or

(1, 3, 2, 0)    -- microsoft.com

ContentLicense: CC BY-SA 2.5

Body:
Table Sufix:
id, name

(3, 'com')

Table DomainName:
id, name

(2, 'microsoft')

Table Domain:
id, name_code, sufix

(1, 2, 3)    -- microsoft.com

Table SubDomainName:

(4, 'windows')

Table SubDomain:
id, name_code, domain

(7, 4, 1)     -- windows.microsoft.com

Table Email:
id, name, atserver

(3, 'myemail', 7)    -- myemail@windows.microsoft.com
(4, 'other', 1)      -- other@microsoft.com

Here is a problem of foreign key constraints. How can I resolve domains and subdomains to create emails correctly? I'm having problems with Unique INDEX with NULL values, for example, a solution maybe:

Table Email:
id, name, subdomain, domain

(3, 'myemail', 7, NULL)  -- myemail@windows.microsoft.com
(4, 'other', NULL, 1)    -- other@microsoft.com

BUT

(5, 'newemail', NULL, NULL)  -- will duplicated values in the table
(6, 'newemail', NULL, NULL)
(7, 'newemail', NULL, NULL)
(8, 'newemail', NULL, NULL)

AND

(**3**, 'myemail', 7, 1)   -- myemail@windows.microsoft.com and myemail@microsoft.com


问:
Storing functions in array. Is it a good practice?
```<code>var sing = function(name) {
    console.log(name + " is SINGING");
}

var cry = function(name) {
    console.log(name + " is CRYING");
}

var list = [sing, cry];

for(var func of list) {
    func('foo');
}
</code>```

This is exactly what I want in my code. But I am not sure if its a good practice.

答:
Yes, in some situations, it is the preferable design to store functions in an array.

Imagine the following EventEmitter class. You can register event listeners using a method called on and dispatch an event using emit. The functions are stored in an array:

var EventEmitter = function () {
  this._events = {};
};

EventEmitter.prototype.on = function (event, listener) {
  if (!this._events.hasOwnProperty(event)) {
    this._events[event] = []; // stores the listeners bound to the event's name
  }
  this._events[event].push(listener); // add the listener to the event's listeners array
};

EventEmitter.prototype.emit = function (event) {
  var args = Array.slice(arguments, 1);
  if (this._events.hasOwnProperty(event)) {
    this._events[event].forEach(function (listener) {
      listener.apply(null, args);
    });
  }
}

var emitter = new EventEmitter();

// push the first function to the array
emitter.on('event-a', function (data) {
  console.log('Event A was fired!');
});

// push the second function to the array
emitter.on('event-a', function (data) {
  console.log('Second listener to event A');
});

emitter.on('event-b', function (a, b, c) {
  console.log('Event B:', a + b + c);
});

emitter.emit('event-a');
setTimeout(function () {
  emitter.emit('event-b', 2, 3, 4);
}, 1500);```

This is why I would use it in some situations. I don't consider it bad practice.

Body:
var sing = function(name) {
    console.log(name + " is SINGING");
}

var cry = function(name) {
    console.log(name + " is CRYING");
}

var list = [sing, cry];

for(var func of list) {
    func('foo');
}

This is exactly what I want in my code. But I am not sure if its a good practice.

Body:
Yes, in some situations, it is the preferable design to store functions in an array.

Imagine the following EventEmitter class. You can register event listeners using a method called on and dispatch an event using emit. The functions are stored in an array:

var EventEmitter = function () {
  this._events = {};
};

EventEmitter.prototype.on = function (event, listener) {
  if (!this._events.hasOwnProperty(event)) {
    this._events[event] = []; // stores the listeners bound to the event's name
  }
  this._events[event].push(listener); // add the listener to the event's listeners array
};

EventEmitter.prototype.emit = function (event) {
  var args = Array.slice(arguments, 1);
  if (this._events.hasOwnProperty(event)) {
    this._events[event].forEach(function (listener) {
      listener.apply(null, args);
    });
  }
}

var emitter = new EventEmitter();

// push the first function to the array
emitter.on('event-a', function (data) {
  console.log('Event A was fired!');
});

// push the second function to the array
emitter.on('event-a', function (data) {
  console.log('Second listener to event A');
});

emitter.on('event-b', function (a, b, c) {
  console.log('Event B:', a + b + c);
});

emitter.emit('event-a');
setTimeout(function () {
  emitter.emit('event-b', 2, 3, 4);
}, 1500);

This is why I would use it in some situations. I don't consider it bad practice.


问:
How to write a function f("123")=123+12+23+1+2+3 as a recurrence relationship
I'm wondering if someone can help me try to figure this out.

I want f(str) to take a string str of digits and return the sum of all substrings as numbers, and I want to write f as a function of itself so that I can try to solve this with memoization.

It's not jumping out at me as I stare at

```<code>        Solve("1") = 1
        Solve("2") = 2
        Solve("12") = 12 + 1 + 2
        Solve("29") = 29 + 2 + 9
        Solve("129") = 129 + 12 + 29 + 1 + 2 + 9
        Solve("293") = 293 + 29 + 93 + 2 + 9 + 3
        Solve("1293") = 1293 + 129 + 293 + 12 + 29 + 93 + 1 + 2 + 9 + 3
        Solve("2395") = 2395 + 239 + 395 + 23 + 39 + 95 + 2 + 3 + 9 + 5
        Solve("12395") = 12395 + 1239 + 2395 + 123 + 239 + 395 + 12 + 23 + 39 + 95 + 1 + 2 + 3 + 9 + 5
</code>```

答:
Looking at this pattern:

```<code>Solve("1") = f("1") = 1
Solve("12") = f("12") = 1 + 2 + 12 = f("1") + 2 + 12
Solve("123") = f("123") = 1 + 2 + 12 + 3 + 23 + 123 = f("12") + 3 + 23 + 123
Solve("1239") = f("1239") = 1 + 2 + 12 + 3 + 23 + 123 + 9 + 39 + 239 + 1239 = f("123") + 9 + 39 + 239 + 1239
Solve("12395") = f("12395") = 1 + 2 + 12 + 3 + 23 + 123 + 9 + 39 + 239 + 1239 + 5 + 95 + 395 + 2395 + 12395 = f("1239") + 5 + 95 + 395 + 2395 + 12395
</code>```

To get the new terms, with n being the length of str, you are including the substrings made up of the 0-based index ranges of characters in str: (n-1,n-1), (n-2,n-1), (n-3,n-1), ... (n-n, n-1).

You can write a function to get the sum of the integers formed from the substring index ranges. Calling that function g(str), you can write the function recursively as f(str) = f(str.substring(0, str.length - 1)) + g(str) when str.length > 1, and the base case with str.length == 1 would just return the integer value of str. (The parameters of substring are the start index of a character in str and the length of the resulting substring.)

For the example Solve("12395"), the recursive equation f(str) = f(str.substring(0, str.length - 1)) + g(str) yields:

```<code>f("12395") =
f("1239") + g("12395") =
(f("123") + g("1239")) + g("12395") =
((f("12") + g("123")) + g("1239")) + g("12395") =
(((f("1") + g("12")) + g("123")) + g("1239")) + g("12395") =
1 + (2 + 12) + (3 + 23 + 123) + (9 + 39 + 239 + 1239) + (5 + 95 + 395 + 2395 + 12395)
</code>```

Body:
I'm wondering if someone can help me try to figure this out.

I want f(str) to take a string str of digits and return the sum of all substrings as numbers, and I want to write f as a function of itself so that I can try to solve this with memoization.

It's not jumping out at me as I stare at

        Solve("1") = 1
        Solve("2") = 2
        Solve("12") = 12 + 1 + 2
        Solve("29") = 29 + 2 + 9
        Solve("129") = 129 + 12 + 29 + 1 + 2 + 9
        Solve("293") = 293 + 29 + 93 + 2 + 9 + 3
        Solve("1293") = 1293 + 129 + 293 + 12 + 29 + 93 + 1 + 2 + 9 + 3
        Solve("2395") = 2395 + 239 + 395 + 23 + 39 + 95 + 2 + 3 + 9 + 5
        Solve("12395") = 12395 + 1239 + 2395 + 123 + 239 + 395 + 12 + 23 + 39 + 95 + 1 + 2 + 3 + 9 + 5

Body:
Looking at this pattern:

Solve("1") = f("1") = 1
Solve("12") = f("12") = 1 + 2 + 12 = f("1") + 2 + 12
Solve("123") = f("123") = 1 + 2 + 12 + 3 + 23 + 123 = f("12") + 3 + 23 + 123
Solve("1239") = f("1239") = 1 + 2 + 12 + 3 + 23 + 123 + 9 + 39 + 239 + 1239 = f("123") + 9 + 39 + 239 + 1239
Solve("12395") = f("12395") = 1 + 2 + 12 + 3 + 23 + 123 + 9 + 39 + 239 + 1239 + 5 + 95 + 395 + 2395 + 12395 = f("1239") + 5 + 95 + 395 + 2395 + 12395

To get the new terms, with n being the length of str, you are including the substrings made up of the 0-based index ranges of characters in str: (n-1,n-1), (n-2,n-1), (n-3,n-1), ... (n-n, n-1).

You can write a function to get the sum of the integers formed from the substring index ranges. Calling that function g(str), you can write the function recursively as f(str) = f(str.substring(0, str.length - 1)) + g(str) when str.length > 1, and the base case with str.length == 1 would just return the integer value of str. (The parameters of substring are the start index of a character in str and the length of the resulting substring.)

For the example Solve("12395"), the recursive equation f(str) = f(str.substring(0, str.length - 1)) + g(str) yields:

f("12395") =
f("1239") + g("12395") =
(f("123") + g("1239")) + g("12395") =
((f("12") + g("123")) + g("1239")) + g("12395") =
(((f("1") + g("12")) + g("123")) + g("1239")) + g("12395") =
1 + (2 + 12) + (3 + 23 + 123) + (9 + 39 + 239 + 1239) + (5 + 95 + 395 + 2395 + 12395)


问:
Declare and get static variable in JSP
Is there any way in JSP to declare static variable apart from <%! int like=0;%>? Is there any tag in custom tags to declare static variable on JSP pages?

If not and if I declare my static integer variable 'like' this way <%! int like=0;%>, is there any way I get this variable value using EL like ${like}? I want this value in my JQuery function, and I know I can get this value using <%=like>, but I need other way.

答:
In a JSP use ${staticVar.ClassName_staticPropertyName}
During context initialization do:

```<code>servletContext.setAttribute("staticVar", new AbstractMap<String,Object>() {
    @Override
    public Set<Map.Entry<String, Object>> entrySet() {
        throw new UnsupportedOperationException();
    }
    @Override
    public String get(Object key) {
        return methodToGetStaticVariableUsingReflection(key)
    }
}
</code>```

Title: Declare and get static variable in JSP

Body:
In a JSP use ${staticVar.ClassName_staticPropertyName}
During context initialization do:

servletContext.setAttribute("staticVar", new AbstractMap&lt;String,Object>() {
    @Override
    public Set&lt;Map.Entry<String, Object>> entrySet() {
        throw new UnsupportedOperationException();
    }
    @Override
    public String get(Object key) {
        return methodToGetStaticVariableUsingReflection(key)
    }
}


问:
Sass maps output
I have a map of styles for each header elemenet:

```<code>$header: (
    h1: (
        color: black,
        font-size: 13px
    ),
     h2: (
        color: black,
        font-size: 10px
    ),
    .....
</code>```

I wish to output these like so:

```<code>@each $label, $map in $header {
    color: map-get($map, color);
    font-size: map-get($map, font-size);
}
</code>```

The above gives a syntax error. I'm not sure what's wrong with it.

Also is it possible to spit out the color and font size for each h tag?

答:
In your current code, you are just trying to print the css properties and forgetting to print the selectors(h1, h2...) which is why it's throwing syntax error.

Here is the updated SASS,

```<code>@each $label, $map in $header {
  #{$label} {
    color: map-get($map, color);
    font-size: map-get($map, font-size);
  }
}
</code>```

Title: Sass maps output

Body:
I have a map of styles for each header elemenet:

$header: (
    h1: (
        color: black,
        font-size: 13px
    ),
     h2: (
        color: black,
        font-size: 10px
    ),
    .....

I wish to output these like so:

@each $label, $map in $header {
    color: map-get($map, color);
    font-size: map-get($map, font-size);
}

The above gives a syntax error. I'm not sure what's wrong with it.

Also is it possible to spit out the color and font size for each h tag?

Body:
In your current code, you are just trying to print the css properties and forgetting to print the selectors(h1, h2...) which is why it's throwing syntax error.

Here is the updated SASS,

@each $label, $map in $header {
  #{$label} {
    color: map-get($map, color);
    font-size: map-get($map, font-size);
  }
}


问:
Format Error for Input into Keras using 4-channel DNA data
I have DNA data that I am trying to input into Keras, and I have one-hot encoded it such that each DNA sequence is 4 channels (one for each type of nucleotide). I followed some of the tutorials, but I seem to be having a formatting issue. Perhaps someone could help me out? This is the first time I've tried inputting my own data into Keras. My data looks like this:

print(x_train.shape)
(1509, 4, 476)
print(y_train.shape)
(1509,)

And my model (so far) looks like this:

```<code>###Setup Keras to create a convolutional recurrent NN
# set parameters:
batch_size = 32
filters = (32, 1, 2) #(number of filters, rows per convolution kernel, columns per convolution kernel)
kernel_size = 16
x_shape = (1509, 1, 476, 4) #(samples, height, width, depth)
epochs = 3

#declare model
model = Sequential()

#CNN Input layer
model.add(Conv2D(filters,
                 kernel_size,
                 padding='same',
                 activation='relu',
                 strides=(1,0),
                 input_shape=x_shape))
print(model.output_shape)
</code>```

but I get the following error:

```<code>ValueError: Input 0 is incompatible with layer conv2d_0: expected ndim=4, found ndim=5
</code>```

I am unclear on why the model is finding 5 dimensions for the input_shape argument when I specify 4 dimensions. What am I missing?

答:
You shouldn't include the number of samples in the input_shape argument. This is what the error means.
The batch size dimension is added automaticaly.

Also, you should reshape your x_train table to match the input_shape :

```<code>x_train = np.reshape(np.transpose(x_train, (0, 2, 1)), (x_train.shape[0], 1, x_train.shape[1], x_train.shape[2]))
</code>```

That way I first transposed the array into (1509, 476, 4) then added a dimension : (1509, 1, 476, 4)

I hope this helps

Body:
I have DNA data that I am trying to input into Keras, and I have one-hot encoded it such that each DNA sequence is 4 channels (one for each type of nucleotide). I followed some of the tutorials, but I seem to be having a formatting issue. Perhaps someone could help me out? This is the first time I've tried inputting my own data into Keras. My data looks like this:

print(x_train.shape)
(1509, 4, 476)
print(y_train.shape)
(1509,)

And my model (so far) looks like this:

###Setup Keras to create a convolutional recurrent NN
# set parameters:
batch_size = 32
filters = (32, 1, 2) #(number of filters, rows per convolution kernel, columns per convolution kernel)
kernel_size = 16
x_shape = (1509, 1, 476, 4) #(samples, height, width, depth)
epochs = 3

#declare model
model = Sequential()

#CNN Input layer
model.add(Conv2D(filters,
                 kernel_size,
                 padding='same',
                 activation='relu',
                 strides=(1,0),
                 input_shape=x_shape))
print(model.output_shape)

but I get the following error:

ValueError: Input 0 is incompatible with layer conv2d_0: expected ndim=4, found ndim=5

I am unclear on why the model is finding 5 dimensions for the input_shape argument when I specify 4 dimensions. What am I missing?

Body:
You shouldn't include the number of samples in the input_shape argument. This is what the error means.
The batch size dimension is added automaticaly.

Also, you should reshape your x_train table to match the input_shape :

x_train = np.reshape(np.transpose(x_train, (0, 2, 1)), (x_train.shape[0], 1, x_train.shape[1], x_train.shape[2]))

That way I first transposed the array into (1509, 476, 4) then added a dimension : (1509, 1, 476, 4)

I hope this helps


问:
Listview item background color change on condition
```<code>mydb = new Databaseop(Main15Activity.this);
    Intent i = getIntent();
    final String rname = i.getStringExtra("rname");
    t1.setText(rname);
    Databaseop dp = new Databaseop(ctx);
    mydb = new Databaseop(Main15Activity.this);

    Cursor data = mydb.getListContents(dp, rname);
    if (data.getCount() == 0) {
        Toast.makeText(Main15Activity.this, "There are no contents in this list!", Toast.LENGTH_LONG).show();
    } else {
        while (data.moveToNext()) {
            String theListcon = data.getString(0);
          final  String[] contents = convertStringToArray(theListcon);
            listAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contents){@Override
            public View getView(int position , View convertView, ViewGroup parent){
                View view=super.getView(position, convertView, parent);
                TextView textView=(TextView)view.findViewById(android.R.id.text1);
                textView.setTextColor(Color.WHITE);
                String content=getItem(position);

                if(content.equals(tagcontent))
                    {
                        textView.setBackgroundColor(Color.GREEN);
                        Intent intent=getIntent();
                        String user=intent.getStringExtra("name");
                        String rank=intent.getStringExtra("rank");
                        Databaseop dp = new Databaseop(ctx);
                        dp.reports(dp, user, rank, tagcontent);
                        Toast.makeText(Main15Activity.this, "one room visited", Toast.LENGTH_SHORT).show();

                    }

                return view;
            }
            };
            l1.setAdapter(listAdapter);
</code>```

<p>I want to match a string with the list view items and if the item matches with the string the background of the item must turn green and my items in the list view are from database. </p>

答:
you have to set else condition while you set background to item list.

Like below.

```<code>if(condition to compare string){
 // set item color as green
}
else{
 // set normal color to item
}
</code>```

Body:
mydb = new Databaseop(Main15Activity.this);
    Intent i = getIntent();
    final String rname = i.getStringExtra("rname");
    t1.setText(rname);
    Databaseop dp = new Databaseop(ctx);
    mydb = new Databaseop(Main15Activity.this);

    Cursor data = mydb.getListContents(dp, rname);
    if (data.getCount() == 0) {
        Toast.makeText(Main15Activity.this, "There are no contents in this list!", Toast.LENGTH_LONG).show();
    } else {
        while (data.moveToNext()) {
            String theListcon = data.getString(0);
          final  String[] contents = convertStringToArray(theListcon);
            listAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contents){@Override
            public View getView(int position , View convertView, ViewGroup parent){
                View view=super.getView(position, convertView, parent);
                TextView textView=(TextView)view.findViewById(android.R.id.text1);
                textView.setTextColor(Color.WHITE);
                String content=getItem(position);

                if(content.equals(tagcontent))
                    {
                        textView.setBackgroundColor(Color.GREEN);
                        Intent intent=getIntent();
                        String user=intent.getStringExtra("name");
                        String rank=intent.getStringExtra("rank");
                        Databaseop dp = new Databaseop(ctx);
                        dp.reports(dp, user, rank, tagcontent);
                        Toast.makeText(Main15Activity.this, "one room visited", Toast.LENGTH_SHORT).show();

                    }

                return view;
            }
            };
            l1.setAdapter(listAdapter);

I want to match a string with the list view items and if the item matches with the string the background of the item must turn green and my items in the list view are from database.

Body:
you have to set else condition while you set background to item list.

Like below.

if(condition to compare string){
 // set item color as green
}
else{
 // set normal color to item
}


问:
trouble creating table using foreign key
```<code>create table department
(
dept_name varchar(20),
building varchar(20),
budget numeric(12, 2),
primary key(dept_name)
);
</code>```

This is table that i created before...

now i am writing this:

```<code>create table course
(
course_id varchar(7),
title varchar(50),
dept_name varchar(20),
credits numeric(2, 0),
primary key(course_id),
foreign key (dept_name) references department
);
</code>```

an it shows :

ERROR 1005 (HY000): Can't create table 'satyarth.course' (errno: 150)

答:
You're missing a portion of the FOREIGN KEY requirement, as you cannot simply refer to another table:</p>

```<code>foreign key (dept_name) references department(dept_name)
</code>```

Body:
create table department
(
dept_name varchar(20),
building varchar(20),
budget numeric(12, 2),
primary key(dept_name)
);

This is table that i created before...

now i am writing this:

create table course
(
course_id varchar(7),
title varchar(50),
dept_name varchar(20),
credits numeric(2, 0),
primary key(course_id),
foreign key (dept_name) references department
);

an it shows :

ERROR 1005 (HY000): Can't create table 'satyarth.course' (errno: 150)

Body:
You're missing a portion of the FOREIGN KEY requirement, as you cannot simply refer to another table:

foreign key (dept_name) references department(dept_name)


问:
Loop through a JSON object array and takeout objects based on condition
I am trying to figure out a way to loop through a JSON object and pickout the objects which meets a particular condition. I need to create a new JSON with the result.
I have a tree component with check boxes in nodes. I want to extract only the nodes which are checked. The checked nodes can be identified by "isSelected": true

My JSON is - https://pastebin.com/RHR2tAxZ

I am new to Angular and have not handled a JSON loop before. Can anyone help me to sort this out?

答:
Just use the **isSelected property on the checkbox,

```<code>   <input type="checkbox" ng-model="listitem.isSelected" >
</code>```

DEMO

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope, $http) {
$scope.newList =[];
 $scope.list=
    [
  {
    "node": [
      {
        "node": [],
        "pageName": "Upload Files",
        "isSelected": false,
        "node1": [],
        "pagedefinitionId": 7
      },
      {
        "node": [],
        "pageName": "Download Files",
        "isSelected": false,
        "node1": [],
        "pagedefinitionId": 8
      }
    ],
    "pageName": "Manage Files",
    "isSelected": false,
    "node1": [],
    "pagedefinitionId": 4
  },
  {
    "node": [],
    "pageName": "Vendor Request",
    "isSelected": false,
    "node1": [
      {
        "isSelected": false,
        "pageControlId": 89,
        "elementIdentifier": "vendorRequest.add",
        "pageDefinitionId": 355
      },
      {
        "isSelected": false,
        "pageControlId": 90,
        "elementIdentifier": "vendorRequest.submitForApproval",
        "pageDefinitionId": 355
      },
      {
        "isSelected": false,
        "pageControlId": 91,
        "elementIdentifier": "vendorRequest.complete",
        "pageDefinitionId": 355
      }
    ],
    "pagedefinitionId": 355
  }
];
$scope.getselected = function(){
  angular.forEach( $scope.list,function(key,value){
  console.log(key);
      if(key.isSelected){
        $scope.newList.push(key);
      }
  });
}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <div ng-app="myApp" ng-controller="AppCtrl">
 <div ng-repeat ="listitem in list">
  <label>
     {{ listitem.pageName }}
   </label>
    <input type="checkbox" ng-model="listitem.isSelected" >
 </div>
  <button ng-click="getselected()">getSelected</button>
   <h1>selected ones{{newList}}</h1>
  </div>
</body>

</html></code>```

Body:
Just use the **isSelected property on the checkbox,

   <input type="checkbox" ng-model="listitem.isSelected" >

DEMO

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope, $http) {
$scope.newList =[];
 $scope.list=
    [
  {
    "node": [
      {
        "node": [],
        "pageName": "Upload Files",
        "isSelected": false,
        "node1": [],
        "pagedefinitionId": 7
      },
      {
        "node": [],
        "pageName": "Download Files",
        "isSelected": false,
        "node1": [],
        "pagedefinitionId": 8
      }
    ],
    "pageName": "Manage Files",
    "isSelected": false,
    "node1": [],
    "pagedefinitionId": 4
  },
  {
    "node": [],
    "pageName": "Vendor Request",
    "isSelected": false,
    "node1": [
      {
        "isSelected": false,
        "pageControlId": 89,
        "elementIdentifier": "vendorRequest.add",
        "pageDefinitionId": 355
      },
      {
        "isSelected": false,
        "pageControlId": 90,
        "elementIdentifier": "vendorRequest.submitForApproval",
        "pageDefinitionId": 355
      },
      {
        "isSelected": false,
        "pageControlId": 91,
        "elementIdentifier": "vendorRequest.complete",
        "pageDefinitionId": 355
      }
    ],
    "pagedefinitionId": 355
  }
];
$scope.getselected = function(){
  angular.forEach( $scope.list,function(key,value){
  console.log(key);
      if(key.isSelected){
        $scope.newList.push(key);
      }
  });
}
});

<!DOCTYPE html>
<html>
<head>
</head>

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <div ng-app="myApp" ng-controller="AppCtrl">
 <div ng-repeat ="listitem in list">
  <label>
     {{ listitem.pageName }}
   </label>
    <input type="checkbox" ng-model="listitem.isSelected" >
 </div>
  <button ng-click="getselected()">getSelected</button>
   <h1>selected ones{{newList}}</h1>
  </div>
</body>

</html>


问:
Virtual functions and performance - C++
In my class design, I use abstract classes and virtual functions extensively. I had a  feeling that virtual functions affects the performance. Is this true? But I think this performance difference is not noticeable and looks like I am doing premature optimization. Right?</p>

答:
absolutely. It was a problem way back when computers ran at 100Mhz, as every method call required a lookup on the vtable before it was called. But today.. on a 3Ghz CPU that has 1st level cache with more memory than my first computer had? Not at all. Allocating memory from main RAM will cost you more time than if all your functions were virtual.

Its like the old, old days where people said structured programming was slow because all the code was split into functions, each function required stack allocations and  a function call!

The only time I would even think of bothering to consider the performance impact of a virtual function, is if it was very heavily used and instantiated in templated code that ended up throughout everything. Even then, I wouldn't spend too much effort on it!

PS think of other 'easy to use' languages - all their methods are virtual under the covers and they don't crawl nowadays.

OwnerDisplayName: Appu

Title: Virtual functions and performance - C++

LastEditorDisplayName: Serge

OwnerDisplayName: gbjbaanb


问:
mysql5.58 unstart server in mac os 10.6.5
MySQL 5.5.8 uninstall MAC OS 10.6.5,restart computer is message “/Library/StartupItems/MySQLCOM” has not been started because it does not have the proper security settings. i set
sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit /usr/local/mysql/support-files/mysql.server

Locate the configuration defining the basedir and set the following :
basedir=/usr/local/mysql
datadir=/usr/local/mysql/data

bug i click the mysql preference start mysql server isn't start

and i sudo chown -R root:wheel /Library/StartupItems/MySQLCOM and restart again ,not warning message but mysql server not start ,why?

答:
I just installed MySQL 5.5.8 (mysql-5.5.8-osx10.6-x86_64.dmg) on Mac os X 10.6.5 and also had the problem that MySQL was not starting.

After reading this post:
http://forums.mysql.com/read.php?11,399397,399606#msg-399606

Modify the mysql.server script file
  using the following command :

```<code>sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit /usr/local/mysql/support-files/mysql.server
</code>```

Locate the configuration defining the
  basedir and set the following:

```<code>basedir=/usr/local/mysql
datadir=/usr/local/mysql/data
</code>```

Save the file and start the mysql
  server in the system preferences /
  terminal

This solved the problem.

Hope this helps. Thanks to http://forums.mysql.com/profile.php?11,3773555 !

Body:
I just installed MySQL 5.5.8 (mysql-5.5.8-osx10.6-x86_64.dmg) on Mac os X 10.6.5 and also had the problem that MySQL was not starting.

After reading this post:
http://forums.mysql.com/read.php?11,399397,399606#msg-399606

Modify the mysql.server script file
  using the following command :

sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit /usr/local/mysql/support-files/mysql.server

Locate the configuration defining the
  basedir and set the following:

basedir=/usr/local/mysql
datadir=/usr/local/mysql/data

Save the file and start the mysql
  server in the system preferences /
  terminal

This solved the problem.

Hope this helps. Thanks to http://forums.mysql.com/profile.php?11,3773555 !


问:
How can I test network errors in fetch api?
I have been successfully able to test a resolved promise on a simple application I have been working on to learn ES6 but been having issues testing the case where there may be network errors.

I wrote this test case:

```<code>import {Weather} from '../js/weather';

import chai from 'chai';
import sinon from 'sinon';
import * as chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);

let assert = chai.assert;
let should = chai.should;

describe('weatherbot-1', function () {
    beforeEach(function () {
        sinon.stub(window, 'fetch');

        let data = '{"cod": "400", "message": "Nothing to geocode"}';
        let res = new window.Response(data, {
            ok: false,
            status: 400,
            headers: {
                'Content-type': 'application/json'
            }
        });

        window.fetch.returns(Promise.reject(res));
    });

    afterEach(function () {
       window.fetch.restore();
    });

    it('should ensure that promise is rejected', function () {
        let weather = new Weather(0, 0);

        return assert.isRejected(weather.getWeather(), 'Rejected');
    });
});
</code>```

The method in question is:

```<code>getWeather() {
        let headers = new Headers();

        let init = {
            method: 'GET',
            headers: headers,
            cache: 'default'
        };

        let url = 'http://localhost:8080/weather?lat=' + '' + '&lon=' + this.longitude;

        return fetch(url, init).then(function (response) {
            return response.json();
        }).catch((error) => {
            return error;
        });
}
</code>```

For testing the promise, I am using chai-as-promised & chai with mocha & sinon to stub the fetch api.

Whenever I run the test I get this error:

```<code>AssertionError: expected promise to be rejected with an error including 'Rejected' but it was fulfilled with { type: 'default',
      url: '',
      redirected: false,
      status: 400,
      ok: false,
      statusText: 'OK',
      headers:
       { append: [Function: append],
         delete: [Function: delete],
         get: [Function: get],
         getAll: [Function: getAll],
         has: [Function: has],
         set: [Function: set],
         keys: [Function: keys],
         values: [Function: values],
         entries: [Function: entries],
         forEach: [Function: forEach] },
      body: {},
      bodyUsed: false,
      clone: [Function: clone],
      arrayBuffer: [Function: arrayBuffer],
      blob: [Function: blob],
      json: [Function: json],
      text: [Function: text] }
</code>```

From what it looks like, the Promise.reject() may not be working properly. Is there any other way I could test network errors?

答:
The problem is in getWeather, not the test:

```<code>return fetch(url, init)
  .then(function (response) {
    return response.json();
  })
  .catch((error) => {
    return error;
  })
</code>```

Promise#catch returns a resolved Promise, because its job is to handle errors. The rest of the application should be able to function after catching a rejection, just like with try/catch.

If you want the rejection to reach the test, your code shouldn't catch the rejection:

```<code>return fetch(url, init)
  .then(function (response) {
    return response.json();
  })
</code>```

In general you should only catch where you can properly handle the error. In this example you might want to handle the rejection in a view where you can display an error message.

Also, your code models an invalid situation. fetch returns a resolved Promise for all valid HTTP responses including non-200 status.

It does reject when it cannot make a connection at all, e.g. fetch("http://sdfdsfsd"). In this case it rejects with an Error object.

To properly test a fetch rejection you should simulate this condition and have the stub return Promise.reject(new Error("a message")).

Body:
I have been successfully able to test a resolved promise on a simple application I have been working on to learn ES6 but been having issues testing the case where there may be network errors.

I wrote this test case:

import {Weather} from '../js/weather';

import chai from 'chai';
import sinon from 'sinon';
import * as chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);

let assert = chai.assert;
let should = chai.should;

describe('weatherbot-1', function () {
    beforeEach(function () {
        sinon.stub(window, 'fetch');

        let data = '{"cod": "400", "message": "Nothing to geocode"}';
        let res = new window.Response(data, {
            ok: false,
            status: 400,
            headers: {
                'Content-type': 'application/json'
            }
        });

        window.fetch.returns(Promise.reject(res));
    });

    afterEach(function () {
       window.fetch.restore();
    });

    it('should ensure that promise is rejected', function () {
        let weather = new Weather(0, 0);

        return assert.isRejected(weather.getWeather(), 'Rejected');
    });
});

The method in question is:

getWeather() {
        let headers = new Headers();

        let init = {
            method: 'GET',
            headers: headers,
            cache: 'default'
        };

        let url = 'http://localhost:8080/weather?lat=' + '' + '&lon=' + this.longitude;

        return fetch(url, init).then(function (response) {
            return response.json();
        }).catch((error) => {
            return error;
        });
}

For testing the promise, I am using chai-as-promised & chai with mocha & sinon to stub the fetch api.

Whenever I run the test I get this error:

AssertionError: expected promise to be rejected with an error including 'Rejected' but it was fulfilled with { type: 'default',
      url: '',
      redirected: false,
      status: 400,
      ok: false,
      statusText: 'OK',
      headers:
       { append: [Function: append],
         delete: [Function: delete],
         get: [Function: get],
         getAll: [Function: getAll],
         has: [Function: has],
         set: [Function: set],
         keys: [Function: keys],
         values: [Function: values],
         entries: [Function: entries],
         forEach: [Function: forEach] },
      body: {},
      bodyUsed: false,
      clone: [Function: clone],
      arrayBuffer: [Function: arrayBuffer],
      blob: [Function: blob],
      json: [Function: json],
      text: [Function: text] }

From what it looks like, the Promise.reject() may not be working properly. Is there any other way I could test network errors?

Body:
The problem is in getWeather, not the test:

return fetch(url, init)
  .then(function (response) {
    return response.json();
  })
  .catch((error) => {
    return error;
  })

Promise#catch returns a resolved Promise, because its job is to handle errors. The rest of the application should be able to function after catching a rejection, just like with try/catch.

If you want the rejection to reach the test, your code shouldn't catch the rejection:

return fetch(url, init)
  .then(function (response) {
    return response.json();
  })

In general you should only catch where you can properly handle the error. In this example you might want to handle the rejection in a view where you can display an error message.

Also, your code models an invalid situation. fetch returns a resolved Promise for all valid HTTP responses including non-200 status.

It does reject when it cannot make a connection at all, e.g. fetch("http://sdfdsfsd"). In this case it rejects with an Error object.

To properly test a fetch rejection you should simulate this condition and have the stub return Promise.reject(new Error("a message")).


问:
to find unequal partitions of an integer in php
I have total partitions of an integer and I want only those partitions which have all the values unequal.

For ex.

-Partitions of 3 are {1,1,1,1},{2,2},{3,1},{1,1,2} and {4}.

So, the required unequal partitions are {3,1} and {4} because they contain no equal elements.I can filter the partitions to get the desired result, but I want some efficient way to find all the partitions, which have no equal terms in them, without finding all the partitions. I have searched the net and StackOverflow but nothing states exactly the problem that I am facing. Every idea is appreciated. Thanks.

答:
I would just use sets for this:</p>

```<code>partitions = [[1,1,1,1], [2,2], [3,1], [1,1,2], [4]]

unique_partions = [p for p in partitions if len(p) == len(set(p))]
</code>```

Body:
I would just use sets for this:

partitions = [[1,1,1,1], [2,2], [3,1], [1,1,2], [4]]

unique_partions = [p for p in partitions if len(p) == len(set(p))]


问:
Why isn't move_upload_file is always returning false in the given code?
I am trying to upload an image using php and mysql and below is the code used..

index.php

```<code><form action="submit.php" enctype="multipart/form-data" method="post">

<table style="border-collapse: collapse; font: 12px Tahoma;" border="1" cellspacing="5" cellpadding="5">
<tbody><tr>
<td>
<input name="uploadedimage" type="file">
</td>

</tr>

<tr>
<td>
<input name="Upload Now" type="submit" value="Upload Image">
</td>
</tr>

</tbody></table>

</form>
</code>```

submit.php

```<code><?php

include("mysqlconnect.php");

function GetImageExtension($imagetype) {
    if (empty($imagetype))
        return false;
    switch ($imagetype) {
        case 'image/bmp': return '.bmp';
        case 'image/gif': return '.gif';
        case 'image/jpeg': return '.jpg';
        case 'image/png': return '.png';
        default: return false;
    }
}

if (!empty($_FILES["uploadedimage"]["name"])) {

    $file_name = $_FILES["uploadedimage"]["name"];
    $temp_name = $_FILES["uploadedimage"]["tmp_name"];
    $imgtype = $_FILES["uploadedimage"]["type"];
    $ext = GetImageExtension($imgtype);
    $imagename = date("d-m-Y") . "-" . time() . $ext;
    $target_path = "images/" . $imagename;

    if (move_uploaded_file($_FILES['uploadedimage']['tmp_name'], $target_path)) {
        $detail = date("Y-m-d");
        $sql = "INSERT INTO `image_upload`(`id`, `image`, `detail`) VALUES (NULL,'$target_path','$detail')";
        if (!$conn->query($sql)) {
            echo $conn->error;
        } else {
            echo "Successfully inserted. ";
        }
    } else {

        exit("Error While uploading image on the server");
    }
}
?>
</code>```

Table structure:

```<code>#   Name        Type    Collation     Attributes    Null Default  Extra
1   id(Primary) int(11)                              No   None    AUTO_INCREMENT
2   image       blob                                 Yes  NULL
3   detail     varchar(500) utf8_general_ci          Yes  NULL
</code>```

Every time I execute this it always shows me "Error While uploading image on the server" I don't understand why. Can someone let me know where am I going wrong and how can I improve my implementation?
Thanks in advance.

答:
add this line before moving file.

```<code>if (!file_exists($target_path )) { mkdir($target_path , 0777, true); }
</code>```

this will add the folder if not exist.. with all permissions.

Body:
I am trying to upload an image using php and mysql and below is the code used..

index.php

<form action="submit.php" enctype="multipart/form-data" method="post">

<input name="uploadedimage" type="file">

<input name="Upload Now" type="submit" value="Upload Image">

</form>

submit.php

<?php

include("mysqlconnect.php");

function GetImageExtension($imagetype) {
    if (empty($imagetype))
        return false;
    switch ($imagetype) {
        case 'image/bmp': return '.bmp';
        case 'image/gif': return '.gif';
        case 'image/jpeg': return '.jpg';
        case 'image/png': return '.png';
        default: return false;
    }
}

if (!empty($_FILES["uploadedimage"]["name"])) {

    $file_name = $_FILES["uploadedimage"]["name"];
    $temp_name = $_FILES["uploadedimage"]["tmp_name"];
    $imgtype = $_FILES["uploadedimage"]["type"];
    $ext = GetImageExtension($imgtype);
    $imagename = date("d-m-Y") . "-" . time() . $ext;
    $target_path = "images/" . $imagename;

    if (move_uploaded_file($_FILES['uploadedimage']['tmp_name'], $target_path)) {
        $detail = date("Y-m-d");
        $sql = "INSERT INTO `image_upload`(`id`, `image`, `detail`) VALUES (NULL,'$target_path','$detail')";
        if (!$conn->query($sql)) {
            echo $conn->error;
        } else {
            echo "Successfully inserted. ";
        }
    } else {

        exit("Error While uploading image on the server");
    }
}
?>

Table structure:

#   Name        Type    Collation     Attributes    Null Default  Extra
1   id(Primary) int(11)                              No   None    AUTO_INCREMENT
2   image       blob                                 Yes  NULL
3   detail     varchar(500) utf8_general_ci          Yes  NULL

Every time I execute this it always shows me "Error While uploading image on the server" I don't understand why. Can someone let me know where am I going wrong and how can I improve my implementation?
Thanks in advance.

Body:
add this line before moving file.

if (!file_exists($target_path )) { mkdir($target_path , 0777, true); }

this will add the folder if not exist.. with all permissions.


答: You can do it in your adapter. When the cell is inflated, check if the string matches. If it does, fetch the view you want, and alter its background accordingly.</p>

Title: Listview item background color change on condition


问:
Intellij Idea doesn't see values in .yaml file, but successfully references .properties in @Value
I'm using @Value annotation in my spring boot application.

If I'm using application.properties file then Intellij Idea can go to those values if I Сtrl-Click them. But it doesn't work if I use application.yaml.

答:
i think that you use the community edition and i am not sure but i think this only supports .properties files.

OR what i see is that your file ending is .yml, rename it to .yaml and it should work if you use the ultimate edition


问:
Everything works fine but when I click edit button, a comma (,) is add every time. I would not find what going wrong?
I am trying to build a note taking app. I have created Note And Board component. Everything works fine but when I click edit button, a comma (,) is add every time. I would not find what's going wrong?

Here's my code:

class Note extends React.Component{
 constructor(){
  super();
  this.state={
   editing:true
  }
 }
 edit(){
  this.setState({editing: false});
 }
 save(){
  var val =this.refs.newText.value;
  console.log(this.refs.newText.value)
  this.props.onChange(val,this.props.index)
  this.setState({editing: true});
 }
 delete(){
  this.props.onRemove(this.props.index)
 }
 renderDisplay(){
  return(

{this.props.children}

      <button onClick={this.edit.bind(this)}>Edit</button>
      <button onClick={this.delete.bind(this)} className="danger">Delete</button>

   );
 }
 renderForm(){
  return(

     <textarea ref="newText" defaultValue={this.props.children}></textarea>
     <button onClick={this.save.bind(this)}>Save </button>

   );
 }
 render(){
  // this.state.editing ? return this.renderDisplay() : return this.renderForm();
  if(this.state.editing){
   return this.renderDisplay();
  }else{
   return this.renderForm();
  }
 }
}

class Board extends React.Component{
 constructor(){
  super();
  this.state={
   notes: ["Hello"]
  }
 }
 update(newText,i){
  var arr = this.state.notes;
  arr[i]=newText;
  this.setState({notes:arr});
 }
 remove(i){
  var arr =this.state.notes;
  arr.splice(i,1);
  this.setState({notes:arr});
 }
 eachNote(note,i){
  return(
    <Note key={i} index={i} onChange={this.update.bind(this)} onRemove= {this.remove.bind(this)}> {note}</Note>
   )
 }
 add(text){
  // alert("hello");
  var arr = this.state.notes;
  arr.push(text);
  this.setState({notes:arr});
 }
 render(){
  return

   <button onClick={this.add.bind(this,"New Note")}>Add</button>

   {
    this.state.notes.map(this.eachNote.bind(this))
   }

 }
}

ReactDOM.render(<Board ></Board>, document.getElementById('root'));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
 box-sizing: border-box;

}
body,html{
 margin:0;
 padding: 0;
 height:100%;
}
.board{
 background:#fbd14b;
 height:100%;
 min-height: 100vh;
 width:100%;
 padding:20px;
}
.note{
 background:yellow;
 color: #333;
 width: 200px;
 padding: 10px;
 margin-bottom: 20px;
 box-shadow: 0px 0px 15px 5px rgba(0,0,0,.1);
 display: inline-block;
 margin-right: 20px;
 vertical-align: top;
 min-height: 150px;
}
button{
 border:0;
 box-shadow: none;
 padding: 5px 10px;
 background:#3ac569;
 color: #fff;
 margin:0 5px 5px 0;
}
button:hover{
 cursor: pointer;
}
.danger{
 background: #E71D36;
}</code>```

```

答:
It's happening because of the space you provide before {note},

```<code><Note key={i} index={i} onChange={this.update.bind(this)} onRemove= {this.remove.bind(this)}> {note}</Note>
</code>```

that changes children to Note in an array,

```<code>[' ', 'Hello']
</code>```

So when you do defaultValue = {this.props.children}, it converts array to string by performing this.props.children.join(',') and that's how you are getting , in your result.

You can fix this by removing space before {Note}

class Note extends React.Component{
 constructor(props){
  super();
  this.state={
   editing:true
  }
 }
 edit(){
  this.setState({editing: false});
 }
 save(){
  var val =this.refs.newText.value;
  console.log(this.refs.newText.value)
  this.props.onChange(val,this.props.index)
  this.setState({editing: true});
 }
 delete(){
  this.props.onRemove(this.props.index)
 }
 renderDisplay(){
  return(

{this.props.children}

      <button onClick={this.edit.bind(this)}>Edit</button>
      <button onClick={this.delete.bind(this)} className="danger">Delete</button>

   );
 }
 renderForm(){
  return(

     <textarea ref="newText" defaultValue={this.props.children}></textarea>
     <button onClick={this.save.bind(this)}>Save </button>

   );
 }
 render(){
  // this.state.editing ? return this.renderDisplay() : return this.renderForm();
  if(this.state.editing){
   return this.renderDisplay();
  }else{
   return this.renderForm();
  }
 }
}

class Board extends React.Component{
 constructor(){
  super();
  this.state={
   notes: ["Hello"]
  }
 }
 update(newText,i){
  var arr = this.state.notes;
  arr[i]=newText;
  this.setState({notes:arr});
 }
 remove(i){
  var arr =this.state.notes;
  arr.splice(i,1);
  this.setState({notes:arr});
 }
 eachNote(note,i){
  return(
    <Note key={i} index={i} onChange={this.update.bind(this)} onRemove= {this.remove.bind(this)}>{note}</Note>
   )
 }
 add(text){
  // alert("hello");
  var arr = this.state.notes;
  arr.push(text);
  this.setState({notes:arr});
 }
 render(){
  return

   <button onClick={this.add.bind(this,"New Note")}>Add</button>

   {
    this.state.notes.map(this.eachNote.bind(this))
   }

 }
}

ReactDOM.render(<Board ></Board>, document.getElementById('root'));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
 box-sizing: border-box;

}
body,html{
 margin:0;
 padding: 0;
 height:100%;
}
.board{
 background:#fbd14b;
 height:100%;
 min-height: 100vh;
 width:100%;
 padding:20px;
}
.note{
 background:yellow;
 color: #333;
 width: 200px;
 padding: 10px;
 margin-bottom: 20px;
 box-shadow: 0px 0px 15px 5px rgba(0,0,0,.1);
 display: inline-block;
 margin-right: 20px;
 vertical-align: top;
 min-height: 150px;
}
button{
 border:0;
 box-shadow: none;
 padding: 5px 10px;
 background:#3ac569;
 color: #fff;
 margin:0 5px 5px 0;
}
button:hover{
 cursor: pointer;
}
.danger{
 background: #E71D36;
}</code>```

```

Body:
I am trying to build a note taking app. I have created Note And Board component. Everything works fine but when I click edit button, a comma (,) is add every time. I would not find what's going wrong?

Here's my code:

class Note extends React.Component{
 constructor(){
  super();
  this.state={
   editing:true
  }
 }
 edit(){
  this.setState({editing: false});
 }
 save(){
  var val =this.refs.newText.value;
  console.log(this.refs.newText.value)
  this.props.onChange(val,this.props.index)
  this.setState({editing: true});
 }
 delete(){
  this.props.onRemove(this.props.index)
 }
 renderDisplay(){
  return(

{this.props.children}

      <button onClick={this.edit.bind(this)}>Edit</button>
      <button onClick={this.delete.bind(this)} className="danger">Delete</button>

   );
 }
 renderForm(){
  return(

     <textarea ref="newText" defaultValue={this.props.children}></textarea>
     <button onClick={this.save.bind(this)}>Save </button>

   );
 }
 render(){
  // this.state.editing ? return this.renderDisplay() : return this.renderForm();
  if(this.state.editing){
   return this.renderDisplay();
  }else{
   return this.renderForm();
  }
 }
}

class Board extends React.Component{
 constructor(){
  super();
  this.state={
   notes: ["Hello"]
  }
 }
 update(newText,i){
  var arr = this.state.notes;
  arr[i]=newText;
  this.setState({notes:arr});
 }
 remove(i){
  var arr =this.state.notes;
  arr.splice(i,1);
  this.setState({notes:arr});
 }
 eachNote(note,i){
  return(
    <Note key={i} index={i} onChange={this.update.bind(this)} onRemove= {this.remove.bind(this)}> {note}</Note>
   )
 }
 add(text){
  // alert("hello");
  var arr = this.state.notes;
  arr.push(text);
  this.setState({notes:arr});
 }
 render(){
  return

   <button onClick={this.add.bind(this,"New Note")}>Add</button>

   {
    this.state.notes.map(this.eachNote.bind(this))
   }

 }
}

ReactDOM.render(<Board ></Board>, document.getElementById('root'));

*{
 box-sizing: border-box;

}
body,html{
 margin:0;
 padding: 0;
 height:100%;
}
.board{
 background:#fbd14b;
 height:100%;
 min-height: 100vh;
 width:100%;
 padding:20px;
}
.note{
 background:yellow;
 color: #333;
 width: 200px;
 padding: 10px;
 margin-bottom: 20px;
 box-shadow: 0px 0px 15px 5px rgba(0,0,0,.1);
 display: inline-block;
 margin-right: 20px;
 vertical-align: top;
 min-height: 150px;
}
button{
 border:0;
 box-shadow: none;
 padding: 5px 10px;
 background:#3ac569;
 color: #fff;
 margin:0 5px 5px 0;
}
button:hover{
 cursor: pointer;
}
.danger{
 background: #E71D36;
}

Body:
It's happening because of the space you provide before {note},

<Note key={i} index={i} onChange={this.update.bind(this)} onRemove= {this.remove.bind(this)}> {note}</Note>

that changes children to Note in an array,

[' ', 'Hello']

So when you do defaultValue = {this.props.children}, it converts array to string by performing this.props.children.join(',') and that's how you are getting , in your result.

You can fix this by removing space before {Note}

class Note extends React.Component{
 constructor(props){
  super();
  this.state={
   editing:true
  }
 }
 edit(){
  this.setState({editing: false});
 }
 save(){
  var val =this.refs.newText.value;
  console.log(this.refs.newText.value)
  this.props.onChange(val,this.props.index)
  this.setState({editing: true});
 }
 delete(){
  this.props.onRemove(this.props.index)
 }
 renderDisplay(){
  return(
    <div className="note">
     <p>{this.props.children}</p>
     <span>
      <button onClick={this.edit.bind(this)}>Edit</button>
      <button onClick={this.delete.bind(this)} className="danger">Delete</button>
     </span>
    </div>
   );
 }
 renderForm(){
  return(
    <div className="note">
     <textarea ref="newText" defaultValue={this.props.children}></textarea>
     <button onClick={this.save.bind(this)}>Save </button>
    </div>
   );
 }
 render(){
  // this.state.editing ? return this.renderDisplay() : return this.renderForm();
  if(this.state.editing){
   return this.renderDisplay();
  }else{
   return this.renderForm();
  }
 }
}

class Board extends React.Component{
 constructor(){
  super();
  this.state={
   notes: ["Hello"]
  }
 }
 update(newText,i){
  var arr = this.state.notes;
  arr[i]=newText;
  this.setState({notes:arr});
 }
 remove(i){
  var arr =this.state.notes;
  arr.splice(i,1);
  this.setState({notes:arr});
 }
 eachNote(note,i){
  return(
    <Note key={i} index={i} onChange={this.update.bind(this)} onRemove= {this.remove.bind(this)}>{note}</Note>
   )
 }
 add(text){
  // alert("hello");
  var arr = this.state.notes;
  arr.push(text);
  this.setState({notes:arr});
 }
 render(){
  return <div className="board">
   <button onClick={this.add.bind(this,"New Note")}>Add</button><br/>
   {
    this.state.notes.map(this.eachNote.bind(this))
   }

  </div>
 }
}

ReactDOM.render(<Board ></Board>, document.getElementById('root'));

*{
 box-sizing: border-box;

}
body,html{
 margin:0;
 padding: 0;
 height:100%;
}
.board{
 background:#fbd14b;
 height:100%;
 min-height: 100vh;
 width:100%;
 padding:20px;
}
.note{
 background:yellow;
 color: #333;
 width: 200px;
 padding: 10px;
 margin-bottom: 20px;
 box-shadow: 0px 0px 15px 5px rgba(0,0,0,.1);
 display: inline-block;
 margin-right: 20px;
 vertical-align: top;
 min-height: 150px;
}
button{
 border:0;
 box-shadow: none;
 padding: 5px 10px;
 background:#3ac569;
 color: #fff;
 margin:0 5px 5px 0;
}
button:hover{
 cursor: pointer;
}
.danger{
 background: #E71D36;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>


问:
Adding custom tab in uCommerce - Extending uCommerce
I have added a custom tab in uCommerce and followed all the steps that were mentioned here.

Everything is working fine but the only problem is the new tab is coming with square brackets on each side like this - [Order Line Status History]

Can anyone help me with this problem that how can I remove these brackets and from where they are coming as I haven't added them anywhere.

Thanks

答: It seems lige you're missing translation resource for the tabs. Try to take a look here: http://eureka.ucommerce.net/#!/question/1067/Adding-custom-resource-key-for-custom-added-tab</p>


问:
EntityFramework Core Database.EnsureCreated doesn't create database
I create a project with dotnetcore and entity framework core. I use MySql database and I added dependency to SapientGuardian.EntityFrameworkCore.MySql version 7.1.19.

I created a SeedData class where initialize my database:

```<code>public class SeedData
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (MyDbContext context = new MyDbContext(serviceProvider.GetRequiredService<DbContextOptions<MyDbContext>>())) {
            context.Database.EnsureCreated();
        }
    }
}
</code>```

The call to seed class:

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // Other code

    SeedData.Initialize(app.ApplicationServices);
}
</code>```

And the configuration of service:

```<code>public void ConfigureServices(IServiceCollection services)
{
    // Other code

    // Add database
    services.AddDbContext<MyDbContext>(options => {
            options.UseMySQL(Configuration.GetConnectionString("DefaultConnection"));
    });

    services.AddScoped<Microsoft.EntityFrameworkCore.Infrastructure.IDbContextOptions, Microsoft.EntityFrameworkCore.DbContextOptions<MyDbContext>>();
}
</code>```

When I start the project I get an exception on EnsureCreate call. Exception message say Authentication failed but if I manually create database (without tables) my connection string works fine and EnsureCreated simply create tables for my entities.

What's wrong? It's a problem with SapientGuardian.EntityFrameworkCore.MySql?

答:
I had the same problem you described. It looks like the SapientGuardian provider might simply have an incomplete implementation in this version. </p>

<p>The SapientGuardian project's readme file actually suggests using a more actively maintained provider such as Pomelo.EntityFrameworkCore.MySql. So I switched my project to Pomelo. Now the call to EnsureCreated creates the database as expected and does not have an authentication failed exception. </p>

Body:
I create a project with dotnetcore and entity framework core. I use MySql database and I added dependency to SapientGuardian.EntityFrameworkCore.MySql version 7.1.19.

I created a SeedData class where initialize my database:

public class SeedData
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (MyDbContext context = new MyDbContext(serviceProvider.GetRequiredService<DbContextOptions<MyDbContext>>())) {
            context.Database.EnsureCreated();
        }
    }
}

The call to seed class:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // Other code

    SeedData.Initialize(app.ApplicationServices);
}

And the configuration of service:

public void ConfigureServices(IServiceCollection services)
{
    // Other code

    // Add database
    services.AddDbContext<MyDbContext>(options => {
            options.UseMySQL(Configuration.GetConnectionString("DefaultConnection"));
    });

    services.AddScoped<Microsoft.EntityFrameworkCore.Infrastructure.IDbContextOptions, Microsoft.EntityFrameworkCore.DbContextOptions<MyDbContext>>();
}

When I start the project I get an exception on EnsureCreate call. Exception message say Authentication failed but if I manually create database (without tables) my connection string works fine and EnsureCreated simply create tables for my entities.

What's wrong? It's a problem with SapientGuardian.EntityFrameworkCore.MySql?

Body:
I had the same problem you described. It looks like the SapientGuardian provider might simply have an incomplete implementation in this version.

The SapientGuardian project's readme file actually suggests using a more actively maintained provider such as Pomelo.EntityFrameworkCore.MySql. So I switched my project to Pomelo. Now the call to EnsureCreated creates the database as expected and does not have an authentication failed exception.


问:
IS routing order for signers optional?
I have 2 recipients and in my envelope, we do not want to force any specific  order for signing, so basically either of then can sign first. What routing order option should be set in such case? Can I omit the routing order for signers altogether?
Thanks,</p>

答:
If you do not want to force any specific order for signing, then leave the routingOrder empty. The routingOrder will be set to the default value of 1.

Multiple signers can have the same routing order. See this blog post for more information.

Title: IS routing order for signers optional?


答:
Here you go with the solution in the jsfiddle https://jsfiddle.net/6ktw0ucm/1/</p>

```<code>renderForm(){
    return(
            <div className="note">
                <textarea ref="newText" defaultValue={this.props.children[1]}></textarea>
                <button onClick={this.save.bind(this)}>Save </button>
            </div>
        );
}
</code>```

Title: Everything works fine but when I click edit button, a comma (,) is add every time. I would not find what going wrong?

Body:
Here you go with the solution in the jsfiddle https://jsfiddle.net/6ktw0ucm/1/

renderForm(){
    return(
            <div className="note">
                <textarea ref="newText" defaultValue={this.props.children[1]}></textarea>
                <button onClick={this.save.bind(this)}>Save </button>
            </div>
        );
}


问:
Increment values of an array using a for loop and a foreach
I have done a lot of research on google about it but I don't know how to achieve that in PHP. Actually I have an array with values and for each values I would like to get 5 new values incremented of 1.

Exemple :

```<code>$valueseg = array( 0 => 2510 , 1 => 1700);
</code>```

I would like to get this result :

```<code>$valueseg = array( 0 => 2510, 1 => 2511, 2 => 2512, 3 => 2513, 4 => 2514 , 5 => 2515, 6 => 1700, , 7 => 1701, , 8 => 1702, , 9 => 1703, 10 => 1704 , 11 => 1705);
</code>```

I tried to do that with a foreach and a for loop but I can't retrieve an array.

```<code>$tabasc = array();

foreach($valueseg as $key => $value){

    for($i = 0; $i < 5; $i++){
        $tabasc[$i] = $value + $i ;
    }
}
</code>```

With an echo inside the for loop I have a result inline like this : 2478247924802481248225102511251225132514

And if I try to do a var_dump of $tabasc it shows me values incremented of 1 only for the first value of $valueseg.

Do you know how to do that ?

Thanks

答:
Do it like below:-

```<code><?php

$valueseg = array( 0 => 2510 , 1=> 1700);

$final_array = array(); //create a new array

foreach($valueseg as $values){ // iterate over your original array
  for($i=1;$i<=5;$i++){ // loop 5 times
    $final_array[] = $values+$i; //add incremented $i value to original value and assign to new array
  }

}

print_r($final_array); // print new array
</code>```

Output:- https://eval.in/829546

Body:
I have done a lot of research on google about it but I don't know how to achieve that in PHP. Actually I have an array with values and for each values I would like to get 5 new values incremented of 1.

Exemple :

$valueseg = array( 0 => 2510 , 1 => 1700);

I would like to get this result :

$valueseg = array( 0 => 2510, 1 => 2511, 2 => 2512, 3 => 2513, 4 => 2514 , 5 => 2515, 6 => 1700, , 7 => 1701, , 8 => 1702, , 9 => 1703, 10 => 1704 , 11 => 1705);

I tried to do that with a foreach and a for loop but I can't retrieve an array.

$tabasc = array();

foreach($valueseg as $key => $value){

    for($i = 0; $i < 5; $i++){
        $tabasc[$i] = $value + $i ;
    }
}

With an echo inside the for loop I have a result inline like this : 2478247924802481248225102511251225132514

And if I try to do a var_dump of $tabasc it shows me values incremented of 1 only for the first value of $valueseg.

Do you know how to do that ?

Thanks

Body:
Do it like below:-

<?php

$valueseg = array( 0 => 2510 , 1=> 1700);

$final_array = array(); //create a new array

foreach($valueseg as $values){ // iterate over your original array
  for($i=1;$i<=5;$i++){ // loop 5 times
    $final_array[] = $values+$i; //add incremented $i value to original value and assign to new array
  }

}

print_r($final_array); // print new array

Output:- https://eval.in/829546


问:
PHP Fatal error: Call to a member function result_array() on a non-object
I am working on php using codeigniter framework as a beginner. My program is running perfectly on my localhost. But after uploading to the web server, it is showing an error for some pages. I have searched about this problem and most of the solutions show that my program is right. But for the live server, it is showing PHP fatal error. First one is, whenever I want to see data in datatable it is showing HTTP 500 error. My server administrator told me this is because of my model whenever I am returning data as result_array(). Here is my model,

```<code> public function get_pages()
    {
        $this->db->select('*');
        $this->db->from('page');
        $this->db->join('NavigationMenu', 'NavigationMenu.MenuID = page.MenuID', 'left');
        $this->db->join('SubMenu', 'SubMenu.SubMenuID = Page.SubMenuID', 'left');
        $query = $this->db->get();
        return $query->result_array();
    }
</code>```

Here is my controller for that,

```<code>public function pages()
{
        $data['page'] = $this->Pages_Model->get_pages();
        $tempString =  $this->load->view('admin_panel/content/pages', $data, true);
        $page_data = array(
            'fileHere' => $tempString
        );
        $this->load->view('admin_panel/shared/admin_layout',$page_data);
}
</code>```

And this is my View page,

Page Lists

                  Title
                  Main Menu
                  Sub-Menu
                  Edit/Remove

                <?php foreach ($page as $page_item): ?>

                        <?php echo $page_item['PageTitle']; ?>
                        <?php echo $page_item['MenuName']; ?>
                        <?php echo $page_item['SubMenuName']; ?>
                        <button type="submit" class="btn btn-primary" onClick="javascipt:window.location.href='<?php echo base_url('content/edit_page_content')?>/<?php echo $page_item['PageID']; ?>'">Edit</button>
                            <button type="submit" class="btn btn-danger delete_page" id="<?php echo $page_item['PageID']; ?>">Remove</button>

                <?php endforeach; ?>

```

This is one of my problem. I beleive if I get a solution I can solve others. The result_array() function is working perfectly in other places like where I need to fetch data. Thank you in advance.

答:
My database is case-sensitive. This is the reason it is showing that error. I have modified my model and it works now. </p>

```<code>public function get_pages()
{
    $this->db->select('*');
    $this->db->from('Page');
    $this->db->join('NavigationMenu', 'NavigationMenu.MenuID = Page.MenuID', 'left');
    $this->db->join('SubMenu', 'SubMenu.SubMenuID = Page.SubMenuID', 'left');
    $query = $this->db->get();
    return $query->result_array();
}
</code>```

Body:
I am working on php using codeigniter framework as a beginner. My program is running perfectly on my localhost. But after uploading to the web server, it is showing an error for some pages. I have searched about this problem and most of the solutions show that my program is right. But for the live server, it is showing PHP fatal error. First one is, whenever I want to see data in datatable it is showing HTTP 500 error. My server administrator told me this is because of my model whenever I am returning data as result_array(). Here is my model,

 public function get_pages()
    {
        $this->db->select('*');
        $this->db->from('page');
        $this->db->join('NavigationMenu', 'NavigationMenu.MenuID = page.MenuID', 'left');
        $this->db->join('SubMenu', 'SubMenu.SubMenuID = Page.SubMenuID', 'left');
        $query = $this->db->get();
        return $query->result_array();
    }

Here is my controller for that,

public function pages()
{
        $data['page'] = $this->Pages_Model->get_pages();
        $tempString =  $this->load->view('admin_panel/content/pages', $data, true);
        $page_data = array(
            'fileHere' => $tempString
        );
        $this->load->view('admin_panel/shared/admin_layout',$page_data);
}

And this is my View page,

Page Lists

                  Title
                  Main Menu
                  Sub-Menu
                  Edit/Remove

                <?php foreach ($page as $page_item): ?>

                        <?php echo $page_item['PageTitle']; ?>
                        <?php echo $page_item['MenuName']; ?>
                        <?php echo $page_item['SubMenuName']; ?>
                        <button type="submit" class="btn btn-primary" onClick="javascipt:window.location.href='<?php echo base_url('content/edit_page_content')?>/<?php echo $page_item['PageID']; ?>'">Edit</button>
                            <button type="submit" class="btn btn-danger delete_page" id="<?php echo $page_item['PageID']; ?>">Remove</button>

                <?php endforeach; ?>

This is one of my problem. I beleive if I get a solution I can solve others. The result_array() function is working perfectly in other places like where I need to fetch data. Thank you in advance.

Body:
My database is case-sensitive. This is the reason it is showing that error. I have modified my model and it works now.

public function get_pages()
{
    $this->db->select('*');
    $this->db->from('Page');
    $this->db->join('NavigationMenu', 'NavigationMenu.MenuID = Page.MenuID', 'left');
    $this->db->join('SubMenu', 'SubMenu.SubMenuID = Page.SubMenuID', 'left');
    $query = $this->db->get();
    return $query->result_array();
}


问:
Xpath selector not working for (presumably) Ajax control
I am trying to select flights between 2 places on this travel website.

I am able to select the source (LEAVING FROM field), but having issues with destination (GOING TO field) input field.

Here is the code:

```<code>public class CathaypacificFlightSearch {
    static WebDriver driver=null;
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "D:\\bala back up\\personel\\selenium\\Jars\\Drivers\\geckodriver.exe");
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.cathaypacific.com/cx/en_IN.html");

        WebElement leavingFrom=driver.findElement(By.xpath("//*[@id='depart-label']"));
        leavingFrom.click();
        leavingFrom.sendKeys("Bengaluru"); // Entering the starting point

        WebElement cityList=driver.findElement(By.xpath("//*[contains(@id,'ui-id')]//a"));
        System.out.println(cityList.getText());
        cityList.click();  // Selecting the required option

        WebElement goingTo=driver.findElement(By.xpath("//*[@id='destination-label']"));
        goingTo.click();
        goingTo.sendKeys("Singapore");  //Entering the Destination point

        WebElement gCityList=driver.findElement(By.xpath("//*[contains(@id,'ui-id')]//a")); //THIS IS WHERE XPATH IS NOT WORKING
        System.out.println(gCityList.getText());
        gCityList.click();
}}
</code>```

I also tried using the below xpath and cssSelector, but no luck.

```<code> //WebElement gCityList=driver.findElement(By.cssSelector("li[id*='ui-id'] a"));
 //WebElement gCityList=driver.findElement(By.xpath("//ul[contains(@id,'ui-id')]//li//a"));
</code>```

FYI, a similar kind of XPath worked for source field. Only having issues with selecting the destination city.

答:
Here is the Answer to your Question:

A few words about the solution:

You can consider to construct unique xpath like //input[@id='depart-label'] instead of //*[@id='depart-label']

The xpath you constructed for LEAVING FROM as //*[contains(@id,'ui-id')]//a is brittle and vulnerable.

Here is the working code block which selects GOING TO as Singapore:

```<code>import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Q44982690_ajax
{

    static WebDriver driver=null;
    public static void main(String[] args)
    {

        System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.cathaypacific.com/cx/en_IN.html");
        WebElement leavingFrom=driver.findElement(By.xpath("//input[@id='depart-label']"));
        leavingFrom.click();
        leavingFrom.sendKeys("Bengaluru"); // Entering the starting point
        WebElement cityList=driver.findElement(By.xpath("//*[contains(@id,'ui-id')]//a"));
        System.out.println(cityList.getText());
        cityList.click();  // Selecting the required option
        WebElement goingTo=driver.findElement(By.xpath("//input[@id='destination-label']"));
        goingTo.click();
        goingTo.sendKeys("Singapore");  //Entering the Destination point
        WebElement gCityList=driver.findElement(By.xpath("//input[@id='destination-label']//following::ul[1]/li/a")); //THIS IS WHERE XPATH IS AGAIN WORKING
        System.out.println(gCityList.getText());
        gCityList.click();
    }
}
</code>```

Let me know if this Answers your Question.

Body:
I am trying to select flights between 2 places on this travel website.

I am able to select the source (LEAVING FROM field), but having issues with destination (GOING TO field) input field.

Here is the code:

public class CathaypacificFlightSearch {
    static WebDriver driver=null;
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "D:\\bala back up\\personel\\selenium\\Jars\\Drivers\\geckodriver.exe");
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.cathaypacific.com/cx/en_IN.html");

        WebElement leavingFrom=driver.findElement(By.xpath("//*[@id='depart-label']"));
        leavingFrom.click();
        leavingFrom.sendKeys("Bengaluru"); // Entering the starting point

        WebElement cityList=driver.findElement(By.xpath("//*[contains(@id,'ui-id')]//a"));
        System.out.println(cityList.getText());
        cityList.click();  // Selecting the required option

        WebElement goingTo=driver.findElement(By.xpath("//*[@id='destination-label']"));
        goingTo.click();
        goingTo.sendKeys("Singapore");  //Entering the Destination point

        WebElement gCityList=driver.findElement(By.xpath("//*[contains(@id,'ui-id')]//a")); //THIS IS WHERE XPATH IS NOT WORKING
        System.out.println(gCityList.getText());
        gCityList.click();
}}

I also tried using the below xpath and cssSelector, but no luck.

 //WebElement gCityList=driver.findElement(By.cssSelector("li[id*='ui-id'] a"));
 //WebElement gCityList=driver.findElement(By.xpath("//ul[contains(@id,'ui-id')]//li//a"));

FYI, a similar kind of XPath worked for source field. Only having issues with selecting the destination city.

Body:
Here is the Answer to your Question:

A few words about the solution:

You can consider to construct unique xpath like //input[@id='depart-label'] instead of //*[@id='depart-label']

The xpath you constructed for LEAVING FROM as //*[contains(@id,'ui-id')]//a is brittle and vulnerable.

Here is the working code block which selects GOING TO as Singapore:

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Q44982690_ajax
{

    static WebDriver driver=null;
    public static void main(String[] args)
    {

        System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.cathaypacific.com/cx/en_IN.html");
        WebElement leavingFrom=driver.findElement(By.xpath("//input[@id='depart-label']"));
        leavingFrom.click();
        leavingFrom.sendKeys("Bengaluru"); // Entering the starting point
        WebElement cityList=driver.findElement(By.xpath("//*[contains(@id,'ui-id')]//a"));
        System.out.println(cityList.getText());
        cityList.click();  // Selecting the required option
        WebElement goingTo=driver.findElement(By.xpath("//input[@id='destination-label']"));
        goingTo.click();
        goingTo.sendKeys("Singapore");  //Entering the Destination point
        WebElement gCityList=driver.findElement(By.xpath("//input[@id='destination-label']//following::ul[1]/li/a")); //THIS IS WHERE XPATH IS AGAIN WORKING
        System.out.println(gCityList.getText());
        gCityList.click();
    }
}

Let me know if this Answers your Question.


问:
Create parameterized VIEW in SQL Server 2008
Can we create parameterized VIEW in SQL Server 2008.

Or Any other alternative for this ?

答: No, you cannot. But you can create a user defined table function.</p>


问:
Code for iterative function
I'd like to write the Matlab code for the following equation:

```<code>z(k)=lamda*x(k)+(1-lamda)*z(k-1)
</code>```

lamda can be of any value. x is a 1000x22 matrix. Z(0)=0.

Can anyone help me please?

答:
You can use iteration function.same thing like this

```<code>function z = itrationFunctio(k,x,lambda)
if(k == 0)
    z = 0;
else
    z = lambda*x+(1-lambda)*itrationFunctio((k-1),x,lambda);
end
</code>```

and in your code just call itrationFunctio(k,x,lambda).

Title: Code for iterative function

Body:
I'd like to write the Matlab code for the following equation:

z(k)=lamda*x(k)+(1-lamda)*z(k-1)

lamda can be of any value. x is a 1000x22 matrix. Z(0)=0.

Can anyone help me please?

Body:
You can use iteration function.same thing like this

function z = itrationFunctio(k,x,lambda)
if(k == 0)
    z = 0;
else
    z = lambda*x+(1-lambda)*itrationFunctio((k-1),x,lambda);
end

and in your code just call itrationFunctio(k,x,lambda).


问:
How to assign (add) value to a undefined item in a json object
I have a external json file and I parse it in to local object,
Currently I know I can't push value into a object so I want to assign a value to them here is my code:

```<code>//I parse my JSON into object and name it data
var data = {
  ...
}
// I use this object as a database so I don't list it all out
var name = "title";
var content = "hello guys";
data[name] = content;
// I wish after this script the object will have one more item like
// {
//  ...
//  "title": "hello guys",
//  ...
//}
</code>```

But the vscode's console show the following error when I run the script

```<code>TypeError: Cannot set property 'title' of undefined
</code>```

If you can assign value to undefined object how can you add item in to object.

But if there is any way that can let me assign value to undefined item, I'll be very happy

Here is the full code if you need

```<code>var jsonfile = require('jsonfile')

var file = './test.json'
var data = jsonfile.readFileSync(file); //I'm very sure data isn't undefined
//console.log(data);
var name="title";
var content="hello guys";
data.post[name] = content;

jsonfile.writeFileSync(file, tmd, {spaces: 4});
</code>```

答:
Probably data has no key named 'post'.
Try this:

```<code>data.post = data.post || {};
data.post[name] = content;
</code>```

EDIT:
I know this is old, but maybe it will help someone.
Here https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options states that readFileSync returns string not data structure.

Body:
I have a external json file and I parse it in to local object,
Currently I know I can't push value into a object so I want to assign a value to them here is my code:

//I parse my JSON into object and name it data
var data = {
  ...
}
// I use this object as a database so I don't list it all out
var name = "title";
var content = "hello guys";
data[name] = content;
// I wish after this script the object will have one more item like
// {
//  ...
//  "title": "hello guys",
//  ...
//}

But the vscode's console show the following error when I run the script

TypeError: Cannot set property 'title' of undefined

If you can assign value to undefined object how can you add item in to object.

But if there is any way that can let me assign value to undefined item, I'll be very happy

Here is the full code if you need

var jsonfile = require('jsonfile')

var file = './test.json'
var data = jsonfile.readFileSync(file); //I'm very sure data isn't undefined
//console.log(data);
var name="title";
var content="hello guys";
data.post[name] = content;

jsonfile.writeFileSync(file, tmd, {spaces: 4});

Body:
Probably data has no key named 'post'.
Try this:

data.post = data.post || {};
data.post[name] = content;

EDIT:
I know this is old, but maybe it will help someone.
Here https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options states that readFileSync returns string not data structure.


问:
Sorting JSON Array by a double nested value?
I am unable to find a reasonable solution as I am pulling JSON data from firebase and pulling it from node.js into an html file. I want to sort my data via a property called "value" by not sure how to access a sub-sub-value to sort by in JQuery and am wondering if someone could help lead me in the right direction.

```<code>{
    key: "a",
    {
         key: "ab",
         {
               value: 2
         }
         key: "ac",
         {
               value: 0
         }
    }
},
    {
    key: "b",
    {
         key: "bb",
         {
               value: 1
         }
    }
},
</code>```

Output:

```<code>[{ac}, {bb}, {ab}]
</code>```

答:
Both your input and desired output are expressed in an invalid notation (both in JSON and JavaScript syntax), so I'll have to make some assumptions.

You could use this recursive function, which will find all nested value properties, and collect those values together with the names of the parent properties in which they occur. Finally those pairs of data (parent key and value) are sorted:

function collectValues(obj, name) {
    return Object.entries(obj).reduce( (acc, [key, value]) => {
        return acc.concat(
            // recursively look into nested objects:
            Object(value) === value ? collectValues(value, key)
                // else, when key is 'value', collect that object
                : key == 'value' ? [[name, value]]
                // otherwise ignore this value
                : []
        )
    }, []);
}

// Sample input
var input = [{
    "a": {
         "ab": {
            value: 2
         },
         "ac": {
            value: 0
         }
    }
}, {
    "b": {
        "bb": {
            value: 1
        }
    }
}];

var result = collectValues(input).sort( (a,b) => a[1] - b[1] );

console.log(result);```

Body:
I am unable to find a reasonable solution as I am pulling JSON data from firebase and pulling it from node.js into an html file. I want to sort my data via a property called "value" by not sure how to access a sub-sub-value to sort by in JQuery and am wondering if someone could help lead me in the right direction.

{
    key: "a",
    {
         key: "ab",
         {
               value: 2
         }
         key: "ac",
         {
               value: 0
         }
    }
},
    {
    key: "b",
    {
         key: "bb",
         {
               value: 1
         }
    }
},

Output:

[{ac}, {bb}, {ab}]