问:
Call a function written in different file from jupyter notebook
From a jupyter notebook, I'd like to call a function written in another .ipynb file. The partial answer is given in this thread Reusing code from different IPython notebooks by drevicko. As an example, I'm using plus_one function written in plus_one.ipynb:

```<code>def plus_one(x):
    print(x + 1)
</code>```

Then, in my current notebook, I execute the cell:

```<code>%run plus_one.ipynb 3
</code>```

which gives me no output. My expected output is 4. How to pass an argument (3) to this script? Thanks!

答:
From the %run? documentation

This is similar to running at a system prompt python file args,
  but with the advantage of giving you IPython's tracebacks, and of
  loading all variables into your interactive namespace for further use

so all the cells from plus_one.ipynb are run and all it's variables are added to the namespace of the calling notebook.
This does not call the plus_one method directly (unless it is called in the other notebook), but it defines it in the current namespace, kind of like an import in a regular python script.so from that moment on, you should be able to do  plus_one(3) in the calling notebook, and expect 4 as return value

Body:
From a jupyter notebook, I'd like to call a function written in another .ipynb file. The partial answer is given in this thread Reusing code from different IPython notebooks by drevicko. As an example, I'm using plus_one function written in plus_one.ipynb:

def plus_one(x):
    print(x + 1)

Then, in my current notebook, I execute the cell:

%run plus_one.ipynb 3

which gives me no output. My expected output is 4. How to pass an argument (3) to this script? Thanks!


来源: stackexchange

问:
Distinct method doesn't work for class with overriden Equals
I created class with overriden Equals. The problem is that Distinct method doesn't work for my class.

```<code>class MyClass
{
    public int Item1 { get; private set; }
    public int Item2 { get; private set; }

    public MyClass(int item1, int item2)=>(Item1,Item2)=(item1,item2);

    public override bool Equals(object obj)
    {
        var other = obj as MyClass;

        if (other == null)
        {
            return false;
        }

        return (this.Item1 == other.Item1 && this.Item2 == other.Item2);
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass x = new MyClass(1, 0);
        MyClass y = new MyClass(1, 0);
        var list = new List<MyClass>();
        list.Add(x);
        list.Add(y);

        bool b = x.Equals(y));  //True
        var distincts = list.Distinct(); //Doesn't work, contains both
    }
}
</code>```

How can I fix that and why it doesn't use my Equals in Distinct?

答:
Distinct docs:

Returns distinct elements from a sequence by using the default equality comparer to compare values.

Let's see what the default equality comparer does:

The Default property checks whether type T implements the System.IEquatable<T> interface and, if so, returns an EqualityComparer<T> that uses that implementation. Otherwise, it returns an EqualityComparer<T> that uses the overrides of Object.Equals and Object.GetHashCode provided by T.

So basically, to make this work, you either:

implement GetHashCode as well

implement IEquatable<T>

Call the overload of Distinct that accepts a custom equality comparer.

If I were you, I would choose the second one because you need to change the least of your code.

```<code>class MyClass: IEquatable<MyClass> {
    ...

    public bool Equals(MyClass obj)
    {
        if (obj == null)
        {
            return false;
        }

        return (this.Item1 == obj.Item1 && this.Item2 == obj.Item2);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I created class with overriden Equals. The problem is that Distinct method doesn't work for my class.

class MyClass
{
    public int Item1 { get; private set; }
    public int Item2 { get; private set; }

    public MyClass(int item1, int item2)=>(Item1,Item2)=(item1,item2);

    public override bool Equals(object obj)
    {
        var other = obj as MyClass;

        if (other == null)
        {
            return false;
        }

        return (this.Item1 == other.Item1 && this.Item2 == other.Item2);
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass x = new MyClass(1, 0);
        MyClass y = new MyClass(1, 0);
        var list = new List<MyClass>();
        list.Add(x);
        list.Add(y);

        bool b = x.Equals(y));  //True
        var distincts = list.Distinct(); //Doesn't work, contains both
    }
}

How can I fix that and why it doesn't use my Equals in Distinct?

Body:
Distinct docs:

Returns distinct elements from a sequence by using the default equality comparer to compare values.

Let's see what the default equality comparer does:

The Default property checks whether type T implements the System.IEquatable<T> interface and, if so, returns an EqualityComparer<T> that uses that implementation. Otherwise, it returns an EqualityComparer<T> that uses the overrides of Object.Equals and Object.GetHashCode provided by T.

So basically, to make this work, you either:

implement GetHashCode as well

implement IEquatable<T>

Call the overload of Distinct that accepts a custom equality comparer.

If I were you, I would choose the second one because you need to change the least of your code.

class MyClass: IEquatable<MyClass> {
    ...

    public bool Equals(MyClass obj)
    {
        if (obj == null)
        {
            return false;
        }

        return (this.Item1 == obj.Item1 && this.Item2 == obj.Item2);
    }
}


问:
How do I run a function on ngOnInit() only once and not again upon returning back from another routerLink?
HomeComponent

```<code>ngOnInit()
{
    console.log('loaded');
    this.retrieveData();
}

retrieveData()
{
    // this.dataService.getData().subscribe(...);
}
</code>```

I am retrieving data when the component loads. When the user clicks on another routerLink, for example, SettingsComponent and returns back to the HomeComponent, the function of course, is called again because the component has loaded again. But Everytime I return back to the component, it makes the function call again which creates too many unwanted HTTP requests. I need to prevent this and make sure the function is called only the first time. How do I do this? Should I use some other component lifecycle hook?

答:
Okay I see you are using a service to load the data which is a good way.

Then you can simply cache the data somewhere and when you come back to a component check the cache for this data. I think you can store the data directly in your service which will keep it in the memory or you can put it in the localStorage

So first option would look like:

data.service.ts

```<code>export class DataService {

    private data: any[];

    setData(data:any[]){
        this.data = data;
    }

    getData(){
        return this.data || [];
    }

    hasData(){
        return this.data && this.data.length;
    }

    getData(){
        // your implementation here
    }
}
</code>```

then inside HomeComponent

```<code>retrieveData(){
    if(this.dataService.hasData()){
         // this will get the data which was previously stored in the memory
         // and there will be no HTTP request
         let data = this.dataService.getData();
         // do something with data now ...
    }else{
        // old code
        this.dataService.getData().subscribe(response => {
            // but this time safe the data for future use
            this.dataService.setData(response.data);
        }, error => {
            // handle errors
        });
    }
}
</code>```

IMPORTANT: if using this approach you should make your service global when declaring it in app.module.ts -> providers

```<code>@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule
    ],
    providers: [
        DataService   <---------- SEE HERE
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

and then not doing this:

```<code>@Component({
    selector: 'home',
    templateUrl: '...',
    styleUrls: ['...'],
    providers: [
        DataService     <---- THEN DON'T put in component's providers
    ]
})
export class HomeComponent{ ... }
</code>```

=============================================

The localStorage approach

HomeComponenet

```<code>retrieveData()
{
    let data = localStorage.getItem('yourDataName');
    if (data === null){
        // old code
        this.dataService.getData().subscribe(response => {
            // but this time safe the data for future use in localStorage
            localStorage.setItem('yourDataName', response.data);
        }, error => {
            // handle errors
        });
    } else {
        // seems that you already loaded this data
        // do something with this data ...
    }
}
</code>```

Both approaches has the limitation that you can't work with huge amounts of data, of course if you don't want to blow the browsers of users that are using your app :)

Body:
HomeComponent

ngOnInit()
{
    console.log('loaded');
    this.retrieveData();
}

retrieveData()
{
    // this.dataService.getData().subscribe(...);
}

I am retrieving data when the component loads. When the user clicks on another routerLink, for example, SettingsComponent and returns back to the HomeComponent, the function of course, is called again because the component has loaded again. But Everytime I return back to the component, it makes the function call again which creates too many unwanted HTTP requests. I need to prevent this and make sure the function is called only the first time. How do I do this? Should I use some other component lifecycle hook?

Body:
Okay I see you are using a service to load the data which is a good way.

Then you can simply cache the data somewhere and when you come back to a component check the cache for this data. I think you can store the data directly in your service which will keep it in the memory or you can put it in the localStorage

So first option would look like:

data.service.ts

export class DataService {

    private data: any[];

    setData(data:any[]){
        this.data = data;
    }

    getData(){
        return this.data || [];
    }

    hasData(){
        return this.data && this.data.length;
    }

    getData(){
        // your implementation here
    }
}

then inside HomeComponent

retrieveData(){
    if(this.dataService.hasData()){
         // this will get the data which was previously stored in the memory
         // and there will be no HTTP request
         let data = this.dataService.getData();
         // do something with data now ...
    }else{
        // old code
        this.dataService.getData().subscribe(response => {
            // but this time safe the data for future use
            this.dataService.setData(response.data);
        }, error => {
            // handle errors
        });
    }
}

IMPORTANT: if using this approach you should make your service global when declaring it in app.module.ts -> providers

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule
    ],
    providers: [
        DataService   <---------- SEE HERE
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

and then not doing this:

@Component({
    selector: 'home',
    templateUrl: '...',
    styleUrls: ['...'],
    providers: [
        DataService     <---- THEN DON'T put in component's providers
    ]
})
export class HomeComponent{ ... }

=============================================

The localStorage approach

HomeComponenet

retrieveData()
{
    let data = localStorage.getItem('yourDataName');
    if (data === null){
        // old code
        this.dataService.getData().subscribe(response => {
            // but this time safe the data for future use in localStorage
            localStorage.setItem('yourDataName', response.data);
        }, error => {
            // handle errors
        });
    } else {
        // seems that you already loaded this data
        // do something with this data ...
    }
}

Both approaches has the limitation that you can't work with huge amounts of data, of course if you don't want to blow the browsers of users that are using your app :)


问:
saving values of toggle(yes or no) in database php
i am trying to use toggle buttons to save response in db as yes or no. for some reason the only response i am getting is 'on'. even when i switch off the button. i tried searching for problem and got a match but the problem was asked for android platform.now i am stuck with no answer there where similar questions but none of them is useful for me at this moment. sharing the code down below.Thanks in advance for those who are going to suggest or provide a solution.i am using class handicap to save data into variable inside JQUERY and then send that variable to AJAX page to perform db operation.i am not sharing CSS for toggle as i don't think that is required right now. if u need any additional info, do inform me.this input is inside a form with method POST. i am using a submit button with id that is calling this JQUERY.
   html part

```<code><div class="switch">
    <input id="cmn-toggle-4" class="cmn-toggle cmn-toggle-round-flat handicap" type="checkbox" name="handicap">
    <label for="cmn-toggle-4"></label>
    </div>
</code>```

jquery

```<code>     $("#save-medical-1").click(function () {
        var m11 = $(".handicap").val();
    alert(m11);
        $.ajax({
          url: "ajexupdate.php",
          type: "POST",
          data: {smsgs11: m11},
          dataType: 'text',
          cache: false,
          success: function (e) {
            //           alert(e);
            $("#user_medical_form").html(e);
            $("#medidetail").modal('hide');
            $('body').removeClass('modal-open');
            $('.modal-backdrop').remove();

          }
        });
        return false;
      });
</code>```

答:
You can get value using ":checked" using jquery.
eg.

```<code>if($("#cmn-toggle-4").is(":checked")){
m11="yes";
}
else{
m11="no";
}
</code>```

and send it through ajax.

Body:
i am trying to use toggle buttons to save response in db as yes or no. for some reason the only response i am getting is 'on'. even when i switch off the button. i tried searching for problem and got a match but the problem was asked for android platform.now i am stuck with no answer there where similar questions but none of them is useful for me at this moment. sharing the code down below.Thanks in advance for those who are going to suggest or provide a solution.i am using class handicap to save data into variable inside JQUERY and then send that variable to AJAX page to perform db operation.i am not sharing CSS for toggle as i don't think that is required right now. if u need any additional info, do inform me.this input is inside a form with method POST. i am using a submit button with id that is calling this JQUERY.
   html part

    <input id="cmn-toggle-4" class="cmn-toggle cmn-toggle-round-flat handicap" type="checkbox" name="handicap">

jquery

     $("#save-medical-1").click(function () {
        var m11 = $(".handicap").val();
    alert(m11);
        $.ajax({
          url: "ajexupdate.php",
          type: "POST",
          data: {smsgs11: m11},
          dataType: 'text',
          cache: false,
          success: function (e) {
            //           alert(e);
            $("#user_medical_form").html(e);
            $("#medidetail").modal('hide');
            $('body').removeClass('modal-open');
            $('.modal-backdrop').remove();

          }
        });
        return false;
      });

Body:
You can get value using ":checked" using jquery.
eg.

if($("#cmn-toggle-4").is(":checked")){
m11="yes";
}
else{
m11="no";
}

and send it through ajax.


问:
Mongodb replica set (Write on secondary)
I have created 3 AWS instances for mongodb. One for primary, one for secondary and one arbiter. My application is pointing to the Primary node. So when the Primary goes down and becomes Secondary no data is posted on it. How can I enable write operations for a secondary node. Mongodb's write concern (w:"majority") didnt work for me.
Can anyone please give a work around ?</p>

答:
You cannot write on a secondary node.

If you primary goes down, it will become a secondary which will receive the writes through the replication mechanism from the new elected primary (only one machine of yours can be as the other member is an arbiter which doesn't hold data).

Write concern is not about writing to secondaries directly. It is about how many replica set member (primary, secondaries...) have to acknowledge the write for you application to receive the ok from the driver.

ContentLicense: CC BY-SA 4.0


问:
Disable auto focus on edit text
I have an edit text:

```<code>   <LinearLayout android:id="@+id/linearLayout7" android:layout_width="match_parent" android:layout_height="wrap_content">
        <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_weight="1" android:id="@+id/editText1" android:text="3">
            <requestFocus></requestFocus>
        </EditText>
        <Button android:text="Button" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/button2"></Button>
    </LinearLayout>
</code>```

and then some other stuff underneath

The problem I'm having is that right when the app starts the focus is on the input, i dont want focus to be on input right when the app starts.

I tried removing the

```<code><requestFocus></requestFocus>
</code>```

thing and it didn't do anything.

答:
Hei Lee,

There are several way to do this, Mudassir has give a way to you to do that.

If the idea doesn't work, then do just simple thing-

In your AndroidManifest>Activity add this simple code:

```<code>android:windowSoftInputMode="stateHidden"
</code>```

Nothing need to do in EditText in XML, all will be work and no focus will appear.

Look the real life example code:

```<code><activity
        android:name=".MainActivity"
        android:windowSoftInputMode="stateHidden"
        android:label="@string/app_name"
        >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
</activity>
</code>```

Title: Disable auto focus on edit text

Body:
I have an edit text:

   <LinearLayout android:id="@+id/linearLayout7" android:layout_width="match_parent" android:layout_height="wrap_content">
        <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_weight="1" android:id="@+id/editText1" android:text="3">
            <requestFocus></requestFocus>
        </EditText>
        <Button android:text="Button" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/button2"></Button>
    </LinearLayout>

and then some other stuff underneath

The problem I'm having is that right when the app starts the focus is on the input, i dont want focus to be on input right when the app starts.

I tried removing the

<requestFocus></requestFocus>

thing and it didn't do anything.

Body:
Hei Lee,

There are several way to do this, Mudassir has give a way to you to do that.

If the idea doesn't work, then do just simple thing-

In your AndroidManifest>Activity add this simple code:

android:windowSoftInputMode="stateHidden"

Nothing need to do in EditText in XML, all will be work and no focus will appear.

Look the real life example code:

<activity
        android:name=".MainActivity"
        android:windowSoftInputMode="stateHidden"
        android:label="@string/app_name"
        >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
</activity>


问:
how to convince my manager for a rails 3 upgrade | should I upgrade to rails 3
We are currently running rails 2.1.

My main motivation for the upgrade is the fear that gems/plugins will get rarer/unavailable/unsupported day by day for our version (,and the excitement of the latest technology).

I understand there are many-many improvements that come with rails3, but probably what my manager would want to listen is the advantages that he'd get, in terms of the business.

Ours is a Saas application, load on the app is not very high, but the demand for reliability is more.

Edit :

Looks like my inclination towards the upgrade needs rethinking, so answers to "should I upgrade" are welcome.

my original question also needs answers - how to describe the business advantages of an upgrade from rails2.1 -> rails3.

The app is under active development/enhancements.

答:
There are several reasons to upgrade, all of which are under the assumption that the app is and will continue to be under active development.

Integration with 3rd party software- for example, rails 1 did not have ActiveSupport.  An app remaining on rails1 all through say rails 2 might want to integrate with a 3rd party API that primarily supports restful json.   At that point, the sensibile path is to upgrade, but since you delayed it so long your risk of having lots of issues in the upgrade will be significantly greater than if you upgraded early.

Using plugins that will help with new features - if you want to add a new feature and someone has scratched your itch already, then if you are stuck on an older version of rails you will have to write that code yourself.  The more code you have to write yourself, the greater the likelyhood of bugs and the more maintaince the code will likely require, depending on the function.

Fixing bugs in older verisons of the plugins/gems  - if you encounter a bug in rails, or a plugin, or a gem, or some sort of other integration issue, it might be fixed in a later version, but what that depends on a newer version of rails.  This will make your path to fixing said bug or implementing said enhancement greater the longer you wait to upgrade.

ContentLicense: CC BY-SA 2.5


问:
Issue with local storage element send in http post
I have issue with sending local storage element in http post request. it works with android and website but in ios http request being executed before getting local storage element. I have used async and await but i don't konow why this problem in ios only. here is code what i did.</p>

```<code>async rpibuttonsselect(): Promise<rpibuttondataList[]> {
      const username = await this.storage.get('name');
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      var options = new RequestOptions({ headers: headers });
      let response = await this.http.post('http://node.services.com:3084/api/rpibuttonsselect/', JSON.stringify({ username: username }), options).toPromise();
      return response.json() as rpibuttondataList[];
    }
</code>```

答:
Subscribe to the storage promise by using .then function and shoot the http request from that function.</p>

```<code>      this.storage.get('name').then((username)=>{
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      var options = new RequestOptions({ headers: headers });
      let response = this.http.post('http://node.services.com:3084/api/rpibuttonsselect/', JSON.stringify({ username: username }), options);
    })
</code>```

Body:
I have issue with sending local storage element in http post request. it works with android and website but in ios http request being executed before getting local storage element. I have used async and await but i don't konow why this problem in ios only. here is code what i did.

async rpibuttonsselect(): Promise<rpibuttondataList[]> {
      const username = await this.storage.get('name');
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      var options = new RequestOptions({ headers: headers });
      let response = await this.http.post('http://node.services.com:3084/api/rpibuttonsselect/', JSON.stringify({ username: username }), options).toPromise();
      return response.json() as rpibuttondataList[];
    }

Body:
Subscribe to the storage promise by using .then function and shoot the http request from that function.

      this.storage.get('name').then((username)=>{
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      var options = new RequestOptions({ headers: headers });
      let response = this.http.post('http://node.services.com:3084/api/rpibuttonsselect/', JSON.stringify({ username: username }), options);
    })


问:
Laravel - How to CRUD records with ownership?
Let's say I've multiple users - Admin, Manager, User. User can CRUD records owned by him. Manager can CRUD records owned by him and his Users. Admin can CRUD records of all. How to achieve this in Laravel?</p>

答: You can create a middleware which verify the role of the current user and the role of the selected user for the action.</p>


问:
TypeScript Default Value for property
I have defined an Interface in TypeScript like below:

```<code>export interface User {
    id?: number;
    name?: string;
    logoUrl?: File;
    emailUserName?: string;
    emailPassword?: string;
}
</code>```

With User, I bind it to Angular html input. If I enter anything in the input, the User Object will contains the value, But, If I do not enter, the property like name will be undefine. How could I get empty value for name if I do not enter string for name.
Update

```<code><div *ngIf="hero">
<h2>{{hero.name}} details!</h2>
<div>
<label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name" />
<input [(ngModel)]="hero.location" placeholder="location" />
</div>
<button (click)="goBack()">Back</button>
</div>
//model
    export class Hero {
    private _location:string="test";
    constructor(){
    console.log(this._location);
    this.location=this._location;
    }
    public id: number;
    public name: string;
    public location:string;
    }

goBack(): void {
console.log(this.hero);
// this.hero=new Hero();
// console.log(this.hero);
//this.location.back();
}
}
</code>```

goBack will output hero without location property if I do not enter any value for it in input.

答:
Also you can use this shorthand:</p>

```<code>class User {
  constructor(public id: number = -1,
    public name: string = '',
    public logoUrl: File = 'defaultLogo.png' ,
    public emailUserName: string = ''
    public emailPassword: string = '') {}
}
</code>```

Title: TypeScript Default Value for property

Body:
I have defined an Interface in TypeScript like below:

export interface User {
    id?: number;
    name?: string;
    logoUrl?: File;
    emailUserName?: string;
    emailPassword?: string;
}

With User, I bind it to Angular html input. If I enter anything in the input, the User Object will contains the value, But, If I do not enter, the property like name will be undefine. How could I get empty value for name if I do not enter string for name.
Update

{{hero.name}} details!

id: {{hero.id}}

name:
<input [(ngModel)]="hero.name" placeholder="name" />
<input [(ngModel)]="hero.location" placeholder="location" />

<button (click)="goBack()">Back</button>

//model
    export class Hero {
    private _location:string="test";
    constructor(){
    console.log(this._location);
    this.location=this._location;
    }
    public id: number;
    public name: string;
    public location:string;
    }

goBack(): void {
console.log(this.hero);
// this.hero=new Hero();
// console.log(this.hero);
//this.location.back();
}
}

goBack will output hero without location property if I do not enter any value for it in input.

Body:
Also you can use this shorthand:

class User {
  constructor(public id: number = -1,
    public name: string = '',
    public logoUrl: File = 'defaultLogo.png' ,
    public emailUserName: string = ''
    public emailPassword: string = '') {}
}


问:
tensorflow cifar-10 reading data get stuck
I'm trying to read cifar10 input data using tensorflow. I know the existence of cifar10.py under tensorflow/models github repo. When running the following code, it basically gets stuck and shows no result in the screen. Help appreciated Thanks.</p>

```<code>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import time

import numpy as np
import tensorflow as tf

from tensorflow.contrib import learn
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib
tf.logging.set_verbosity(tf.logging.INFO)

def read_input(filename_queue):
    label_bytes = 1
    record_bytes = label_bytes  + (32 * 32 * 3)
    reader = tf.FixedLengthRecordReader(record_bytes=record_bytes)
    key, value = reader.read(filename_queue)
    single_row_bytes = tf.decode_raw(value, tf.uint8)
    label = tf.cast(tf.strided_slice(single_row_bytes, [0], [1]), tf.int32)
    image = tf.transpose(tf.reshape(tf.strided_slice(single_row_bytes, [1], [3073]), [3, 32, 32]), [1,2,0])
    return label, image

def generate_image_and_label_batch(label, image, batch_size, num_preprocess_threads, min_queue_examples):
    images, label_batch = tf.train.batch(
        [image, label],
        batch_size=batch_size,
        num_threads=num_preprocess_threads,
        capacity=min_queue_examples + 3 * batch_size)

    return images, tf.reshape(label_batch, [batch_size])

def mainFunction(file_names):
    filename_queue = tf.train.string_input_producer(file_names)
    label, image = read_input(filename_queue)
    image.set_shape([32, 32, 3])
    label.set_shape([1])
    return generate_image_and_label_batch(label, image, 10, 2, 4000)

def main(unused_argv):
    with tf.Graph().as_default():
        with tf.Session() as sess:
            x, y = sess.run(mainFunction(["cifar-10-batches-py/data_batch_" + str(i) for i in range(1,2)]))
            print(x)
            print(y)

if __name__ == "__main__":
    tf.app.run()
</code>```

答:
Seems like you are not starting the queuerunners / initializing the variables.
My answer to this question should help.</p>

Body:
I'm trying to read cifar10 input data using tensorflow. I know the existence of cifar10.py under tensorflow/models github repo. When running the following code, it basically gets stuck and shows no result in the screen. Help appreciated Thanks.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import time

import numpy as np
import tensorflow as tf

from tensorflow.contrib import learn
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib
tf.logging.set_verbosity(tf.logging.INFO)

def read_input(filename_queue):
    label_bytes = 1
    record_bytes = label_bytes  + (32 * 32 * 3)
    reader = tf.FixedLengthRecordReader(record_bytes=record_bytes)
    key, value = reader.read(filename_queue)
    single_row_bytes = tf.decode_raw(value, tf.uint8)
    label = tf.cast(tf.strided_slice(single_row_bytes, [0], [1]), tf.int32)
    image = tf.transpose(tf.reshape(tf.strided_slice(single_row_bytes, [1], [3073]), [3, 32, 32]), [1,2,0])
    return label, image

def generate_image_and_label_batch(label, image, batch_size, num_preprocess_threads, min_queue_examples):
    images, label_batch = tf.train.batch(
        [image, label],
        batch_size=batch_size,
        num_threads=num_preprocess_threads,
        capacity=min_queue_examples + 3 * batch_size)

    return images, tf.reshape(label_batch, [batch_size])

def mainFunction(file_names):
    filename_queue = tf.train.string_input_producer(file_names)
    label, image = read_input(filename_queue)
    image.set_shape([32, 32, 3])
    label.set_shape([1])
    return generate_image_and_label_batch(label, image, 10, 2, 4000)

def main(unused_argv):
    with tf.Graph().as_default():
        with tf.Session() as sess:
            x, y = sess.run(mainFunction(["cifar-10-batches-py/data_batch_" + str(i) for i in range(1,2)]))
            print(x)
            print(y)

if __name__ == "__main__":
    tf.app.run()


问:
how can i count the range between 2 dates without counting the weekend in javascript
i want to calculate the range between 2 dates without counting weekend in javascript. i have some code that already count the range between them. but i'm stuck with the weekend part. date inputed by CJuiDatePicker in YII framework

```<code>    <script>
    function calcDay(dt1, dt2, range){

    var msec1 = dt1;
    var date1 = new date(msec1);
    var msec2 = dt2;
    var date2 = new date(msec2);

    if(date1>0 || date2>0){
    range.val(isFinite(Math.round(date2-date1)/86400000) || 0);
    }
    };
    </script>
</code>```

86400000 is day in millisecond

thanks in advance

答:
i found my own solution, but i forgot to share it. this is how i make it

```<code>function myUpdate(dt1, dt2,range){
        var msec1 = dt1;
        var date1 =  new Date(msec1);
        var msec2 = dt2;
        var date2 =  new Date(msec2);
        var diff = (isFinite(Math.round (date2 - date1) / 86400000) && Math.round (date2 - date1) / 86400000 || 0);
        var wEnd=0;

        if(date1>0 || date2>0){
                for(var i=0; i<=diff; i++){
                    if(date1.getDay() ==6 || date1.getDay()==0){
                        wEnd = wEnd + 1;
                    }
                    date1.setDate(date1.getDate() + 1);
                }
            }
        range.val(Math.round((diff-wEnd)+1));
    };
</code>```

first u should count the different date, then the date1 will be check if it is sunday or saturday. then date1 will be added 1 till the value of date1 is equal to date2. if date1 is/are saturday or sunday, wEnd will gain 1. so u can substract diff with wEnd. hope this can help u guys

Body:
i want to calculate the range between 2 dates without counting weekend in javascript. i have some code that already count the range between them. but i'm stuck with the weekend part. date inputed by CJuiDatePicker in YII framework

86400000 is day in millisecond

thanks in advance

Body:
i found my own solution, but i forgot to share it. this is how i make it

function myUpdate(dt1, dt2,range){
        var msec1 = dt1;
        var date1 =  new Date(msec1);
        var msec2 = dt2;
        var date2 =  new Date(msec2);
        var diff = (isFinite(Math.round (date2 - date1) / 86400000) && Math.round (date2 - date1) / 86400000 || 0);
        var wEnd=0;

        if(date1>0 || date2>0){
                for(var i=0; i<=diff; i++){
                    if(date1.getDay() ==6 || date1.getDay()==0){
                        wEnd = wEnd + 1;
                    }
                    date1.setDate(date1.getDate() + 1);
                }
            }
        range.val(Math.round((diff-wEnd)+1));
    };

first u should count the different date, then the date1 will be check if it is sunday or saturday. then date1 will be added 1 till the value of date1 is equal to date2. if date1 is/are saturday or sunday, wEnd will gain 1. so u can substract diff with wEnd. hope this can help u guys


问:
Get location from user and perform an external request in api.ai
Can someone show me using the code
used in the course to get a location from the user(current or any other)
and then use it to show Google map with banks or schools api.ai?</p>

答:
You can trace user location without Google maps. Use geolocation API: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation

Geolocation API supports all latest browser including mobile devices.

You can get the user's current location as given below,

```<code>navigator.geolocation.getCurrentPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});
</code>```

Within the callback, you can make an external AJAX request to send this information to the remote server.

Hope this helps.

Body:
You can trace user location without Google maps. Use geolocation API: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation

Geolocation API supports all latest browser including mobile devices.

You can get the user's current location as given below,

navigator.geolocation.getCurrentPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});

Within the callback, you can make an external AJAX request to send this information to the remote server.

Hope this helps.


问:
Odoo , Domain, filter date and month
I try to create a filter domain in sale.report as : Month(order_date) = month(current_date) AND Day(order_date) <= Day(current_date).

```<code>filter string="This Month" domain="[(('date').strftime('%%m'),'=', ((context_today()).strftime('%%m'))),(('date').strftime('%%d'),'>=', ((context_today()).strftime('%%d')))]"/>
</code>```

I have a problem in left side of domain : ('date'), System say: AttributeError: object has no attribute 'strftime'.

try many combination, but response it's same.

Have you an idea ? What is the type of object 'date' ?

Thanks

答:
Here is example how you can do it. In this example i search for users with write_date (which is datetime) = yesterday. </p>

```<code>yesterday = datetime.datetime.now() - datetime.timedelta(days = 2)
yesterday_beginning = datetime.datetime(yesterday.year, yesterday.month, yesterday.day,0,0,0,0)
yb = yesterday_beginning.strftime("%Y-%m-%d %I:%M:%S")
today = datetime.datetime.now()
today_beginning = datetime.datetime(today.year, today.month, today.day,0,0,0,0)
tb = today_beginning.strftime("%Y-%m-%d %I:%M:%S")
self.env['res.users'].search([('write_date','>=',yb),('write_date','<',tb)])
</code>```

Title: Odoo , Domain, filter date and month

Body:
I try to create a filter domain in sale.report as : Month(order_date) = month(current_date) AND Day(order_date) <= Day(current_date).

filter string="This Month" domain="[(('date').strftime('%%m'),'=', ((context_today()).strftime('%%m'))),(('date').strftime('%%d'),'>=', ((context_today()).strftime('%%d')))]"/>

I have a problem in left side of domain : ('date'), System say: AttributeError: object has no attribute 'strftime'.

try many combination, but response it's same.

Have you an idea ? What is the type of object 'date' ?

Thanks

Body:
Here is example how you can do it. In this example i search for users with write_date (which is datetime) = yesterday.

yesterday = datetime.datetime.now() - datetime.timedelta(days = 2)
yesterday_beginning = datetime.datetime(yesterday.year, yesterday.month, yesterday.day,0,0,0,0)
yb = yesterday_beginning.strftime("%Y-%m-%d %I:%M:%S")
today = datetime.datetime.now()
today_beginning = datetime.datetime(today.year, today.month, today.day,0,0,0,0)
tb = today_beginning.strftime("%Y-%m-%d %I:%M:%S")
self.env['res.users'].search([('write_date','>=',yb),('write_date','<',tb)])


问:
Restore Atom text space to fullscreen
I pressed Alt Gr + something in Atom text editor and now my window looks like this:

How can I remove this blank space on the right and restore text to full screen width?

答: Itºs a known issue. Workaround is to close atom and launch it using the --clear-window-state argument

Title: Restore Atom text space to fullscreen


问:
How to select a value from Dropdown without using SELECT statement
In my automation suite I want to select a value from dropdown without using SELECT statement. Can someone please help me out with this.

Example:
I want to select a country name(India) from dropdown and I should not be using SELECT here.

Automation suite(Selenium with java)

Code:

```<code><div id="pie_register_reg_form">
    <form id="pie_regiser_form" enctype="multipart/form-data" method="post" action="/registration/">
    <ul id="pie_register">
    <div class="fieldset">
    <label for="dropdown_7">Country</label>
        <select id="dropdown_7" class="piereg_validate[required]" name="dropdown_7">
        <option value="Afghanistan">Afghanistan</option>
        <option value="Albania">Albania</option>
        <option value="Algeria">Algeria</option>
        …
        <option value="India">India</option>
        …
        <option value="Zambia">Zambia</option>
        <option value="Zimbabwe">Zimbabwe</option>
        </select>
    </div>
</li>
</code>```

I can select India from dropdown using the below code.

```<code>Select select = new Select(driver.findElement(By.xpath("path of the dropdown")));
select.selectByVisibleText("India");
</code>```

But I don't want to use Select here. Is there any other way to select India from dropdown.

Thanks in Advance

答:
You can use following alternative for selection of values from drop down:

```<code>driver.findElement(By.xpath("path of the dropdown")).sendKeys("India");
</code>```

Try this one. It will work.

Body:
In my automation suite I want to select a value from dropdown without using SELECT statement. Can someone please help me out with this.

Example:
I want to select a country name(India) from dropdown and I should not be using SELECT here.

Automation suite(Selenium with java)

Code:

    <form id="pie_regiser_form" enctype="multipart/form-data" method="post" action="/registration/">

    Country
        <select id="dropdown_7" class="piereg_validate[required]" name="dropdown_7">
        <option value="Afghanistan">Afghanistan</option>
        <option value="Albania">Albania</option>
        <option value="Algeria">Algeria</option>
        …
        <option value="India">India</option>
        …
        <option value="Zambia">Zambia</option>
        <option value="Zimbabwe">Zimbabwe</option>
        </select>

I can select India from dropdown using the below code.

Select select = new Select(driver.findElement(By.xpath("path of the dropdown")));
select.selectByVisibleText("India");

But I don't want to use Select here. Is there any other way to select India from dropdown.

Thanks in Advance

Body:
You can use following alternative for selection of values from drop down:

driver.findElement(By.xpath("path of the dropdown")).sendKeys("India");

Try this one. It will work.


问:
How do I insert a space between an alpha character and a numeric character?
This is a continuation of my original question:
Perl- How do I insert a space before each capital letter except for the first occurrence or existing?

I was able to achieve a desired result of inserting spaces between caps with only letters in the string:

```<code>my $camel ="SomeCamel IsEnteringText";
$camel =~ s/(?<=[a-z])(?=[A-Z])/ /g;
$camel =~ s/([^[:space:]]+)/\u$1/g;
</code>```

Prints:

Some Camel Is Entering Text

But, when numbers are present, I ran into issues:

```<code>my $camel ="Some 440Camel220 IsEntering100Text Nogo";
$camel =~ s/(?<=[a-z])(?=[A-Z])/ /g;
$camel =~ s/([^[:space:]]+)/\u$1/g;
</code>```

Prints:

Some 440Camel220 Is Entering100Text Nogo

Desired:

Some 440 Camel 220 Is Entering 100 Text Nogo

So, how do I now insert a space between the letters and the numbers?.

答:
Continuing from last night, a 5.10+ solution,

```<code>$camel =~ s/(?:\p{Lu}\p{Ll}*+|[0-9]++)(?!\W)\K/ /g;
</code>```

With the \p{} properties[1] that tchrist had me rediscover : ) It's basically the same solution as last time, but now we check for numbers too.

1: http://perldoc.perl.org/perluniprops.html#Properties-accessible-through-\p{}-and-\P{}

Body:
This is a continuation of my original question:
Perl- How do I insert a space before each capital letter except for the first occurrence or existing?

I was able to achieve a desired result of inserting spaces between caps with only letters in the string:

my $camel ="SomeCamel IsEnteringText";
$camel =~ s/(?<=[a-z])(?=[A-Z])/ /g;
$camel =~ s/([^[:space:]]+)/\u$1/g;

Prints:

Some Camel Is Entering Text

But, when numbers are present, I ran into issues:

my $camel ="Some 440Camel220 IsEntering100Text Nogo";
$camel =~ s/(?<=[a-z])(?=[A-Z])/ /g;
$camel =~ s/([^[:space:]]+)/\u$1/g;

Prints:

Some 440Camel220 Is Entering100Text Nogo

Desired:

Some 440 Camel 220 Is Entering 100 Text Nogo

So, how do I now insert a space between the letters and the numbers?.

Body:
Continuing from last night, a 5.10+ solution,

$camel =~ s/(?:\p{Lu}\p{Ll}*+|[0-9]++)(?!\W)\K/ /g;

With the \p{} properties[1] that tchrist had me rediscover : ) It's basically the same solution as last time, but now we check for numbers too.

1: http://perldoc.perl.org/perluniprops.html#Properties-accessible-through-\p{}-and-\P{}


问:
XML Values to retrieve in single Column with Any(,) Delimiter
My Xml file

```<code><Detials xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Tests>
  <Test Name="Test1" TotalMarks="100">95</Test>
  <Test Name="Test2" TotalMarks="200">65</Test>
  <Test Name="Test3" TotalMarks="150">95</Test>
  <Test Name="Test4" TotalMarks="150"></Test>
    </Tests>
</Detials>
</code>```

I want to query it back to view as

```<code>TestName         |TotalMarks     |ScoreObtained**
Test1,Test2,Test3,Test4|100,200,150,150| 95,65,95,|
</code>```

I tried with this ,But not able to get the Result above as i want,I got the error as XQuery [T1.XMLData.query()]: ")" was expected.

```<code>Select

                           TestName  = x.c.query ('STUFF((SELECT
              '','' + fd.v.value(''(.)[1]'', ''varchar(100)'')
           FROM
              XMLwithOpenXML
           CROSS APPLY
              XMLData.nodes(''/Tests/Test/@Name'') AS fd(v)
           FOR XML PATH('''')
          ), 1, 1, ''''')

                        From T1 s
                        Cross Apply s.XMLData.nodes('/Detials') AS x(c)
</code>```

Help me to solve this !

Thanks,Jayendran

答:
'TestName  = x.c.query ('STUFF((SELECT ...'

You tried to put a 'T-SQL'-statement within an XQuery-expression... That cannot work...

This approach seems dangerous...

With the given example the last entry is doubled. Your expected output shows three values as TestName, but four values as TotalMarksand four values (with an empty value at the end) as ScoreObtained. Your approach seems to me very dangerous... What, if there are two "Test1" entries? You would not know, whether the TotalMarks="200" belongs to this, or to "Test2". Is this really the output you need?

A possible solution

You might try this, but I really doubt, that your approach is correct:

```<code>DECLARE @xml XML=
'<Detials xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Tests>
  <Test Name="Test1" TotalMarks="100">95</Test>
  <Test Name="Test2" TotalMarks="200">65</Test>
  <Test Name="Test3" TotalMarks="150">95</Test>
  <Test Name="Test3" TotalMarks="150"></Test>
    </Tests>
</Detials>';

WITH DerivedTable AS
(
    SELECT t.value(N'@Name','nvarchar(max)') AS Name
          ,t.value(N'@TotalMarks','nvarchar(max)') AS Mark
          ,t.value(N'.','nvarchar(max)') AS Point --use 'text()[1]' to avoid empty values
    FROM @xml.nodes(N'/Detials/Tests/Test') AS A(t)
)
SELECT
    (
        STUFF(
        (
        SELECT ', ' + Name FROM DerivedTable GROUP BY Name ORDER BY Name FOR XML PATH(''),TYPE
        ).value(N'text()[1]','nvarchar(max)'),1,2,'')
    ) AS TestName
   ,(
        STUFF(
        (
        SELECT ', ' + Mark FROM DerivedTable ORDER BY Name FOR XML PATH(''),TYPE
        ).value(N'text()[1]','nvarchar(max)'),1,2,'')
    ) AS TotalMarks
   ,(
        STUFF(
        (
        SELECT ', ' + Point FROM DerivedTable ORDER BY Name FOR XML PATH(''),TYPE
        ).value(N'text()[1]','nvarchar(max)'),1,2,'')
    ) AS ScoreObtained;
</code>```

The result

```<code>TestName            TotalMarks          ScoreObtained
Test1, Test2, Test3 100, 200, 150, 150  95, 65, 95,
</code>```

Body:
My Xml file

<Detials xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Tests>
  <Test Name="Test1" TotalMarks="100">95</Test>
  <Test Name="Test2" TotalMarks="200">65</Test>
  <Test Name="Test3" TotalMarks="150">95</Test>
  <Test Name="Test4" TotalMarks="150"></Test>
    </Tests>
</Detials>

I want to query it back to view as

TestName         |TotalMarks     |ScoreObtained**
Test1,Test2,Test3,Test4|100,200,150,150| 95,65,95,|

I tried with this ,But not able to get the Result above as i want,I got the error as XQuery [T1.XMLData.query()]: ")" was expected.

Select

                           TestName  = x.c.query ('STUFF((SELECT
              '','' + fd.v.value(''(.)[1]'', ''varchar(100)'')
           FROM
              XMLwithOpenXML
           CROSS APPLY
              XMLData.nodes(''/Tests/Test/@Name'') AS fd(v)
           FOR XML PATH('''')
          ), 1, 1, ''''')

                        From T1 s
                        Cross Apply s.XMLData.nodes('/Detials') AS x(c)

Help me to solve this !

Thanks,Jayendran

Body:
'TestName  = x.c.query ('STUFF((SELECT ...'

You tried to put a 'T-SQL'-statement within an XQuery-expression... That cannot work...

This approach seems dangerous...

With the given example the last entry is doubled. Your expected output shows three values as TestName, but four values as TotalMarksand four values (with an empty value at the end) as ScoreObtained. Your approach seems to me very dangerous... What, if there are two "Test1" entries? You would not know, whether the TotalMarks="200" belongs to this, or to "Test2". Is this really the output you need?

A possible solution

You might try this, but I really doubt, that your approach is correct:

DECLARE @xml XML=
'<Detials xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Tests>
  <Test Name="Test1" TotalMarks="100">95</Test>
  <Test Name="Test2" TotalMarks="200">65</Test>
  <Test Name="Test3" TotalMarks="150">95</Test>
  <Test Name="Test3" TotalMarks="150"></Test>
    </Tests>
</Detials>';

WITH DerivedTable AS
(
    SELECT t.value(N'@Name','nvarchar(max)') AS Name
          ,t.value(N'@TotalMarks','nvarchar(max)') AS Mark
          ,t.value(N'.','nvarchar(max)') AS Point --use 'text()[1]' to avoid empty values
    FROM @xml.nodes(N'/Detials/Tests/Test') AS A(t)
)
SELECT
    (
        STUFF(
        (
        SELECT ', ' + Name FROM DerivedTable GROUP BY Name ORDER BY Name FOR XML PATH(''),TYPE
        ).value(N'text()[1]','nvarchar(max)'),1,2,'')
    ) AS TestName
   ,(
        STUFF(
        (
        SELECT ', ' + Mark FROM DerivedTable ORDER BY Name FOR XML PATH(''),TYPE
        ).value(N'text()[1]','nvarchar(max)'),1,2,'')
    ) AS TotalMarks
   ,(
        STUFF(
        (
        SELECT ', ' + Point FROM DerivedTable ORDER BY Name FOR XML PATH(''),TYPE
        ).value(N'text()[1]','nvarchar(max)'),1,2,'')
    ) AS ScoreObtained;

The result

TestName            TotalMarks          ScoreObtained
Test1, Test2, Test3 100, 200, 150, 150  95, 65, 95,


问:
How to use setState in external function?
```<code>import Request from 'superagent';

const getApi = () => {
    let url = '/* URL */';
    return Request.get(url).then((res) => {
        this.setState({
             content: res.body
        });
    });
}

export default getApi;
</code>```

I've created function in external file for api call. How do I get access to function/setState in external file?

```<code>componentWillMount(){
   getApi();
}
</code>```

I receive this error:

'TypeError: Cannot read property 'setState' of undefined'

答:
You can pass in a callback to the getApi function from your component.

```<code>const getApi = (onSuccess) => {
    let url = '/* URL */';
    return Request.get(url).then((res) => {
        onSuccess(res.body);
    });
}
</code>```

Component

```<code>componentWillMount(){
   getApi(this.setApiResponse);
}

setApiResponse(data) {
    this.setState({
        content: data
    });
}
</code>```

NB. As your project grows larger, you may wish to look into a state management system, such as Redux.

Body:
import Request from 'superagent';

const getApi = () => {
    let url = '/* URL */';
    return Request.get(url).then((res) => {
        this.setState({
             content: res.body
        });
    });
}

export default getApi;

I've created function in external file for api call. How do I get access to function/setState in external file?

componentWillMount(){
   getApi();
}

I receive this error:

'TypeError: Cannot read property 'setState' of undefined'

Body:
You can pass in a callback to the getApi function from your component.

const getApi = (onSuccess) => {
    let url = '/* URL */';
    return Request.get(url).then((res) => {
        onSuccess(res.body);
    });
}

Component

componentWillMount(){
   getApi(this.setApiResponse);
}

setApiResponse(data) {
    this.setState({
        content: data
    });
}

NB. As your project grows larger, you may wish to look into a state management system, such as Redux.


问:
html5 video on internet explorer
i have a problem.
I want to show my video on the page, but it doesn't work on IE 11 windows 7, on other it works fine. The problem is that other mp4 files works on IE 11, windows 7 too.

I don't know what is wrong with my video file that IE 11, windows 7 shows nothing

```<code><div class="my-video">
<div class="my-video-overlay"></div>
<video autoplay="autoplay" loop="loop">
<source src="http://megasystem.freshdraft.pl/wp-content/themes/x/video/megasys.mp4" type="video/mp4">
<source src="http://megasystem.freshdraft.pl/wp-content/themes/x/video/megasys.webm" type="video/webm">
<source src="http://megasystem.freshdraft.pl/wp-content/themes/x/video/megasys.ogv" type="video/ogv">
</video>
</div>
</code>```

答: I understand, but other mp4 files, which i tested plays on ie 11 windows 7 too. I think the problem must be with my video and I want to solve it (convert this video or something...)</p>

Title: html5 video on internet explorer

Body:
i have a problem.
I want to show my video on the page, but it doesn't work on IE 11 windows 7, on other it works fine. The problem is that other mp4 files works on IE 11, windows 7 too.

I don't know what is wrong with my video file that IE 11, windows 7 shows nothing

<video autoplay="autoplay" loop="loop">
<source src="http://megasystem.freshdraft.pl/wp-content/themes/x/video/megasys.mp4" type="video/mp4">
<source src="http://megasystem.freshdraft.pl/wp-content/themes/x/video/megasys.webm" type="video/webm">
<source src="http://megasystem.freshdraft.pl/wp-content/themes/x/video/megasys.ogv" type="video/ogv">
</video>


问:
how to show tick mark and an overlay on image while clicking an image, but when i click other image it should hide and display the same on new image?
i want the image to be overlay-ed with any color and give a tick mark on it(As it is selected) allowing only one image at  a time. while clicking other image it should hide the previous one and show tick and overlay on new image.

```<code><div class="grid-two imageandtext">
                                    <figure>

                                        <img src="assets/images/painting.jpg" class="img-thumbnail">
                                        <div class="caption">
                                            <p>Painting</p>
                                        </div>
                                        <div class="imageandtext image_grid">
                                            <img src="assets/images/photography.jpg" class="img-thumbnail" >
                                            <div class="caption1">
                                                <p>Photography</p>
                                            </div></div>
                                        </figure>
                                    </div>
</code>```

it should display like below image

now it is working like this

https://jsfiddle.net/liza_susan/L8jyum77/

答:
How about adding an image when someone hovers over it.

i.e.

```<code>.image-thumbnail:hover {
    background-image: <path to image>;
    background-repeat: no-repeat;
}
</code>```

Body:
i want the image to be overlay-ed with any color and give a tick mark on it(As it is selected) allowing only one image at  a time. while clicking other image it should hide the previous one and show tick and overlay on new image.

Painting

Photography

it should display like below image

now it is working like this

https://jsfiddle.net/liza_susan/L8jyum77/

Body:
How about adding an image when someone hovers over it.

i.e.

.image-thumbnail:hover {
    background-image: <path to image>;
    background-repeat: no-repeat;
}


问:
css first child not wokring
I have the following html

.resources .resource:first-child {
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="resources">
  <h2 class="text-center">Ресурси</h1>

    <div class="resource">
      <h4>Минерали <span class="resource-quantity">3700</span></h3>
    </div>

    <div class="resource">
      <h4>Газ <span class="resource-quantity">500</span></h3>
    </div>
</div></code>```

the selector without the first-child works fine. But the first-child selector it's not wrking in my case. Can someone tell me why ?

答:
Because that the .resource element that you want to stylize is the second child of it's parent, the first child is the h1 tag (careful, your heading tags were not properly closed).

You may be mistaken :first-child with :first-of-type.

:first-child only selects the .resource elements that are the first child within their parent container.

:first-of-type selects the .resource elements that are the first element matching the given selector (.resource) within their parent container, but not necessarily on the first-child position.

You can either use :nth-child(2) or :first-of-type, as in your case the element is the second child.

.resources .resource:nth-child(2){
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="resources">
  <h1 class="text-center">Ресурси</h1>

    <div class="resource">
      <h3>Минерали <span class="resource-quantity">3700</span></h3>
    </div>

    <div class="resource">
      <h3>Газ <span class="resource-quantity">500</span></h3>
    </div>
</div></code>```

Title: css first child not wokring

Body:
I have the following html

.resources .resource:first-child {
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}

Ресурси

Минерали 3700

Газ 500

the selector without the first-child works fine. But the first-child selector it's not wrking in my case. Can someone tell me why ?

Body:
Because that the .resource element that you want to stylize is the second child of it's parent, the first child is the h1 tag (careful, your heading tags were not properly closed).

You may be mistaken :first-child with :first-of-type.

:first-child only selects the .resource elements that are the first child within their parent container.

:first-of-type selects the .resource elements that are the first element matching the given selector (.resource) within their parent container, but not necessarily on the first-child position.

You can either use :nth-child(2) or :first-of-type, as in your case the element is the second child.

.resources .resource:nth-child(2){
  border-top: 1px solid #D9B310;
}

.resources .resource {
  border-bottom: 1px solid #D9B310;
  padding: 10px 0;
}

<div class="resources">
  <h1 class="text-center">Ресурси</h1>

    <div class="resource">
      <h3>Минерали <span class="resource-quantity">3700</span></h3>
    </div>

    <div class="resource">
      <h3>Газ <span class="resource-quantity">500</span></h3>
    </div>
</div>


问:
Thoughts on index creation for SQL Server for missing indexes
I'm working on performance tuning my SQL Server 2008 database and am using the output from various DMVs to identify missing indexes, indexes that aren't being used, etc.

I am mainly using these 3 scripts (from SQLServerCentral.com) that rely on DMV data that SQL Server provides:

The Ultimate Missing Index Finder

The Ultimate Duplicate Index Finder

The Ultimate Index Usage Reporter

When trying to create new indexes, I know that I need to be smart and try to group many of the suggestions into as few indexes as possible by creating them just right so that they can do a decent job of serving a few different queries vs. creating a separate index for each query when the only difference may be the included columns, etc.

So I wanted to get the community's thoughts and see if people can answer a few questions about reading the DMV results and structuring the new indexes.

Does the order of the included columns in an index matter?

Take the following two index suggestions.  What would you do to try to make 1 to fit both?

```<code>object_name equality_columns                    inequality_columns              included_columns
    Appointment [FranchiseId], [AppointmentTypeId]  [CustomerId], [ApptDateTime]    NULL
    Appointment [FranchiseId], [AppointmentTypeId]  [ApptDateTime]                  [CustomerId]
</code>```

If I have lots of index suggestions with the same equality and inequality fields but different included fields, is it better to include more fields or go with less included fields?  Again, the goal is to create 1 index vs. 3 (if 3 have different included columns).

Lastly, if there are any good resources out there that can offer up good rules of thumb or general guidelines for things like this I would appreciate it if those links could be provided.

答:
Order matters for indexed columns, but not included columns.  This is because only key columns are used for lookups.

You have to "read between the lines" of most of the documentation, but that's what they're implying in this BOL article

This discussion is a bit more explicit in saying order isn't important.

Pretty much the only concern with included columns in indexes is space--the indexes can get quite large if you include lots of columns, or very large columns. BUT this means you definitely don't want to do two separate indexes, each with the same key columns but different included ones. Then you're just compounding your space problem.

OwnerDisplayName: Don

Body:
I'm working on performance tuning my SQL Server 2008 database and am using the output from various DMVs to identify missing indexes, indexes that aren't being used, etc.

I am mainly using these 3 scripts (from SQLServerCentral.com) that rely on DMV data that SQL Server provides:

The Ultimate Missing Index Finder

The Ultimate Duplicate Index Finder

The Ultimate Index Usage Reporter

When trying to create new indexes, I know that I need to be smart and try to group many of the suggestions into as few indexes as possible by creating them just right so that they can do a decent job of serving a few different queries vs. creating a separate index for each query when the only difference may be the included columns, etc.

So I wanted to get the community's thoughts and see if people can answer a few questions about reading the DMV results and structuring the new indexes.

Does the order of the included columns in an index matter?

Take the following two index suggestions.  What would you do to try to make 1 to fit both?

object_name equality_columns                    inequality_columns              included_columns
    Appointment [FranchiseId], [AppointmentTypeId]  [CustomerId], [ApptDateTime]    NULL
    Appointment [FranchiseId], [AppointmentTypeId]  [ApptDateTime]                  [CustomerId]

If I have lots of index suggestions with the same equality and inequality fields but different included fields, is it better to include more fields or go with less included fields?  Again, the goal is to create 1 index vs. 3 (if 3 have different included columns).

Lastly, if there are any good resources out there that can offer up good rules of thumb or general guidelines for things like this I would appreciate it if those links could be provided.

OwnerDisplayName: BradC

LastEditorDisplayName: BradC


问:
How is a random number generated at runtime?
Since computers cannot pick random numbers(can they?) how is this random number actually generated. For example in C# we say,

```<code>Random.Next()
</code>```

What happens inside?

答: You may checkout this article. According to the documentation the specific implementation used in .NET is based on Donald E. Knuth's subtractive random number generator algorithm. For more information, see D. E. Knuth. "The Art of Computer Programming, volume 2: Seminumerical Algorithms". Addison-Wesley, Reading, MA, second edition, 1981.</p>

Body:
Since computers cannot pick random numbers(can they?) how is this random number actually generated. For example in C# we say,

Random.Next()

What happens inside?


问:
Type detection: using variadic arguments to properly implement a function that calculates the mean
I am trying to understand how to properly implement a function to calculate the mathematical sample mean, with two initial required characteristics:

1) using variadic arguments.

2) not using two functions to do the job, that is, not using a caller function and then a second function that actually does the calculation.

3) function should be as generic as possible

I am very aware that a pretty similar question has been already asked: Calculate the average of several values using a variadic-template function However, while the accepted answer to that question seems to have taught the OP how to do the small part he didn't know, it presents a code that is actually wrong and does not compile.

So, my own first attempt was along these lines:

```<code>template <class... Args>
double mean(const Args & ... args)
{
    auto total = 0;
    for (auto value : { ...args })
    {
        total += value;
    }
    return (double)total / sizeof...(args);
}
</code>```

The problem here is that in the line auto total = 0; the compile naturally can't automatically identify the type that object total should have.

Then, my second attempt:

```<code>template <class T, class... Args>
T mean(const T &t, const Args & ... args)
{
    T total = 0;
    for (auto value : { args... })
    {
        total += value;
    }
    return (T)(total / sizeof...(args));
}
</code>```

That version the following problem. It does not work if the caller calls the function with arguments of mixed type, like in mean(1, 2.5), where the first arguments is automatically detected as an int and the second is detected as a double.

I was able to solve that by doing the following:

```<code>template <class T, class... Args>
T mean(const T &t, const Args & ... args)
{
    size_t argsSize = sizeof...(args);
    T total = t;
    T arg_array[] = { args... };
    for (size_t i = 0; i< argsSize; i++)
    {
        total += (T)arg_array[i];
    }
    return (T)(total / argsSize) ;
}
</code>```

This one works even when passed arguments are of different types (of course, provided that such types can be converted to T). The problem now, however, is that the function only works with a minimum of two arguments. If it is called like in mean(3.14), while it should return 3.14, it actually raises an error because T arg_array[] = { args... } can't be compiled because it is impossible to have a static array be created with size 0. Sure, I could substitute it for a dynamic array, but that would make me have to do one memory allocation and one memory deallocation every time that the function is called - which is an unacceptable waste.

So, what would be the correct way to implement such a function that avoids the mentioned problems and that follows my two initial conditions?

答:
Use fold expressions in C++17

```<code>template<typename... Args>
constexpr decltype(auto) mean(Args&&... args)
{
    return (... + std::forward<Args>(args)) / sizeof...(Args);
}
</code>```

The std::forward is there for some bignum types that supports moving.

Before C++17, manual folding is required, but that will require overloading mean for a base case, which seems like not what you want.

Body:
I am trying to understand how to properly implement a function to calculate the mathematical sample mean, with two initial required characteristics:

1) using variadic arguments.

2) not using two functions to do the job, that is, not using a caller function and then a second function that actually does the calculation.

3) function should be as generic as possible

I am very aware that a pretty similar question has been already asked: Calculate the average of several values using a variadic-template function However, while the accepted answer to that question seems to have taught the OP how to do the small part he didn't know, it presents a code that is actually wrong and does not compile.

So, my own first attempt was along these lines:

template <class... Args>
double mean(const Args & ... args)
{
    auto total = 0;
    for (auto value : { ...args })
    {
        total += value;
    }
    return (double)total / sizeof...(args);
}

The problem here is that in the line auto total = 0; the compile naturally can't automatically identify the type that object total should have.

Then, my second attempt:

template <class T, class... Args>
T mean(const T &t, const Args & ... args)
{
    T total = 0;
    for (auto value : { args... })
    {
        total += value;
    }
    return (T)(total / sizeof...(args));
}

That version the following problem. It does not work if the caller calls the function with arguments of mixed type, like in mean(1, 2.5), where the first arguments is automatically detected as an int and the second is detected as a double.

I was able to solve that by doing the following:

template <class T, class... Args>
T mean(const T &t, const Args & ... args)
{
    size_t argsSize = sizeof...(args);
    T total = t;
    T arg_array[] = { args... };
    for (size_t i = 0; i< argsSize; i++)
    {
        total += (T)arg_array[i];
    }
    return (T)(total / argsSize) ;
}

This one works even when passed arguments are of different types (of course, provided that such types can be converted to T). The problem now, however, is that the function only works with a minimum of two arguments. If it is called like in mean(3.14), while it should return 3.14, it actually raises an error because T arg_array[] = { args... } can't be compiled because it is impossible to have a static array be created with size 0. Sure, I could substitute it for a dynamic array, but that would make me have to do one memory allocation and one memory deallocation every time that the function is called - which is an unacceptable waste.

So, what would be the correct way to implement such a function that avoids the mentioned problems and that follows my two initial conditions?

Body:
Use fold expressions in C++17

template<typename... Args>
constexpr decltype(auto) mean(Args&&... args)
{
    return (... + std::forward<Args>(args)) / sizeof...(Args);
}

The std::forward is there for some bignum types that supports moving.

Before C++17, manual folding is required, but that will require overloading mean for a base case, which seems like not what you want.


问:
How to play .mp4 video as a background video in Android?
I have watched many tutorials but somethings wrong. I have simple mainactivity and there is a VideoView on the it's layout. I downloaded a video from youtube as a .mp4 file size is about 10 mb. I found a great sample about videoview on youtube as the following link.

https://www.youtube.com/watch?v=tPeDn18FrGY&t=75s

ublic class MainActivity extends AppCompatActivity {

```<code>private VideoView bgVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bgVideo=(VideoView) findViewById(R.id.bg_videoview);

        Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.bgvideo);

        bgVideo.setVideoURI(uri);
        bgVideo.start();

        bgVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });
    }
}
</code>```

I use genymotion emulator. While i run the app i take "can't play this" error. And at the android monitor things like this.

```<code>06-07 03:16:28.675 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.675 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.692 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.692 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.709 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.709 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.742 2146-2146/com.sample E/MediaPlayer: Error (1,-32)
06-07 03:16:28.742 2146-2146/com.sample D/VideoView: Error: 1,-32
06-07 03:16:28.758 2146-2146/com.sample E/MediaPlayer: Error (1,-38)
06-07 03:16:28.758 2146-2146/com.sample D/VideoView: Error: 1,-38
06-07 03:16:29.526 2146-2146/com.sample I/Choreographer: Skipped 44 frames!  The application may be doing too much work on its main thread.
</code>```

How can i fix it ?

答:
You can use MediaPlayer object and play in one service. here is the example code:

```<code>public class Mp3PlayerService extends Service implements
        MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener {

    /** Android Built-in Media Player */
    public MediaPlayer player;

    /** Binder for Mp3 Service */
    private final IBinder iBinder = new Mp3PlayerService.BackgroundAudioServiceBinder();

    @Override
    public void onCreate() {
        super.onCreate();
        player = new MediaPlayer();
        player.setOnCompletionListener(this);
        player = new MediaPlayer();
        try {
          playSongLocal();
          playSongNetwork();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

    private void playsongLocal() {
        AssetFileDescriptor afd;
        player.reset();
        try {
            LogUtils.LOGE(TAG, "playing aaa.mp3");
            afd = getApplicationContext().getAssets().openFd("aaa.mp3");
            player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
            player.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playsongNetwork() {
        player.reset();
        try {
            player.setDataSource(networkUrlLink);
            player.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return iBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    public void onDestroy() {
        if (player.isPlaying()) {
            player.stop();
        }
        player.release();
    }

    /** return itself when beeing asked */
    public class BackgroundAudioServiceBinder extends Binder {
        public Mp3PlayerService getService() {
            return Mp3PlayerService.this;
        }
    }
</code>```

Body:
I have watched many tutorials but somethings wrong. I have simple mainactivity and there is a VideoView on the it's layout. I downloaded a video from youtube as a .mp4 file size is about 10 mb. I found a great sample about videoview on youtube as the following link.

https://www.youtube.com/watch?v=tPeDn18FrGY&t=75s

ublic class MainActivity extends AppCompatActivity {

private VideoView bgVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bgVideo=(VideoView) findViewById(R.id.bg_videoview);

        Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.bgvideo);

        bgVideo.setVideoURI(uri);
        bgVideo.start();

        bgVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });
    }
}

I use genymotion emulator. While i run the app i take "can't play this" error. And at the android monitor things like this.

06-07 03:16:28.675 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.675 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.692 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.692 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.709 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.709 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.742 2146-2146/com.sample E/MediaPlayer: Error (1,-32)
06-07 03:16:28.742 2146-2146/com.sample D/VideoView: Error: 1,-32
06-07 03:16:28.758 2146-2146/com.sample E/MediaPlayer: Error (1,-38)
06-07 03:16:28.758 2146-2146/com.sample D/VideoView: Error: 1,-38
06-07 03:16:29.526 2146-2146/com.sample I/Choreographer: Skipped 44 frames!  The application may be doing too much work on its main thread.

How can i fix it ?

Body:
You can use MediaPlayer object and play in one service. here is the example code:

public class Mp3PlayerService extends Service implements
        MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener {

    /** Android Built-in Media Player */
    public MediaPlayer player;

    /** Binder for Mp3 Service */
    private final IBinder iBinder = new Mp3PlayerService.BackgroundAudioServiceBinder();

    @Override
    public void onCreate() {
        super.onCreate();
        player = new MediaPlayer();
        player.setOnCompletionListener(this);
        player = new MediaPlayer();
        try {
          playSongLocal();
          playSongNetwork();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

    private void playsongLocal() {
        AssetFileDescriptor afd;
        player.reset();
        try {
            LogUtils.LOGE(TAG, "playing aaa.mp3");
            afd = getApplicationContext().getAssets().openFd("aaa.mp3");
            player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
            player.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playsongNetwork() {
        player.reset();
        try {
            player.setDataSource(networkUrlLink);
            player.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return iBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    public void onDestroy() {
        if (player.isPlaying()) {
            player.stop();
        }
        player.release();
    }

    /** return itself when beeing asked */
    public class BackgroundAudioServiceBinder extends Binder {
        public Mp3PlayerService getService() {
            return Mp3PlayerService.this;
        }
    }


问:
How can I remove spaces in view?
I use laravel 5.3

My case is like this :

My code in view :

```<code><div class="alert alert-warning" role="alert">
    "
    @if(isset($country))
        {{ $country }}
    @endif
    @if(isset($city))
        @if(isset($country))
            -
        @endif
        {{ $city }}
    @endif
    "
</div>
</code>```

The result like this :

" England - London "

I want the result like this :

"England - London"

How can I do it?

答:
Have you tried using the trim function of PHP?
http://php.net/manual/en/function.trim.php</p>

Title: How can I remove spaces in view?

Body:
I use laravel 5.3

My case is like this :

My code in view :

    "
    @if(isset($country))
        {{ $country }}
    @endif
    @if(isset($city))
        @if(isset($country))
            -
        @endif
        {{ $city }}
    @endif
    "

The result like this :

" England - London "

I want the result like this :

"England - London"

How can I do it?


答: This code is obfuscated. You can view a more readable version of it on sites like this. Chrome also has a built in beautifier. You still will have to figure out what it does. Also eval can be a bad idea.

Title: What is the encoding used in this code?


问:
Need to know the right way to scan infected website files
My website index.php and htaccess. file got infected and another PHP file of plugin and the website is down now. See the snapshot in this link [https://drive.google.com/open?id=0B6wLmLAtHwZCZnhmV0QzdDMyTW8][1]

could you tell my the way to scan these files? I have scanned with some free antivirus but it is not showing any virus infection. Help to solve this issue.

答: Please try to remove .htacess and index.php file both are default so you can reupload the code from google. Also you can scan your website with maldet scanner.</p>


问:
Display values in edit
I've been trying to display my edit values in the editContact page. I ran out of ideas as to how I'm supposed to fix this.

Here's my controller for edit

```<code>[HttpGet]
public ActionResult editContact(int? id)
{
    var databaseModel = new database();

    if (id == null)
    {
        return RedirectToAction("Index");
    }

    IEnumerable<contact> contact = databaseModel.displayContact(id);

    return View(contact);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult editContact(contact editModel, int id)
{
    try
    {
        programEntities db = new programEntities();
        var databaseModel = new database();

        if (databaseModel.editContact(editModel, id))
        {
            ViewBag.AlertMsg = "Contact edited successfully";
            return RedirectToAction("Index");
        }

        return View();
    }
    catch (Exception ex)
    {
        return View(ex);
    }
}
</code>```

In my model, I have this code that controls the database manipulation

```<code>   public List<contact> displayContact(int? Id)
   {
        using (SqlConnection conn = new SqlConnection(connectionString))
        using (SqlCommand comObj = new SqlCommand("displayContact", conn))
        {
            comObj.CommandType = CommandType.StoredProcedure;
            comObj.Parameters.Add(new SqlParameter("@contactId", Id));
            conn.Open();

            List<contact> contactList = new List<contact>();

            SqlDataAdapter da = new SqlDataAdapter(comObj);
            DataTable dt = new DataTable();

            //conn.Open();
            da.Fill(dt);
            conn.Close();

            contactList = (from DataRow dr in dt.Rows
                           select new contact()
                           {
                               contactId = Convert.ToInt32(dr["contactId"]),
                               establishmentType = Convert.ToString(dr["establishmentType"]),
                               ownerName = Convert.ToString(dr["ownerName"]),
                               address = Convert.ToString(dr["address"]),
                               city = Convert.ToString(dr["city"]),
                               region = Convert.ToString(dr["region"]),
                               mobileNumber = Convert.ToString(dr["mobileNumber"]),
                               phoneNumber = Convert.ToString(dr["phoneNumber"])
                           }).ToList();

            return contactList;
        }
}
</code>```

My view markup:

```<code>@model directory.Models.contact

@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>contact</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.contactId)

    <div class="form-group">
        @Html.LabelFor(model => model.establishmentType, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.establishmentType, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.establishmentType, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ownerName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.ownerName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ownerName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.address, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.address, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.address, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.city, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.city, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.city, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.region, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.region, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.region, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.mobileNumber, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.mobileNumber, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.mobileNumber, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.phoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.phoneNumber, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.phoneNumber, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
</code>```

I tried creating a different query to display the edit values, but the exception says my dispayContact stored procedure does not exist even though it does. My other stored procedure works well except for this one.

Edit

So I fixed my stored procedure in SQL Server; it was named "dispayContact". Still the edit values won't display even after adding firstOrDefault() and then changing the declaration in my view from @model directory.Models.contact to @model IEnumerable<directory.Models.contact>

答:
There are few issues with your function. You can use datareader which is much faster than data adopter. You also don't need to return a collection but just an object of your type:

Function to get object:

```<code>public contact displayContact(int? Id)
{
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        using (SqlCommand comObj = new SqlCommand("displayContact", conn))
        {
            comObj.CommandType = CommandType.StoredProcedure;
            comObj.Parameters.Add(new SqlParameter("@contactId", Id));
            conn.Open();

            using (SqlDataReader dr = comObj.ExecuteReader())
            {
                while (dr.Read())
                {
                    return new contact
                    {
                        contactId = int.Parse(dr["contactId"].ToString()),
                        establishmentType = dr["establishmentType"].ToString(),
                        ownerName = dr["ownerName"].ToString(),
                        address = dr["address"].ToString(),
                        city = dr["city"].ToString(),
                        region = dr["region"].ToString(),
                        mobileNumber = dr["mobileNumber"].ToString(),
                        phoneNumber = dr["phoneNumber"].ToString()
                    };
                }
            }
        }

        conn.Close();
    }
    return null;
}
</code>```

Controller Action:

```<code>public ActionResult editContact(int? id)
    {
            var databaseModel = new database();
            if (id == null)
            {
                return RedirectToAction("Index");
           }
        var contact = databaseModel.displayContact(id);
        return View(contact);
    }
</code>```

Title: Display values in edit

Body:
I've been trying to display my edit values in the editContact page. I ran out of ideas as to how I'm supposed to fix this.

Here's my controller for edit

[HttpGet]
public ActionResult editContact(int? id)
{
    var databaseModel = new database();

    if (id == null)
    {
        return RedirectToAction("Index");
    }

    IEnumerable<contact> contact = databaseModel.displayContact(id);

    return View(contact);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult editContact(contact editModel, int id)
{
    try
    {
        programEntities db = new programEntities();
        var databaseModel = new database();

        if (databaseModel.editContact(editModel, id))
        {
            ViewBag.AlertMsg = "Contact edited successfully";
            return RedirectToAction("Index");
        }

        return View();
    }
    catch (Exception ex)
    {
        return View(ex);
    }
}

In my model, I have this code that controls the database manipulation

   public List<contact> displayContact(int? Id)
   {
        using (SqlConnection conn = new SqlConnection(connectionString))
        using (SqlCommand comObj = new SqlCommand("displayContact", conn))
        {
            comObj.CommandType = CommandType.StoredProcedure;
            comObj.Parameters.Add(new SqlParameter("@contactId", Id));
            conn.Open();

            List<contact> contactList = new List<contact>();

            SqlDataAdapter da = new SqlDataAdapter(comObj);
            DataTable dt = new DataTable();

            //conn.Open();
            da.Fill(dt);
            conn.Close();

            contactList = (from DataRow dr in dt.Rows
                           select new contact()
                           {
                               contactId = Convert.ToInt32(dr["contactId"]),
                               establishmentType = Convert.ToString(dr["establishmentType"]),
                               ownerName = Convert.ToString(dr["ownerName"]),
                               address = Convert.ToString(dr["address"]),
                               city = Convert.ToString(dr["city"]),
                               region = Convert.ToString(dr["region"]),
                               mobileNumber = Convert.ToString(dr["mobileNumber"]),
                               phoneNumber = Convert.ToString(dr["phoneNumber"])
                           }).ToList();

            return contactList;
        }
}

My view markup:

@model directory.Models.contact

@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Edit

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

contact

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.contactId)

        @Html.LabelFor(model => model.establishmentType, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.establishmentType, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.establishmentType, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.ownerName, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.ownerName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ownerName, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.address, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.address, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.address, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.city, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.city, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.city, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.region, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.region, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.region, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.mobileNumber, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.mobileNumber, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.mobileNumber, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.phoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.phoneNumber, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.phoneNumber, "", new { @class = "text-danger" })

            <input type="submit" value="Save" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

I tried creating a different query to display the edit values, but the exception says my dispayContact stored procedure does not exist even though it does. My other stored procedure works well except for this one.

Edit

So I fixed my stored procedure in SQL Server; it was named "dispayContact". Still the edit values won't display even after adding firstOrDefault() and then changing the declaration in my view from @model directory.Models.contact to @model IEnumerable<directory.Models.contact>

Body:
There are few issues with your function. You can use datareader which is much faster than data adopter. You also don't need to return a collection but just an object of your type:

Function to get object:

public contact displayContact(int? Id)
{
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        using (SqlCommand comObj = new SqlCommand("displayContact", conn))
        {
            comObj.CommandType = CommandType.StoredProcedure;
            comObj.Parameters.Add(new SqlParameter("@contactId", Id));
            conn.Open();

            using (SqlDataReader dr = comObj.ExecuteReader())
            {
                while (dr.Read())
                {
                    return new contact
                    {
                        contactId = int.Parse(dr["contactId"].ToString()),
                        establishmentType = dr["establishmentType"].ToString(),
                        ownerName = dr["ownerName"].ToString(),
                        address = dr["address"].ToString(),
                        city = dr["city"].ToString(),
                        region = dr["region"].ToString(),
                        mobileNumber = dr["mobileNumber"].ToString(),
                        phoneNumber = dr["phoneNumber"].ToString()
                    };
                }
            }
        }

        conn.Close();
    }
    return null;
}

Controller Action:

public ActionResult editContact(int? id)
    {
            var databaseModel = new database();
            if (id == null)
            {
                return RedirectToAction("Index");
           }
        var contact = databaseModel.displayContact(id);
        return View(contact);
    }