问:
Android Studio project
Hi i am doing an andorid studio project, when I am adding my data the application and then trying to view the data im getting an Error saying "Error, Nothing Found". I made up a SQLite Database and hope someone can help me find the error.</p>

```<code>package ie.wit.andrew.drivingschool;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Driver.db";
public static final String TABLE_NAME = "driver_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "DATE OF BIRTH";
public static final String COL_4 = "LOGBOOK NUMBER";   //Making up my
                                                       //database of the
                                                       //information I will
                                                       //be entering into my
                                                       //application
public static final String COL_5 = "LESSON NUMBER";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1); //when this constructor is
                                            //called your Database has been
                                            //created

}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT,NAME TEXT,DATE OF BIRTH TEXT, LOGBOOK NUMBER TEXT, LESSON
NUMBER INTEGER)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);

}

public boolean insertData(String name, String dateofbirth, String
logbooknumber, String lessonnumber) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_2,name);
    contentValues.put(COL_3,dateofbirth);
    contentValues.put(COL_4,logbooknumber);
    contentValues.put(COL_5,lessonnumber);
    long result = db.insert(TABLE_NAME,null,contentValues); //This method
                                                            //returns -1
    if (result == -1)
        return false;
    else
        return true;
}

public Cursor getAllData() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from "+ TABLE_NAME,null);
    return res;
}
}

package ie.wit.andrew.drivingschool;

import android.database.Cursor;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class DrivingSchool extends AppCompatActivity {

DatabaseHelper myDb;
EditText editName,editDateofBirth,editLogbookNumber,editLessonNumber;
Button btnAddData;
Button btnviewAll;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_driving_school);
    myDb = new DatabaseHelper(this);

    editName = (EditText)findViewById(R.id.editText_name);
    editDateofBirth = (EditText)findViewById(R.id.editText_dateofbirth);
    editLogbookNumber = (EditText)findViewById(R.id.editText_logbooknumber);
    editLessonNumber = (EditText)findViewById(R.id.editText_lessonNumber);
    btnAddData = (Button)findViewById(R.id.button_add);
    btnviewAll = (Button)findViewById(R.id.button_viewAll);
    AddData();
    viewAll();
 }

   public void AddData() {
    btnAddData.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                  boolean isInserted =
    myDb.insertData(editName.getText().toString(),
                            editDateofBirth.getText().toString(),
                            editLogbookNumber.getText().toString(),
                            editLessonNumber.getText().toString());
                    if(isInserted = true)
                        Toast.makeText(DrivingSchool.this,"Data
     Inserted",Toast.LENGTH_LONG).show();
                    else
                        Toast.makeText(DrivingSchool.this,"Data not
   Inserted", Toast.LENGTH_LONG).show();
                 }
              }
      );
   }

  public  void viewAll() {
    btnviewAll.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v){
                    Cursor res = myDb.getAllData();
                     if(res.getCount() == 0) {
                          //Show Message
                         showMessage("Error", "Nothing found");
                         return;
                     }

                     StringBuffer buffer = new StringBuffer();
                    while(res.moveToNext()) {
                        buffer.append("ID : "+ res.getString(0)+"\n");
                        buffer.append("NAME : "+ res.getString(1)+"\n");
                        buffer.append("DATE OF BIRTH : "+
                        res.getString(2)+"\n");
                        buffer.append("LOGBOOK NUMBER : "+
                        res.getString(3)+"\n\n");;

                    }

                    //showdata
                    showMessage("Data",buffer.toString());
                }
            }
      );

  }

  public void showMessage(String title,String Message){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(Message);
        builder.show();
  }
}
</code>```

答:
you are providing wrong column name that's why your database is not creating, please check this link for complete guide for creating and using database in Android application

http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

Title: Android Studio project

Body:
Hi i am doing an andorid studio project, when I am adding my data the application and then trying to view the data im getting an Error saying "Error, Nothing Found". I made up a SQLite Database and hope someone can help me find the error.

package ie.wit.andrew.drivingschool;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Driver.db";
public static final String TABLE_NAME = "driver_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "DATE OF BIRTH";
public static final String COL_4 = "LOGBOOK NUMBER";   //Making up my
                                                       //database of the
                                                       //information I will
                                                       //be entering into my
                                                       //application
public static final String COL_5 = "LESSON NUMBER";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1); //when this constructor is
                                            //called your Database has been
                                            //created

}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT,NAME TEXT,DATE OF BIRTH TEXT, LOGBOOK NUMBER TEXT, LESSON
NUMBER INTEGER)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);

}

public boolean insertData(String name, String dateofbirth, String
logbooknumber, String lessonnumber) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_2,name);
    contentValues.put(COL_3,dateofbirth);
    contentValues.put(COL_4,logbooknumber);
    contentValues.put(COL_5,lessonnumber);
    long result = db.insert(TABLE_NAME,null,contentValues); //This method
                                                            //returns -1
    if (result == -1)
        return false;
    else
        return true;
}

public Cursor getAllData() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from "+ TABLE_NAME,null);
    return res;
}
}

package ie.wit.andrew.drivingschool;

import android.database.Cursor;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class DrivingSchool extends AppCompatActivity {

DatabaseHelper myDb;
EditText editName,editDateofBirth,editLogbookNumber,editLessonNumber;
Button btnAddData;
Button btnviewAll;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_driving_school);
    myDb = new DatabaseHelper(this);

    editName = (EditText)findViewById(R.id.editText_name);
    editDateofBirth = (EditText)findViewById(R.id.editText_dateofbirth);
    editLogbookNumber = (EditText)findViewById(R.id.editText_logbooknumber);
    editLessonNumber = (EditText)findViewById(R.id.editText_lessonNumber);
    btnAddData = (Button)findViewById(R.id.button_add);
    btnviewAll = (Button)findViewById(R.id.button_viewAll);
    AddData();
    viewAll();
 }

   public void AddData() {
    btnAddData.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                  boolean isInserted =
    myDb.insertData(editName.getText().toString(),
                            editDateofBirth.getText().toString(),
                            editLogbookNumber.getText().toString(),
                            editLessonNumber.getText().toString());
                    if(isInserted = true)
                        Toast.makeText(DrivingSchool.this,"Data
     Inserted",Toast.LENGTH_LONG).show();
                    else
                        Toast.makeText(DrivingSchool.this,"Data not
   Inserted", Toast.LENGTH_LONG).show();
                 }
              }
      );
   }

  public  void viewAll() {
    btnviewAll.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v){
                    Cursor res = myDb.getAllData();
                     if(res.getCount() == 0) {
                          //Show Message
                         showMessage("Error", "Nothing found");
                         return;
                     }

                     StringBuffer buffer = new StringBuffer();
                    while(res.moveToNext()) {
                        buffer.append("ID : "+ res.getString(0)+"\n");
                        buffer.append("NAME : "+ res.getString(1)+"\n");
                        buffer.append("DATE OF BIRTH : "+
                        res.getString(2)+"\n");
                        buffer.append("LOGBOOK NUMBER : "+
                        res.getString(3)+"\n\n");;

                    }

                    //showdata
                    showMessage("Data",buffer.toString());
                }
            }
      );

  }

  public void showMessage(String title,String Message){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(Message);
        builder.show();
  }
}


来源: stackexchange

问:
How do I extend this mergeWords function to any number of strings?
Following is the mergeWords function.

```<code>mergeWords [] [] = []
mergeWords [] (y:ys) = y:'\n':(mergeWords [] ys)
mergeWords (x:xs) [] = x:'\n':(mergeWords xs [])
mergeWords (x:xs) (y:ys) = x:y:'\n':(mergeWords xs ys)
</code>```

If applied on mergeWords "hello" "world" it gives

```<code>"hw\neo\nlr\nll\nod\n"
</code>```

I can't figure out how to extend this to list of strings. Like applying it to 3 strings should first take first character of each of the strings and then put a '\n' and then the second character and so on.

答:
Sounds reasonably easy if you do it in steps:

```<code>cutWords :: [String] -> [[String]]    -- ["ab", "cd", "e"] -> [["a", "c", "e"], ["b", "d"]]
concatWord :: [String] -> String       -- ["a", "c", "e"] -> "ace\n"
concatWords :: [String] -> String    -- use mergeWord on all of them
</code>```

The most interesting part is of course the cutWords part. What you want there is a zip-like behaviour, and for that it'll help if we "safe" tail and head:

```<code>head' (x:xs) = [x]
head' "" = ""

tail' (x:xs) = xs
tail' "" = ""
</code>```

Now we can implement our cutWords, making sure we stop in time:

```<code>cutWords xs = heads : rest
  where
    heads = map head' xs
    tails = map tail' xs
    rest = if any (/= "") tails then cutWords tails
                                else []
</code>```

Then the remaining part is trivial:

```<code>concatWord word = concat word ++ "\n"
concatWords words = concatMap concatWord word
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Following is the mergeWords function.

mergeWords [] [] = []
mergeWords [] (y:ys) = y:'\n':(mergeWords [] ys)
mergeWords (x:xs) [] = x:'\n':(mergeWords xs [])
mergeWords (x:xs) (y:ys) = x:y:'\n':(mergeWords xs ys)

If applied on mergeWords "hello" "world" it gives

"hw\neo\nlr\nll\nod\n"

I can't figure out how to extend this to list of strings. Like applying it to 3 strings should first take first character of each of the strings and then put a '\n' and then the second character and so on.

Body:
Sounds reasonably easy if you do it in steps:

cutWords :: [String] -> [[String]]    -- ["ab", "cd", "e"] -> [["a", "c", "e"], ["b", "d"]]
concatWord :: [String] -> String       -- ["a", "c", "e"] -> "ace\n"
concatWords :: [String] -> String    -- use mergeWord on all of them

The most interesting part is of course the cutWords part. What you want there is a zip-like behaviour, and for that it'll help if we "safe" tail and head:

head' (x:xs) = [x]
head' "" = ""

tail' (x:xs) = xs
tail' "" = ""

Now we can implement our cutWords, making sure we stop in time:

cutWords xs = heads : rest
  where
    heads = map head' xs
    tails = map tail' xs
    rest = if any (/= "") tails then cutWords tails
                                else []

Then the remaining part is trivial:

concatWord word = concat word ++ "\n"
concatWords words = concatMap concatWord word


问:
How to run vstest.console.exe for Unit Test 64-bit platform
How to run vstest.console.exe targeting the 64-bit platform?

Unit Tests set to target platform x64 were failing to run on DevOps tools (VSTS/TeamCity/Octopus).

[error]Error: None of the provided test containers match the Platform Architecture and .Net Framework settings for the test run.

Platform: X86  .Net Framework: Framework45. Go to
http://go.microsoft.com/fwlink/?LinkID=330428 for more details on
managing these settings.

答:
Check if you have vstest.console.exe under C:\
Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\CommonExtensions\Mi
crosoft\TestWindow\

from cmd go to the path where your projects dll are kept.
i.e. cd C:\Users\krakhil\Desktop\Notes\Practice Codes\VerifyExe\VerifyExe\bin\Debug

Press Enter

Then write -> "C:\
Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\CommonExtensions\Mi
crosoft\TestWindow\vstest.console.exe" VerifyExe.dll

Where VerifyExe.dll is the project dll i want to execute.


问:
how to fetch value from JSONOBJECT inside JSONARRAY?
I am working on application in which i need to show all the ATM. I am fetching the data from google api, but i am not able to fetch all the data. I want to fetch latitude and longitude but when I am fetch the data I am getting only one value.

```<code>String url = "https://maps.googleapis.com/maps/api/place/radarsearch/json?location=23.308003,81.3275914&radius=5000&type=atm&key=AIzaSyCYZoSkxHC_Exym4YBWvXZXwMyJA7dzEB4";
        try {
            JSONObject jObject = new JSONObject(request(url));
            String jj = jObject.getString("status");

            JSONArray data = jObject.getJSONArray("results");

            location = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> map;

            for(int i = 0; i < data.length(); i++){
                JSONObject c = data.getJSONObject(i);
                map = new HashMap<String, String>();

            JSONObject geometry = c.getJSONObject("geometry");
            JSONObject locate = geometry.getJSONObject("location");
            String lat = locate.getString("lat");
            String lng = locate.getString("lng");
            Log.e("Data", lat+"--"+lng);
            //map.put("LocationID", c.getString("id"));
            //map.put("placeId",c.getString("place_id"));
            //location.add(map);

            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
</code>```

答:
I will suggest you to go through some parsing tutorial. Later you can us libraries like gson or jackson to parse you json. Now lot of people don't write json parsing code themselves.

Once you understand the json structure you should be able to parse it yourself.

Your json

```<code>"results": [ // array
    {        //  jsonobject
        "geometry": {  // geometry jsonobject
            "location": {   // location jsonobject
                // values
                "lat": 23.3085793,
                "lng": 81.353116
            }
        },
        ... // the rest of the json
</code>```

Then

```<code>// this is right
JSONArray data = jObject.getJSONArray("results");
</code>```

After that

```<code>   for(int i = 0; i < data.length(); i++){
       JSONObject c = data.getJSONObject(i);
       JSONObject geometry = c.getJSONObject("geometry");
       JSONObject location = geometry.getJSONObject("location");
       String lat = location.getString("lat");
       String lng = location.getString("lng");

       Log.d("Location->"," "+lat+" "+lng);
       // now do what you want.
       // You probably meant to do
       map = new HashMap<String, String>();
       map.put("lat",lat);
       map.pt("lng",lng);
       location.add(map);

   }
</code>```

Body:
I am working on application in which i need to show all the ATM. I am fetching the data from google api, but i am not able to fetch all the data. I want to fetch latitude and longitude but when I am fetch the data I am getting only one value.

String url = "https://maps.googleapis.com/maps/api/place/radarsearch/json?location=23.308003,81.3275914&radius=5000&type=atm&key=AIzaSyCYZoSkxHC_Exym4YBWvXZXwMyJA7dzEB4";
        try {
            JSONObject jObject = new JSONObject(request(url));
            String jj = jObject.getString("status");

            JSONArray data = jObject.getJSONArray("results");

            location = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> map;

            for(int i = 0; i < data.length(); i++){
                JSONObject c = data.getJSONObject(i);
                map = new HashMap<String, String>();

            JSONObject geometry = c.getJSONObject("geometry");
            JSONObject locate = geometry.getJSONObject("location");
            String lat = locate.getString("lat");
            String lng = locate.getString("lng");
            Log.e("Data", lat+"--"+lng);
            //map.put("LocationID", c.getString("id"));
            //map.put("placeId",c.getString("place_id"));
            //location.add(map);

            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Body:
I will suggest you to go through some parsing tutorial. Later you can us libraries like gson or jackson to parse you json. Now lot of people don't write json parsing code themselves.

Once you understand the json structure you should be able to parse it yourself.

Your json

"results": [ // array
    {        //  jsonobject
        "geometry": {  // geometry jsonobject
            "location": {   // location jsonobject
                // values
                "lat": 23.3085793,
                "lng": 81.353116
            }
        },
        ... // the rest of the json

Then

// this is right
JSONArray data = jObject.getJSONArray("results");

After that

   for(int i = 0; i < data.length(); i++){
       JSONObject c = data.getJSONObject(i);
       JSONObject geometry = c.getJSONObject("geometry");
       JSONObject location = geometry.getJSONObject("location");
       String lat = location.getString("lat");
       String lng = location.getString("lng");

       Log.d("Location->"," "+lat+" "+lng);
       // now do what you want.
       // You probably meant to do
       map = new HashMap<String, String>();
       map.put("lat",lat);
       map.pt("lng",lng);
       location.add(map);

   }


问:
What data structure should I use to store a collection of items in C#?
I have following string : [Value:"Car" - Name:"Manufactor" [Value:"Audi" - Name:"A6"][Value:"BMW" - Name:"M4"]]]

I need to split the string and save data into suitable data structure. Starting bracket "[" indicates the beginning of the collection, and
matching ending bracket "]" indicates the end of the collection. The "-" character seperates key and values. So I was wondering what is most
logical datastructure to use here? Is using a tree good solution? I have splitted the string up in parts, I only need help to choose a logical datastructure.

Thanks!

答:
You can just do the same as what JavaScriptSerializer does. It returns a Dictionary(Of String, Object) and Object is either a string or an other Dictionary(Of String, Object).

The best way would be to have proper classes and good property name and store the information.


问:
Dockerized Angular 4 and Django is compiled successfully but localhost:4200 is not working
I would like to dockerize Angular 4 frontend with Django backend and postgresql database. At this moment my files looks as shown below. I am note sure if this is done properly? When I try docker-compose up I get information that both frontend with Angular 4 and backend with Django started successfully. Unfortunately when I open http://localhost:4200 it doesn't work (localhost:8001 seems working):

```<code>Safari can't open the page because the server unexpectedly dropped the connection
</code>```

My logs:

```<code>django_1   | Django version 1.11, using settings 'project.settings'
django_1   | Starting development server at http://0.0.0.0:8001/
django_1   | Quit the server with CONTROL-C.
angular_1  | ** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
angular_1  | Time: 20657ms
angular_1  | chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 232 kB {4} [initial] [rendered]
angular_1  | chunk    {1} main.bundle.js, main.bundle.js.map (main) 222 kB {3} [initial] [rendered]
angular_1  | chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 11.6 kB {4} [initial] [rendered]
angular_1  | chunk    {3} vendor.bundle.js, vendor.bundle.js.map (vendor) 4.41 MB [initial] [rendered]
angular_1  | chunk    {4} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]
angular_1  | webpack: Compiled successfully.
</code>```

Structure of my files:

```<code>├── Backend
│   ├── AI
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── __init__.cpython-36.pyc
│   │   │   ├── settings.cpython-36.pyc
│   │   │   ├── urls.cpython-36.pyc
│   │   │   └── wsgi.cpython-36.pyc
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py
│   └── manage.py
├── Dockerfile
├── Frontend
│   └── angularProject
        ├── Dockerfile
│       └── all files in my angular project
├── docker-compose.yml
└── requirements.txt
</code>```

Dockerfile from frontend:

```<code># Create image based on the official Node 6 image from dockerhub
FROM node:6

# Create a directory where our app will be placed
RUN mkdir -p /usr/src/app

# Change directory so that our commands run inside this new directory
WORKDIR /usr/src/app

# Copy dependency definitions
COPY package.json /usr/src/app

# Install dependecies
RUN npm install

# Get all the code needed to run the app
COPY . /usr/src/app

# Expose the port the app runs in
EXPOSE 4200

# Serve the app
CMD ["npm", "start"]
</code>```

Dockerfile from main directory:

```<code>FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/
</code>```

docker-compose.yml:

```<code>version: '3'

services:
  db:
    image: postgres
    environment:
      POSTGRES_USER: aso
      POSTGRES_PASSWORD: somepass
  django:
    build: .
    command: python3 MainDirectory/backend/myProject/manage.py runserver 0.0.0.0:8001
    volumes:
      - .:/code
    ports:
      - "8001:8001"
    depends_on:
      - db
  angular:
    build: MainDirectory/frontend
    ports:
      - "4200:4200"
    depends_on:
      - django
</code>```

Listening:

```<code>CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
e214d1966286        dockerproj_angular   "npm start"              2 hours ago         Up 36 seconds       0.0.0.0:4200->4200/tcp   dockerpri_angular_1
b9fa457bd119        dockerproj_django    "python3 PROJ/backe..."   2 hours ago         Up 37 seconds       0.0.0.0:8000->8000/tcp   dockerpri_django_1
e36635448b6e        postgres            "docker-entrypoint..."   2 hours ago         Up 37 seconds       5432/tcp                 dockerpri_db_1
docker exec e214d1966286 ss -ltn
State      Recv-Q Send-Q        Local Address:Port          Peer Address:Port
LISTEN     0      128              127.0.0.11:42403                    *:*
LISTEN     0      128               127.0.0.1:4200                     *:*
</code>```

SOLUTION:
I changed in package.json "start": "ng serve" to "start": "ng serve --host 0.0.0.0".

答:
The problem seems to be related to the interface that your node app is listening to.

When docker maps a port, it does it between host interfaces and the eth0 container interface, and not to the localhost interface.

So, as you stated, changing this:

```<code>"start": "ng serve"
</code>```

to:

```<code>"start": "ng serve --host 0.0.0.0".
</code>```

will solve the problem.

Body:
I would like to dockerize Angular 4 frontend with Django backend and postgresql database. At this moment my files looks as shown below. I am note sure if this is done properly? When I try docker-compose up I get information that both frontend with Angular 4 and backend with Django started successfully. Unfortunately when I open http://localhost:4200 it doesn't work (localhost:8001 seems working):

Safari can't open the page because the server unexpectedly dropped the connection

My logs:

django_1   | Django version 1.11, using settings 'project.settings'
django_1   | Starting development server at http://0.0.0.0:8001/
django_1   | Quit the server with CONTROL-C.
angular_1  | ** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
angular_1  | Time: 20657ms
angular_1  | chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 232 kB {4} [initial] [rendered]
angular_1  | chunk    {1} main.bundle.js, main.bundle.js.map (main) 222 kB {3} [initial] [rendered]
angular_1  | chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 11.6 kB {4} [initial] [rendered]
angular_1  | chunk    {3} vendor.bundle.js, vendor.bundle.js.map (vendor) 4.41 MB [initial] [rendered]
angular_1  | chunk    {4} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]
angular_1  | webpack: Compiled successfully.

Structure of my files:

├── Backend
│   ├── AI
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── __init__.cpython-36.pyc
│   │   │   ├── settings.cpython-36.pyc
│   │   │   ├── urls.cpython-36.pyc
│   │   │   └── wsgi.cpython-36.pyc
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py
│   └── manage.py
├── Dockerfile
├── Frontend
│   └── angularProject
        ├── Dockerfile
│       └── all files in my angular project
├── docker-compose.yml
└── requirements.txt

Dockerfile from frontend:

# Create image based on the official Node 6 image from dockerhub
FROM node:6

# Create a directory where our app will be placed
RUN mkdir -p /usr/src/app

# Change directory so that our commands run inside this new directory
WORKDIR /usr/src/app

# Copy dependency definitions
COPY package.json /usr/src/app

# Install dependecies
RUN npm install

# Get all the code needed to run the app
COPY . /usr/src/app

# Expose the port the app runs in
EXPOSE 4200

# Serve the app
CMD ["npm", "start"]

Dockerfile from main directory:

FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/

docker-compose.yml:

version: '3'

services:
  db:
    image: postgres
    environment:
      POSTGRES_USER: aso
      POSTGRES_PASSWORD: somepass
  django:
    build: .
    command: python3 MainDirectory/backend/myProject/manage.py runserver 0.0.0.0:8001
    volumes:
      - .:/code
    ports:
      - "8001:8001"
    depends_on:
      - db
  angular:
    build: MainDirectory/frontend
    ports:
      - "4200:4200"
    depends_on:
      - django

Listening:

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
e214d1966286        dockerproj_angular   "npm start"              2 hours ago         Up 36 seconds       0.0.0.0:4200->4200/tcp   dockerpri_angular_1
b9fa457bd119        dockerproj_django    "python3 PROJ/backe..."   2 hours ago         Up 37 seconds       0.0.0.0:8000->8000/tcp   dockerpri_django_1
e36635448b6e        postgres            "docker-entrypoint..."   2 hours ago         Up 37 seconds       5432/tcp                 dockerpri_db_1
docker exec e214d1966286 ss -ltn
State      Recv-Q Send-Q        Local Address:Port          Peer Address:Port
LISTEN     0      128              127.0.0.11:42403                    *:*
LISTEN     0      128               127.0.0.1:4200                     *:*

SOLUTION:
I changed in package.json "start": "ng serve" to "start": "ng serve --host 0.0.0.0".

Body:
The problem seems to be related to the interface that your node app is listening to.

When docker maps a port, it does it between host interfaces and the eth0 container interface, and not to the localhost interface.

So, as you stated, changing this:

"start": "ng serve"

to:

"start": "ng serve --host 0.0.0.0".

will solve the problem.


问:
onKeyPress event in Firefox and IE8
I have the following Javascript code. Here I am using onKeyPress="someFunction( )" in the body tag to get the keyCode of the key that is pressed.

The code is working fine in IE8 but this is not working in Firefox.

Please give some solution to this.

```<code><html>
<head>
<title>onKeyPress( ) event not working in firefox..</title>
<script>
function printDiv()
{
  var divToPrint=document.getElementById('prnt');
  newWin=window.open(''+self.location,'PrintWin','left=50,top=20,width=590,height=840,toolbar=1,resizable=1,scrollbars=yes');
  newWin.document.write(divToPrint.outerHTML);
  newWin.print();
  //newWin.close();
}
</script>

<script>
function keypress()
{
  alert(event.keyCode);
  var key=event.keyCode;
  if(key==112 || key==80)
 printDiv();
  else if(key==101 || key==69)
    window.location="http://google.com";
  else if(key==114 || key==82)
    window.reset();
}
</script>
</head>
<body bgcolor="lightblue" onkeypress="keypress()">
</code>```

Here is the total code which is working fine in IE8 and not working in Firefox.

```<code><!DOCTYPE html>
<html>
    <head>
    <title>Please help me out</title>
    <script type="text/javascript">
    function printDiv()
    {
      var divToPrint=document.getElementById('prnt');
      newWin=window.open(''+self.location,'PrintWin','left=50,top=20,width=590,height=840,toolbar=1,resizable=1,scrollbars=yes');
      newWin.document.write(divToPrint.outerHTML);
      newWin.print();
    }
    </script>

    <script type="text/javascript">
    function keypress(val)
    {
      //-----------------------------------------------------
      //alert('nnnn');
      //alert(window.event ? event.keyCode : val.which);
      //if(val.which != 0 && val.charCode != 0)
      // alert('Firefox'+String.fromCharCode(val.which));
      //else
      // alert('IE');
      //-------------------------------------------------------
      var key=event.keyCode;
      if(key==112 || key==80 || val=="print")
        printDiv();
      else if(key==101 || key==69 || val=="exit")
        window.location="http://google.co.in";
      else if(key==114 || key==82 || val=="refresh")
        document.forms[0].reset();
      else
        event.returnValue=true;
    }
    </script>
</head>
<body bgcolor="lightblue" topmargin="0" leftmargin="0"marginwidth="0px" marginheight="0px" onkeypress="keypress(null)">
<table align="left" border="1" cellpadding="5" cellspacing="0" style="width: 100%;height:100%">
<tbody>
<tr><td width="20%" valign="top">ccccccccccc</td>
    <td width="80%" align="center">
        <table style="width: 100%" border="0" valign="top">
        <tr align="right">
        <td valign="top">
        <button value="refresh" accesskey="R" onclick="keypress(this.value)">
            <b><u>R</u></b>efresh
        </button>
        <button value="print" accesskey="P" onclick="keypress(this.value)">
              <b><u>P</u></b>rint
        </button>
        <button value="exit" accesskey="E" onclick="keypress(this.value)">
               <b><u>E</u></b>xit
        </button>
        </td></tr>
        </table>
        <h3>Press the letters P->Print , E->Exit etc....</h3>
        <h1>Just a test for keypress event</h1>
        <form action="http://google.co.in" method="Post">
            <div id="prnt">
                zzzzzzzzzzzzzzz
            </div>
        </form>
    </td>
</tr>
</tbody>
</table></body></html>
</code>```

答:
Browsers have different ways of handling keyboard events. Have a look at http://unixpapa.com/js/key.html for more info.

For example, these changes to your code will get it working in Firefox:

```<code><body bgcolor="lightblue" onkeypress="keypress(e)">
</code>```

and

```<code>function keypress(e) {
    alert(window.event ? event.keyCode : e.which);
    // other stuff
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: onKeyPress event in Firefox and IE8

Body:
I have the following Javascript code. Here I am using onKeyPress="someFunction( )" in the body tag to get the keyCode of the key that is pressed.

The code is working fine in IE8 but this is not working in Firefox.

Please give some solution to this.

<title>onKeyPress( ) event not working in firefox..</title>

Here is the total code which is working fine in IE8 and not working in Firefox.

<!DOCTYPE html>

    <title>Please help me out</title>

ccccccccccc

        <button value="refresh" accesskey="R" onclick="keypress(this.value)">
            Refresh
        </button>
        <button value="print" accesskey="P" onclick="keypress(this.value)">
              Print
        </button>
        <button value="exit" accesskey="E" onclick="keypress(this.value)">
               Exit
        </button>

Press the letters P->Print , E->Exit etc....

Just a test for keypress event

        <form action="http://google.co.in" method="Post">

                zzzzzzzzzzzzzzz

        </form>

Body:
Browsers have different ways of handling keyboard events. Have a look at http://unixpapa.com/js/key.html for more info.

For example, these changes to your code will get it working in Firefox:

<body bgcolor="lightblue" onkeypress="keypress(e)">

and

function keypress(e) {
    alert(window.event ? event.keyCode : e.which);
    // other stuff
}

ContentLicense: CC BY-SA 2.5


问:
multiload file xls in SheetJs
i want try multiload xls files and view values in SheetJS but work only last in array url.

```<code><!doctype html>
<html>
<head>
<title>Excel to JSON Demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.10.7/xlsx.full.min.js"></script>
</head>
<body>

<script>
/* set up XMLHttpRequest */

var url = new Array();
url.push("2017_01_Zole.xls");
url.push("2017_03_TK.xls");
url.push("2017_05_Psy.xls");

for(var z = 0; z<url.length; z++){
    var oReq = new XMLHttpRequest();
    oReq.open("GET", url[z], true);
    oReq.responseType = "arraybuffer";
    oReq.onload = function(e) {
      var arraybuffer = oReq.response;

      /* convert data to binary string */
      var data = new Uint8Array(arraybuffer);
      var arr = new Array();
      for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
      var bstr = arr.join("");

      /* Call XLSX */
      var workbook = XLSX.read(bstr, {type:"binary"});

      /* DO SOMETHING WITH workbook HERE */
      var first_sheet_name = workbook.SheetNames[0];
      /* Get worksheet */
      var worksheet = workbook.Sheets[first_sheet_name];
     // jsn = XLSX.utils.sheet_to_json(worksheet,{raw:true});
      console.log(worksheet['F3'].v +' = '+ worksheet['J3'].v);

    };
    oReq.send();
}

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

After each loop I want to display the result in console.log. Unfortunately, it only shows me data from the last file.

答:
Moved solution from question to answer:

EDIT:
  Problem solved

```<code>var x = 0;
function xlsy(urls){
    var oReq = new XMLHttpRequest();
    oReq.open("GET", urls, true);
    //.......
    oReq.send();
    x++;
    if(x < url.length){
        xlsy(url[x])
    }
}
xlsy(url[0]);
</code>```

Title: multiload file xls in SheetJs

Body:
i want try multiload xls files and view values in SheetJS but work only last in array url.

<!doctype html>

<title>Excel to JSON Demo</title>

After each loop I want to display the result in console.log. Unfortunately, it only shows me data from the last file.

Body:
Moved solution from question to answer:

EDIT:
  Problem solved

var x = 0;
function xlsy(urls){
    var oReq = new XMLHttpRequest();
    oReq.open("GET", urls, true);
    //.......
    oReq.send();
    x++;
    if(x < url.length){
        xlsy(url[x])
    }
}
xlsy(url[0]);


问:
Jquery not removing row
I have this jQuery where it append a row with link to remove the row. I have this code but it doesn't remove the row.

everything is working except for the function remove()

There is no error too.

```<code>var currentTotal = 0;

function remove(id) {
  $(this).closest('tr').remove();

}

$(document).ready(function() {

      var arr = [];

      $("#btnAdd").click(function() {

        var medname = $("#MedicineID option:selected").text();
        var id = $("#MedicineID option:selected").val();
        var qty = $("#myID").val();

        $.ajax({

          url: '/Purchases/GetValue',
          type: 'GET',
          datatype: 'json',
          data: {
            'id': id
          },
          success: function(val) {

            if (qty == 0) {
              alert("Please define the quantity");
            } else {
              var item = $('#MedicineID').val();

              if ($.inArray(item, arr) != -1) {
                alert("Specified medicine is already been added")
              } else {
                arr.push(item);
                if (currentTotal == 0) {
                  currentTotal = val * qty;
                  $("#tblList").append('<tr> <td>' + medname + '</td>  <td>' + qty + '</td><td> ' + val + '  </td>  <td><a onclick="remove(' + id + ')" class="remove" href="#">Remove</a></td></tr>');
                  $('#total').text(currentTotal);
                } else {
                  var price = val * qty;
                  currenTotal = currentTotal += price;
                  $("#tblList").append('<tr> <td>' + medname + '</td>  <td>' + qty + '</td><td> ' + price + '  </td>  <td><a onclick="remove(' + id + ')" class="remove" href="#">Remove</a></td></tr>');
                  $('#total').text(currentTotal);
                }
              }
            }
          }
        })
      });
</code>```

Here is the tables in my view

```<code> <table id="tblList" class="table">
        <tr>
            <th>
                Item
            </th>
            <th>
                Qty
            </th>
            <th>
                Price
            </th>
            <th>
            </th>
        </tr>
    </table>
    <br />
    <table class="table">
        <tr>
            <th>Total</th>
            <th></th>
            <th><p id="total">0</p></th>
            <th></th>
        </tr>
    </table>
</code>```

答:
I think You need to try this hope its works.</p>

```<code>     $(".remove").on('click', function (e) {
        $(this).closest('tr').remove();
    });
</code>```

Title: Jquery not removing row

Body:
I have this jQuery where it append a row with link to remove the row. I have this code but it doesn't remove the row.

everything is working except for the function remove()

There is no error too.

var currentTotal = 0;

function remove(id) {
  $(this).closest('tr').remove();

}

$(document).ready(function() {

      var arr = [];

      $("#btnAdd").click(function() {

        var medname = $("#MedicineID option:selected").text();
        var id = $("#MedicineID option:selected").val();
        var qty = $("#myID").val();

        $.ajax({

          url: '/Purchases/GetValue',
          type: 'GET',
          datatype: 'json',
          data: {
            'id': id
          },
          success: function(val) {

            if (qty == 0) {
              alert("Please define the quantity");
            } else {
              var item = $('#MedicineID').val();

              if ($.inArray(item, arr) != -1) {
                alert("Specified medicine is already been added")
              } else {
                arr.push(item);
                if (currentTotal == 0) {
                  currentTotal = val * qty;
                  $("#tblList").append('
 ' + medname + '	  ' + qty + '	 ' + val + '  	  Remove
');
                  $('#total').text(currentTotal);
                } else {
                  var price = val * qty;
                  currenTotal = currentTotal += price;
                  $("#tblList").append('
 ' + medname + '	  ' + qty + '	 ' + price + '  	  Remove
');
                  $('#total').text(currentTotal);
                }
              }
            }
          }
        })
      });

Here is the tables in my view

                Item

                Qty

                Price

            Total

0

Body:
I think You need to try this hope its works.

     $(".remove").on('click', function (e) {
        $(this).closest('tr').remove();
    });


问:
Redirect to the same page with retrieved values from database in laravel?
View Code:

```<code> <li class="active"><a href="#tab_1" data-toggle="tab"  id="versiontab"
onclick="window.location='{{ url("versiondb") }}'" >Version
 Database</a></li>
</code>```

This is my view code.This is also a tab .Onclicking the tab the url redirection works.

Route Code:

```<code>Route::get('versiondb','versiondbController@select');
</code>```

Controllercode:

```<code>public function select()
{

    $users=debModel::all();
    return redirect()->back()->with($users);

}
</code>```

Here it should fetches the values from db and redirecting back to the same page and display the retreived values in table .But i am getting an error here as $users undefined

Inside the Same view (specified above):

```<code> <table class="table" id="table">
      @foreach($users as $users)
        <thead>
          <tr class="header">
              <th valign="middle" width="3%">Versions</th>
              <th valign="middle" width="2%">Supported versions</th>
              <th valign="middle" width="10%">Release Date</th>
              <th valign="middle" width="3%">Type</th>
              <th valign="middle" width="10%">Description</th>
              <th valign="middle" width="3%">Actions</th>
              <th valign="middle" width="3%">Downloader</th>
              <!--<th valign="middle" width="3%">Beta code</th>-->

            </tr>
            </thead>
            <tbody>
            <tr>
            <td>{{$users->versions}}</td>
            <td></td>

            </tr>
          @endforeach
            </tbody>

                </table>
</code>```

I think this is the place where error occurs.

答:
The issue is here:

```<code>@foreach($users as $users)
</code>```

here your array variable name and the variable in which you are holding the data on each iteration is the same, so change it to:

```<code>@foreach($users as $user)
  <td>{{$user->versions}}</td>
</code>```

Body:
View Code:

Version
 Database

This is my view code.This is also a tab .Onclicking the tab the url redirection works.

Route Code:

Route::get('versiondb','versiondbController@select');

Controllercode:

public function select()
{

    $users=debModel::all();
    return redirect()->back()->with($users);

}

Here it should fetches the values from db and redirecting back to the same page and display the retreived values in table .But i am getting an error here as $users undefined

Inside the Same view (specified above):

      @foreach($users as $users)

              Versions
              Supported versions
              Release Date
              Type
              Description
              Actions
              Downloader

            {{$users->versions}}

          @endforeach

I think this is the place where error occurs.

Body:
The issue is here:

@foreach($users as $users)

here your array variable name and the variable in which you are holding the data on each iteration is the same, so change it to:

@foreach($users as $user)
  <td>{{$user->versions}}</td>


问:
Angular 2 FormBuilder disable fields on checkbox select
I have build angular cli project and have a form with checkbox. Some of the fields must disable on checkbox select.

Form is as follows:

need to disable/enable password, new password and re type password fields on checkbox select event.

Html

```<code><form [formGroup]="userProfileForm" (ngSubmit)="submitForm(userProfileForm.value)">

    <div class="row">
        <div class="col">
            <div class="form-group">
                <label> {{ 'USER_PROFILE_MODEL.USER_NAME' | translate }}</label>
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['userName']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.DISPLAY_NAME' | translate }}</label>
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['displayName']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.EMAIL' | translate }}</label>
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['email']">
            </div>
        </div>
        <div class="col">
            <div class="form-group ">
                <label class="checkbox-inline">
                <input type="checkbox" value="isResetPassword" name="isResetPassword" [formControl]="userProfileForm.controls['isResetPassword']">
                 {{ 'USER_PROFILE_MODEL.RESET_PASSWORD' | translate }}
              </label>
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.PASSWORD' | translate }}</label>
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['password']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.NEW_PASSWORD' | translate }}</label>
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['newPassword']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.RE_TYPE_PASSWORD' | translate }}</label>
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['reTypePassword']">
            </div>

        </div>

    </div>
</form>
</code>```

ts code

```<code>this.isResetPassword = true;
this.userProfileForm = formBuilder.group({
    'userName': [null, [Validators.required]],
    'displayName': [null],
    'email': [null, [Validators.required]],
    'isResetPassword': this.isResetPassword,
    'password': [{
        value: null,
        disabled: this.isResetPassword
    }],
    'newPassword': [{
        value: null,
        disabled: this.isResetPassword
    }],
    'reTypePassword': [{
        value: null,
        disabled: this.isResetPassword
    }]
})
</code>```

Form has built inside the constructor.
How can I disable/enable the above fields on check box select.

答:
Instead of using [formControl] for your controls in the template, use formControlName.

Your form will look like this:

```<code><form [formGroup]="userProfileForm" (ngSubmit)="submitForm(userProfileForm.value)">

    <div class="row">
        <div class="col">
            <div class="form-group">
                <label> {{ 'USER_PROFILE_MODEL.USER_NAME' | translate }}</label>
                <input class="form-control" type="text" formControlName="userName">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.DISPLAY_NAME' | translate }}</label>
                <input class="form-control" type="text" formControlName="displayName">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.EMAIL' | translate }}</label>
                <input class="form-control" type="text" formControlName="email">
            </div>
        </div>
        <div class="col">
            <div class="form-group ">
                <label class="checkbox-inline">
                <input type="checkbox" value="isResetPassword" name="isResetPassword" formControlName="isResetPassword">
                 {{ 'USER_PROFILE_MODEL.RESET_PASSWORD' | translate }}
              </label>
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.PASSWORD' | translate }}</label>
                <input class="form-control" type="password" formControlName="password" [attr.disabled]="userProfileForm.value.isResetPassword?'':null">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.NEW_PASSWORD' | translate }}</label>
                <input class="form-control" type="password" formControlName="newPassword" [attr.disabled]="userProfileForm.value.isResetPassword?'':null">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.RE_TYPE_PASSWORD' | translate }}</label>
                <input class="form-control" type="password" formControlName="reTypePassword" [attr.disabled]="userProfileForm.value.isResetPassword?'':null">
            </div>

        </div>

    </div>
</form>
</code>```

And you have to define your form like this:

```<code>this.userProfileForm = formBuilder.group({
    'userName': [null, [Validators.required]],
    'displayName': [null],
    'email': [null, [Validators.required]],
    'isResetPassword': [false],
    'password': [null],
    'newPassword': [null],
    'reTypePassword': [null]
})
</code>```

Body:
I have build angular cli project and have a form with checkbox. Some of the fields must disable on checkbox select.

Form is as follows:

need to disable/enable password, new password and re type password fields on checkbox select event.

Html

<form [formGroup]="userProfileForm" (ngSubmit)="submitForm(userProfileForm.value)">

                 {{ 'USER_PROFILE_MODEL.USER_NAME' | translate }}
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['userName']">

                {{ 'USER_PROFILE_MODEL.DISPLAY_NAME' | translate }}
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['displayName']">

                {{ 'USER_PROFILE_MODEL.EMAIL' | translate }}
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['email']">

                <input type="checkbox" value="isResetPassword" name="isResetPassword" [formControl]="userProfileForm.controls['isResetPassword']">
                 {{ 'USER_PROFILE_MODEL.RESET_PASSWORD' | translate }}

                {{ 'USER_PROFILE_MODEL.PASSWORD' | translate }}
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['password']">

                {{ 'USER_PROFILE_MODEL.NEW_PASSWORD' | translate }}
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['newPassword']">

                {{ 'USER_PROFILE_MODEL.RE_TYPE_PASSWORD' | translate }}
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['reTypePassword']">

</form>

ts code

this.isResetPassword = true;
this.userProfileForm = formBuilder.group({
    'userName': [null, [Validators.required]],
    'displayName': [null],
    'email': [null, [Validators.required]],
    'isResetPassword': this.isResetPassword,
    'password': [{
        value: null,
        disabled: this.isResetPassword
    }],
    'newPassword': [{
        value: null,
        disabled: this.isResetPassword
    }],
    'reTypePassword': [{
        value: null,
        disabled: this.isResetPassword
    }]
})

Form has built inside the constructor.
How can I disable/enable the above fields on check box select.

Body:
Instead of using [formControl] for your controls in the template, use formControlName.

Your form will look like this:

<form [formGroup]="userProfileForm" (ngSubmit)="submitForm(userProfileForm.value)">

    <div class="row">
        <div class="col">
            <div class="form-group">
                <label> {{ 'USER_PROFILE_MODEL.USER_NAME' | translate }}</label>
                <input class="form-control" type="text" formControlName="userName">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.DISPLAY_NAME' | translate }}</label>
                <input class="form-control" type="text" formControlName="displayName">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.EMAIL' | translate }}</label>
                <input class="form-control" type="text" formControlName="email">
            </div>
        </div>
        <div class="col">
            <div class="form-group ">
                <label class="checkbox-inline">
                <input type="checkbox" value="isResetPassword" name="isResetPassword" formControlName="isResetPassword">
                 {{ 'USER_PROFILE_MODEL.RESET_PASSWORD' | translate }}
              </label>
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.PASSWORD' | translate }}</label>
                <input class="form-control" type="password" formControlName="password" [attr.disabled]="userProfileForm.value.isResetPassword?'':null">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.NEW_PASSWORD' | translate }}</label>
                <input class="form-control" type="password" formControlName="newPassword" [attr.disabled]="userProfileForm.value.isResetPassword?'':null">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.RE_TYPE_PASSWORD' | translate }}</label>
                <input class="form-control" type="password" formControlName="reTypePassword" [attr.disabled]="userProfileForm.value.isResetPassword?'':null">
            </div>

        </div>

    </div>
</form>

And you have to define your form like this:

this.userProfileForm = formBuilder.group({
    'userName': [null, [Validators.required]],
    'displayName': [null],
    'email': [null, [Validators.required]],
    'isResetPassword': [false],
    'password': [null],
    'newPassword': [null],
    'reTypePassword': [null]
})


问:
Add polygon in A-frame
Is there a way to add polygon in A-frame? Kinda like:

```<code><a-entity geometry="primitive:polygon;positions:x y z, ..., x y z;">
</a-entity>
</code>```

?

Thanks.

答:
There used to be a polygon-component, but it doesn't work with 0.5.0 or 0.6.0. So you have to make your own in three.js, by creating a component which adds a mesh to your entity:

```<code>let points = []; //vertices of Your shape
points.push( new THREE.Vector2( 0, 0 ) );
points.push( new THREE.Vector2( 3, 0 ) );
points.push( new THREE.Vector2( 5, 2 ) );
points.push( new THREE.Vector2( 5, 5 ) );
points.push( new THREE.Vector2( 5, 5 ) );
points.push( new THREE.Vector2( 2, 7 ) );
// scaling, not necessary:
for( var i = 0; i < points.length; i ++ ) {
    points[ i ].multiplyScalar( 0.25 );
}
// Create new shape out of the points:
var heartShape = new THREE.Shape(points);
// Create geometry out of the shape
var geometry = new THREE.ShapeGeometry( heartShape );
// Give it a basic material
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
// Create a mesh using our geometry and material
var mesh = new THREE.Mesh( geometry, material ) ;
// add it to the entity:
this.el.object3D.add( mesh );
</code>```

Working fiddle here, it's the 'foo' component.

UPDATE

You can make the shape to a 3D object by extruding it along the z-axis, using:

```<code>var extrudedGeometry = new THREE.ExtrudeGeometry(shape, {amount: 5,
bevelEnabled: false});
</code>```

You can find more information about extrusion params here. The amount is the 'thickness' of the object.

Working fiddle here.

Title: Add polygon in A-frame

Body:
Is there a way to add polygon in A-frame? Kinda like:

?

Thanks.

Body:
There used to be a polygon-component, but it doesn't work with 0.5.0 or 0.6.0. So you have to make your own in three.js, by creating a component which adds a mesh to your entity:

let points = []; //vertices of Your shape
points.push( new THREE.Vector2( 0, 0 ) );
points.push( new THREE.Vector2( 3, 0 ) );
points.push( new THREE.Vector2( 5, 2 ) );
points.push( new THREE.Vector2( 5, 5 ) );
points.push( new THREE.Vector2( 5, 5 ) );
points.push( new THREE.Vector2( 2, 7 ) );
// scaling, not necessary:
for( var i = 0; i < points.length; i ++ ) {
    points[ i ].multiplyScalar( 0.25 );
}
// Create new shape out of the points:
var heartShape = new THREE.Shape(points);
// Create geometry out of the shape
var geometry = new THREE.ShapeGeometry( heartShape );
// Give it a basic material
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
// Create a mesh using our geometry and material
var mesh = new THREE.Mesh( geometry, material ) ;
// add it to the entity:
this.el.object3D.add( mesh );

Working fiddle here, it's the 'foo' component.

UPDATE

You can make the shape to a 3D object by extruding it along the z-axis, using:

var extrudedGeometry = new THREE.ExtrudeGeometry(shape, {amount: 5,
bevelEnabled: false});

You can find more information about extrusion params here. The amount is the 'thickness' of the object.

Working fiddle here.


问:
Run swift script from Xcode iOS project as build phase
Here is a simple swift script:

```<code>#!/usr/bin/env xcrun swift

import Foundation

let task = NSTask()
task.launchPath = "/bin/echo"
task.arguments = ["farg1", "arg2"]

let pipe = NSPipe()
task.standardOutput = pipe
task.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: NSUTF8StringEncoding)

print(output)
</code>```

I added this script as build phase(before 'compile sources phase) in iOS project but XCode failed to build project with error 'undefined NSTask()...'
When I added same script in OSX project, XCode build project without any errors.

Question is why XCode is looking for NSTask inside iOS framework(where doesn't exists) instead to run swift script as platform script(like bash)?

Just to add: swift script isn't included into project with other files to compile. It's just added into build phase, even before compilation, of other source files(which are objective-c files) to run it.

Any ideas how to run custom swift script from iOS XCode project when script contains classes which aren't part of iOS framework?

答: If you unset the SDKROOT environment variable before calling the swift script, it will then use the OS X sdk.

Body:
Here is a simple swift script:

#!/usr/bin/env xcrun swift

import Foundation

let task = NSTask()
task.launchPath = "/bin/echo"
task.arguments = ["farg1", "arg2"]

let pipe = NSPipe()
task.standardOutput = pipe
task.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: NSUTF8StringEncoding)

print(output)

I added this script as build phase(before 'compile sources phase) in iOS project but XCode failed to build project with error 'undefined NSTask()...'
When I added same script in OSX project, XCode build project without any errors.

Question is why XCode is looking for NSTask inside iOS framework(where doesn't exists) instead to run swift script as platform script(like bash)?

Just to add: swift script isn't included into project with other files to compile. It's just added into build phase, even before compilation, of other source files(which are objective-c files) to run it.

Any ideas how to run custom swift script from iOS XCode project when script contains classes which aren't part of iOS framework?


问:
C Program crashes after assigning value to string
Relatively new to C, don't see what I'm doing wrong here, this piece of code crashes after assigning the 3rd string:

```<code>QW_Be *sentence = (QW_Be*)malloc(sizeof(QW_Be*));
sentence->questionword->word = words[0];
sentence->verb->word = words[1];
sentence->subject->word = words[2]; //crashes here ?
</code>```

words is an char *[ ], and here's the structure of "sentence":

```<code>typedef struct QW_Be{
    Word *questionword;
    Word *verb;
    Word *subject;
    Word *rest[];
} QW_Be;
</code>```

and here's the structure of 'Word':

```<code>typedef struct Word{
    char *word;
    word_type type;
    char *context;
} Word;
</code>```

If you need any more info, just ask !

答:
You should allocate the size of the struct and not the size of a pointer to the struct:</p>

```<code>QW_Be *sentence = (QW_Be*)malloc(sizeof(QW_Be));
</code>```

Body:
Relatively new to C, don't see what I'm doing wrong here, this piece of code crashes after assigning the 3rd string:

QW_Be *sentence = (QW_Be*)malloc(sizeof(QW_Be*));
sentence->questionword->word = words[0];
sentence->verb->word = words[1];
sentence->subject->word = words[2]; //crashes here ?

words is an char *[ ], and here's the structure of "sentence":

typedef struct QW_Be{
    Word *questionword;
    Word *verb;
    Word *subject;
    Word *rest[];
} QW_Be;

and here's the structure of 'Word':

typedef struct Word{
    char *word;
    word_type type;
    char *context;
} Word;

If you need any more info, just ask !

Body:
You should allocate the size of the struct and not the size of a pointer to the struct:

QW_Be *sentence = (QW_Be*)malloc(sizeof(QW_Be));


问:
Hiding Empty Cells
I'm currently working on a code that hides empty cells ,but the problem is i want it to start hiding at a certain range ("A9:A12") not at the beginning of the sheet.
here is my program :

```<code>Sub EmptyRow()
'Dim s As String
po = Range("A9:A12").Count
Range("A8").Activate

For i = 1 To po
 s = i & ":" & i
 If IsEmpty(Cells(i, 1).Value) Then
     Rows(s).Select
     Selection.EntireRow.Hidden = True
End If
Next

End Sub
</code>```

The program keeps on hiding cells from the beginning, how do I set it up so it deletes from the range i want it to. Please help.

答:
You can even make your code shorter like this:

```<code>For i = 9 To 12
    Cells(i, 1).EntireRow.Hidden = IsEmpty(Cells(i, 1).Value)
Next i
</code>```

Thus, the result of the Hidden property would be dependent on whether the Cells(i,1) is empty. It is easier to understand and to maintain.

Title: Hiding Empty Cells

Body:
I'm currently working on a code that hides empty cells ,but the problem is i want it to start hiding at a certain range ("A9:A12") not at the beginning of the sheet.
here is my program :

Sub EmptyRow()
'Dim s As String
po = Range("A9:A12").Count
Range("A8").Activate

For i = 1 To po
 s = i & ":" & i
 If IsEmpty(Cells(i, 1).Value) Then
     Rows(s).Select
     Selection.EntireRow.Hidden = True
End If
Next

End Sub

The program keeps on hiding cells from the beginning, how do I set it up so it deletes from the range i want it to. Please help.

Body:
You can even make your code shorter like this:

For i = 9 To 12
    Cells(i, 1).EntireRow.Hidden = IsEmpty(Cells(i, 1).Value)
Next i

Thus, the result of the Hidden property would be dependent on whether the Cells(i,1) is empty. It is easier to understand and to maintain.


问:
Storing IDs of table rows
sorry to bother some of you again. But I still haven't found a working answer to my problem.

I have a good old fashioned HTML table. Each reach has its unique ID. What I want to achieve with JavaScript is that this ID gets stored in a variable once I cklick a link on each row.

Might sound easy to you, I am new to JS and I can't figure it out to the end. Could someone help me please?

Thanks!

答:
you have to take a global variable for this. U can take it into the head section like-

var idHolder;

Now in the table onclick handler u call a function like-

table onclick="extractId(obj)">

The function definition may be like this-

function extractId(var obj)
{
   idHolder=obj.Id;
}

This will do ur work, in case of any problem reply.

Title: Storing IDs of table rows


问:
Ajax load cause jump Issue and flickering issue
I have five tabs.
On clicking a tab, loading the content through ajax (.load()). Each tab content varies. Which cause the browser to jump.
Is there any possibility to avoid these jump ?
I tried min-height but content height varies dynamically so setting it cause empty space on the page also.
This issue occurs only once.If I again click on the same tab,then there will be no jump.

Flickering,
Tab content have images. It cause flickering too.

Kindly share your thoughts to overcome these jump & flickering.

Adding code:

```<code>jQuery("#tabs a").click(function(event){
    var url_to_load = jQuery(this).attr('href');

    jQuery( ".tab-content-wrapper" ).load(url_to_load+" .tab-content-wrapper", function( response, status, xhr ) {
    var head = response.match(/<meta[^>]*>[\s\S]/gi);
    jQuery("meta").remove();
    jQuery("head").prepend(head);

    });

});`
</code>```

答: try using Ladda or load all the tabs content previously (lazy load if it is lots of data) and just change it trought tabs preventing defaults</p>

Body:
I have five tabs.
On clicking a tab, loading the content through ajax (.load()). Each tab content varies. Which cause the browser to jump.
Is there any possibility to avoid these jump ?
I tried min-height but content height varies dynamically so setting it cause empty space on the page also.
This issue occurs only once.If I again click on the same tab,then there will be no jump.

Flickering,
Tab content have images. It cause flickering too.

Kindly share your thoughts to overcome these jump & flickering.

Adding code:

jQuery("#tabs a").click(function(event){
    var url_to_load = jQuery(this).attr('href');

    jQuery( ".tab-content-wrapper" ).load(url_to_load+" .tab-content-wrapper", function( response, status, xhr ) {
    var head = response.match(/<meta[^>]*>[\s\S]/gi);
    jQuery("meta").remove();
    jQuery("head").prepend(head);

    });

});`


问:
How to split a String using | as the regex?
Im running this code and getting the wrong output.
It seems like | as the expression in split is giving wrong output

```<code>public static void main(String[] args) {
    String s = "Hi, |+nl+|+nl+| split me please";
    String[] sArr = s.split("|");

    for (String sa : sArr) {
        System.out.println(sa);
    }
}
</code>```

Output:

```<code>H
i
,

|
+
n
l
+
|
+
n
l
+
|

s
p
l
i
t

m
e

p
l
e
a
s
e
</code>```

How can I split it properly that it gets split this way?
Hi,
+n1+
+n1+
and so forth

答:
You may have to escape the |. </p>

```<code>String[] sArr = s.split("\\|");
</code>```

Body:
Im running this code and getting the wrong output.
It seems like | as the expression in split is giving wrong output

public static void main(String[] args) {
    String s = "Hi, |+nl+|+nl+| split me please";
    String[] sArr = s.split("|");

    for (String sa : sArr) {
        System.out.println(sa);
    }
}

Output:

H
i
,

|
+
n
l
+
|
+
n
l
+
|

s
p
l
i
t

m
e

p
l
e
a
s
e

How can I split it properly that it gets split this way?
Hi,
+n1+
+n1+
and so forth

Body:
You may have to escape the |.

String[] sArr = s.split("\\|");


问:
Pandas: Transform pairs of columns to cells
I have a pandas data frame like this:

```<code>ts | thing_0 | qty_0 | thing_1 | qty_1 | thing_2 | qty_2
--------------------------------------------------------
1  | dog     |     5 | cat     |     3 | mouse   |     1
2  | house   |     6 | dog     |     4 | cat     |     2
...
</code>```

I want to transform this in a way that the things become columns and the qtys become the cell values. Like this:

```<code>ts | dog | cat | mouse | house
------------------------------
1  |   5 |   3 |     1 |     0
2  |   4 |   2 |     0 |     6
...
</code>```

Currently, I'm doing this transformation manually by iterating over the df.values array manually, but this is very slow. Is there a faster way to implement this with pandas means?

I have seen df.pivot, but couldn't find a way to describe the relationship between thing_0 and qty_0.

答:
You can create MultiIndex from columns by str.split and then reshape by stack and unstack:

```<code>df = df.set_index('ts')
df.columns = df.columns.str.split('_', expand=True)
df = df.stack().reset_index(level=1, drop=True)
       .set_index('thing', append=True)['qty'].unstack(fill_value=0)
print (df)
thing  cat  dog  house  mouse
ts
1        3    5      0      1
2        2    4      6      0
</code>```

Another solution with pivot instead unstack:

```<code>df = df.set_index('ts')
df.columns = df.columns.str.split('_', expand=True)
df = df.stack().reset_index()
df = df.pivot(index='ts', columns='thing', values='qty').fillna(0).astype(int)
print (df)
thing  cat  dog  house  mouse
ts
1        3    5      0      1
2        2    4      6      0
</code>```

And third solution - dynamically create dict for lreshape and then use unstack:

Notice - columns have to be sorted, if not add df = df.sort_index(axis=1)

```<code>t = [x for x in df.columns if x.startswith('thing')]
q = [x for x in df.columns if x.startswith('qty')]
df = pd.lreshape(df, {'thing':t, 'qty':q})
       .set_index(['ts','thing'])['qty'].unstack(fill_value=0)

print (df)
thing  cat  dog  house  mouse
ts
1        3    5      0      1
2        2    4      6      0
</code>```

EDIT:

lreshape is now undocumented, but is possible in future will by removed (with pd.wide_to_long too).

Possible solution is merging all 3 functions to one - maybe melt, but now it is not implementated. Maybe in some new version of pandas. Then my answer will be updated.

Body:
I have a pandas data frame like this:

ts | thing_0 | qty_0 | thing_1 | qty_1 | thing_2 | qty_2
--------------------------------------------------------
1  | dog     |     5 | cat     |     3 | mouse   |     1
2  | house   |     6 | dog     |     4 | cat     |     2
...

I want to transform this in a way that the things become columns and the qtys become the cell values. Like this:

ts | dog | cat | mouse | house
------------------------------
1  |   5 |   3 |     1 |     0
2  |   4 |   2 |     0 |     6
...

Currently, I'm doing this transformation manually by iterating over the df.values array manually, but this is very slow. Is there a faster way to implement this with pandas means?

I have seen df.pivot, but couldn't find a way to describe the relationship between thing_0 and qty_0.

Body:
You can create MultiIndex from columns by str.split and then reshape by stack and unstack:

df = df.set_index('ts')
df.columns = df.columns.str.split('_', expand=True)
df = df.stack().reset_index(level=1, drop=True)
       .set_index('thing', append=True)['qty'].unstack(fill_value=0)
print (df)
thing  cat  dog  house  mouse
ts
1        3    5      0      1
2        2    4      6      0

Another solution with pivot instead unstack:

df = df.set_index('ts')
df.columns = df.columns.str.split('_', expand=True)
df = df.stack().reset_index()
df = df.pivot(index='ts', columns='thing', values='qty').fillna(0).astype(int)
print (df)
thing  cat  dog  house  mouse
ts
1        3    5      0      1
2        2    4      6      0

And third solution - dynamically create dict for lreshape and then use unstack:

Notice - columns have to be sorted, if not add df = df.sort_index(axis=1)

t = [x for x in df.columns if x.startswith('thing')]
q = [x for x in df.columns if x.startswith('qty')]
df = pd.lreshape(df, {'thing':t, 'qty':q})
       .set_index(['ts','thing'])['qty'].unstack(fill_value=0)

print (df)
thing  cat  dog  house  mouse
ts
1        3    5      0      1
2        2    4      6      0

EDIT:

lreshape is now undocumented, but is possible in future will by removed (with pd.wide_to_long too).

Possible solution is merging all 3 functions to one - maybe melt, but now it is not implementated. Maybe in some new version of pandas. Then my answer will be updated.


问:
error on form submit in React
I am struggling with this bug in my Meteor React app.

Long story short: I have a form to create an event, I want handleSubmit() to handle error messages and if there are none, add event to db. I do import {Events}, in fact the form worked before I made some changes. When I run it, I get an error message: Uncaught TypeError: event.target[matches] is not a function. The file that threw the error is unfortunately gibberish to me.

Here's my code:

```<code>export default class Create extends React.Component {
constructor(props) {
  super(props);
  this.state = {
      error: {}
  }

  this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(evt) {
  evt.preventDefault();

  this.setState({error: {}});
  let title = this.refs.title.value;
  if (!title) {
    this.setState((prevState) => {
      let newState = prevState;
      newState.error.title = 'Title has to be filled up.';
      return newState;
    })
  }
  let description = this.refs.description.value;
  if (!description) {
    this.setState((prevState) => {
      let newState = prevState;
      newState.error.description = 'Description has to be filled up.';
      return newState;
 })
}

if (!this.state.error) {
   Events.insert({title: title, description: description});
   this.props.history.push('/home');
}
</code>```

and my html:

```<code>    <form onSubmit={this.handleSubmit} noValidate>

        <input ref="title" type="text" name="title" placeholder="Title"
        style={this.state.error.title ? {borderBottomColor: 'red'} : undefined}/>
        <div className="errorText">{this.state.error.title}</div>

        <input ref="description" type="text" name="description" placeholder="Description"
        style={this.state.error.description ? {borderBottomColor: 'red'} : undefined}/>
        <div className="errorText">{this.state.error.description}</div>

        <button type="submit" className="btn btn-success">Create new event</button>

    </form>
</code>```

Unfortunately I can't proceed with the project until this error is resolved, so I would be really happy if someone helped me!

Best,

答:
It seems like element.matches function is not supported for your targeted element,

I am un clear whether this is caused by meteor native script, as i have not used meteor.

But, you can have a check for this by adding this code and add your own prototype to bypass this error.

```<code>if (!Element.prototype.matches) {
Element.prototype.matches =
    Element.prototype.matchesSelector ||
    Element.prototype.mozMatchesSelector ||
    Element.prototype.msMatchesSelector ||
    Element.prototype.oMatchesSelector ||
    Element.prototype.webkitMatchesSelector ||
    function(s) {
        var matches = (this.document || this.ownerDocument).querySelectorAll(s),
            i = matches.length;
        while (--i >= 0 && matches.item(i) !== this) {}
        return i > -1;
    };
}
</code>```

SOURCES

I hope this resolve your issue.

Title: error on form submit in React

Body:
I am struggling with this bug in my Meteor React app.

Long story short: I have a form to create an event, I want handleSubmit() to handle error messages and if there are none, add event to db. I do import {Events}, in fact the form worked before I made some changes. When I run it, I get an error message: Uncaught TypeError: event.target[matches] is not a function. The file that threw the error is unfortunately gibberish to me.

Here's my code:

export default class Create extends React.Component {
constructor(props) {
  super(props);
  this.state = {
      error: {}
  }

  this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(evt) {
  evt.preventDefault();

  this.setState({error: {}});
  let title = this.refs.title.value;
  if (!title) {
    this.setState((prevState) => {
      let newState = prevState;
      newState.error.title = 'Title has to be filled up.';
      return newState;
    })
  }
  let description = this.refs.description.value;
  if (!description) {
    this.setState((prevState) => {
      let newState = prevState;
      newState.error.description = 'Description has to be filled up.';
      return newState;
 })
}

if (!this.state.error) {
   Events.insert({title: title, description: description});
   this.props.history.push('/home');
}

and my html:

    <form onSubmit={this.handleSubmit} noValidate>

        <input ref="title" type="text" name="title" placeholder="Title"
        style={this.state.error.title ? {borderBottomColor: 'red'} : undefined}/>

{this.state.error.title}

        <input ref="description" type="text" name="description" placeholder="Description"
        style={this.state.error.description ? {borderBottomColor: 'red'} : undefined}/>

{this.state.error.description}

        <button type="submit" className="btn btn-success">Create new event</button>

    </form>

Unfortunately I can't proceed with the project until this error is resolved, so I would be really happy if someone helped me!

Best,

Body:
It seems like element.matches function is not supported for your targeted element,

I am un clear whether this is caused by meteor native script, as i have not used meteor.

But, you can have a check for this by adding this code and add your own prototype to bypass this error.

if (!Element.prototype.matches) {
Element.prototype.matches =
    Element.prototype.matchesSelector ||
    Element.prototype.mozMatchesSelector ||
    Element.prototype.msMatchesSelector ||
    Element.prototype.oMatchesSelector ||
    Element.prototype.webkitMatchesSelector ||
    function(s) {
        var matches = (this.document || this.ownerDocument).querySelectorAll(s),
            i = matches.length;
        while (--i >= 0 && matches.item(i) !== this) {}
        return i > -1;
    };
}

SOURCES

I hope this resolve your issue.


问:
ASP.net MVC - Get currently logged user role in view
I know that there are a lot of topics about this issue but I already tried several solutions and cannot make it work.

So, I am trying to verify the currently logged user role in my view. As referred in the major part of topics about this in StackOverflow, I just have to do:

```<code>@User.IsInRole("Admin")
</code>```

Unfortunately this always returns false even with the "Role" column, in the AspNetUsers table, of the current logged user is populated with "Admin".

I also tried below approach but it says that "UserManager does not exist in current context".

```<code><p>@UserManager.GetRoles(userId)</p>
</code>```

One of my suspects is that I am not correctly setting the role for the user upon registration. My AspNetRoles table is correctly populated but AspNetUserRoles table is empty.

How can I troubleshoot this to find what is wrong with my application so I can use @User.IsInRole(...) instruction?

Thanks in advance for any help.

答:
i think you did not write or you write but in the wrong way this below code on global.asax :</p>

```<code>    protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
    {

        if (FormsAuthentication.CookiesSupported == true)
        {
            if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                try
                {
                    //let us take out the username now
                    string Email = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                    string roles = string.Empty;

                    using (DatabaseContext entities = new DatabaseContext())
                    {
                        var user = entities.TblUsers.Where(u => u.Email == Email).FirstOrDefault().IDRole;

                        //here
                        roles = entities.TblRoles.Where(x => x.IDRole == user).FirstOrDefault().RoleName;

                    }
                    //let us extract the roles from our own custom cookie

                    // and here
                    //Let us set the Pricipal with our user specific details
                    e.User = new System.Security.Principal.GenericPrincipal(
                      new System.Security.Principal.GenericIdentity(Email, "Forms"), roles.Split(';'));

                }
                catch
                {

                    //somehting went wrong
                }
            }
        }
    }
</code>```

Body:
I know that there are a lot of topics about this issue but I already tried several solutions and cannot make it work.

So, I am trying to verify the currently logged user role in my view. As referred in the major part of topics about this in StackOverflow, I just have to do:

@User.IsInRole("Admin")

Unfortunately this always returns false even with the "Role" column, in the AspNetUsers table, of the current logged user is populated with "Admin".

I also tried below approach but it says that "UserManager does not exist in current context".

@UserManager.GetRoles(userId)

One of my suspects is that I am not correctly setting the role for the user upon registration. My AspNetRoles table is correctly populated but AspNetUserRoles table is empty.

How can I troubleshoot this to find what is wrong with my application so I can use @User.IsInRole(...) instruction?

Thanks in advance for any help.

Body:
i think you did not write or you write but in the wrong way this below code on global.asax :

    protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
    {

        if (FormsAuthentication.CookiesSupported == true)
        {
            if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                try
                {
                    //let us take out the username now
                    string Email = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                    string roles = string.Empty;

                    using (DatabaseContext entities = new DatabaseContext())
                    {
                        var user = entities.TblUsers.Where(u => u.Email == Email).FirstOrDefault().IDRole;

                        //here
                        roles = entities.TblRoles.Where(x => x.IDRole == user).FirstOrDefault().RoleName;

                    }
                    //let us extract the roles from our own custom cookie

                    // and here
                    //Let us set the Pricipal with our user specific details
                    e.User = new System.Security.Principal.GenericPrincipal(
                      new System.Security.Principal.GenericIdentity(Email, "Forms"), roles.Split(';'));

                }
                catch
                {

                    //somehting went wrong
                }
            }
        }
    }


问:
cpmplete html page reader using c#
I am new to the programming and I have one concern when I am trying to read my html page content. I am not getting complete data but when I am saving the page with right click save as option I get complete data.
NOTE:
  and inspect element also I am not able to see all data(I am able to see what I read using c#) </p>

<p>How can I read complete data using programming? Please help me to overcome this and following is my code: </p>

```<code>private void button1_Click(object sender, EventArgs e)
    {
        string urlAddress = "http://iris-rmds.tomtomgroup.com

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK)
        {
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = null;

            if (response.CharacterSet == null)
            {
                readStream = new StreamReader(receiveStream);
            }
            else
            {
                readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
            }

            string data = readStream.ReadToEnd();
            textBox1.Text  = data;
            MessageBox.Show(data.ToString());
            //var msg = "Hello world!";
            //MessageBox.Show(msg);
            Clipboard.SetText(data);
            response.Close();
            readStream.Close();

        }
    }
</code>```

答:
Maybe your page is using JavaScript that will not be loaded completely at the beginning. This type of page is like Facebook or Twitter that will dynamically loading its content. By right click and save as, the content is already exist or loaded completely.

Maybe you can save it using method in the answer of the other question: "Scraping webpage generated by javascript with C#".

Title: cpmplete html page reader using c#

Body:
I am new to the programming and I have one concern when I am trying to read my html page content. I am not getting complete data but when I am saving the page with right click save as option I get complete data.
NOTE:
  and inspect element also I am not able to see all data(I am able to see what I read using c#)

How can I read complete data using programming? Please help me to overcome this and following is my code:

private void button1_Click(object sender, EventArgs e)
    {
        string urlAddress = "http://iris-rmds.tomtomgroup.com

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK)
        {
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = null;

            if (response.CharacterSet == null)
            {
                readStream = new StreamReader(receiveStream);
            }
            else
            {
                readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
            }

            string data = readStream.ReadToEnd();
            textBox1.Text  = data;
            MessageBox.Show(data.ToString());
            //var msg = "Hello world!";
            //MessageBox.Show(msg);
            Clipboard.SetText(data);
            response.Close();
            readStream.Close();

        }
    }


问:
Get ClassTag implicitly for abstract type
I'm trying to get ClassTag implicitly. I have the following trait:

```<code>trait Tst{ self =>
  type T
  def getCls = getCls0[T] //no classtag
  private def getCls0[T](implicit ev: ClassTag[T]) = ev.runtimeClass.asInstanceOf[Class[T]]
}

class Tsss extends Tst {
  override type T = String
}
</code>```

Is there a way to get ClassTag by the type variable declaration implicitly without specifying it explicitly?

The thing is I'm trying to make the code as easy to use for clients as possible.

答:
I suggest you use abstract classes, implicit parameters and generics instead of parametric types:

```<code>abstract class Tst[T](implicit ev: ClassTag[T]) { self =>
  def getCls = getCls0[T] //no classtag
  private def getCls0[T](implicit ev: ClassTag[T]) =
    ev.runtimeClass.asInstanceOf[Class[T]]
}

class Tsss extends Tst[String]
</code>```

Note that although Dotty supports traits with parameters, it does not mix as well with generics.

Body:
I'm trying to get ClassTag implicitly. I have the following trait:

trait Tst{ self =>
  type T
  def getCls = getCls0[T] //no classtag
  private def getCls0[T](implicit ev: ClassTag[T]) = ev.runtimeClass.asInstanceOf[Class[T]]
}

class Tsss extends Tst {
  override type T = String
}

Is there a way to get ClassTag by the type variable declaration implicitly without specifying it explicitly?

The thing is I'm trying to make the code as easy to use for clients as possible.

Body:
I suggest you use abstract classes, implicit parameters and generics instead of parametric types:

abstract class Tst[T](implicit ev: ClassTag[T]) { self =>
  def getCls = getCls0[T] //no classtag
  private def getCls0[T](implicit ev: ClassTag[T]) =
    ev.runtimeClass.asInstanceOf[Class[T]]
}

class Tsss extends Tst[String]

Note that although Dotty supports traits with parameters, it does not mix as well with generics.


问:
Use msbuild to deploy BizTalk 2009 project
When I run msbuild on my BizTalk 2009 .btproj file, the default targets execute and the project is built.

Is there a target I can invoke to deploy the project?

答: There is no reason today to create your own deployment tools for BizTalk from scratch. Please take a look at the Deployment Framework for BizTalk at http://biztalkdeployment.codeplex.com. It covers simple to complex deployment scenarios, and also includes configuration management and developer productivity tools for BizTalk.</p>


问:
LocalStorage TextBox's in JSON
Weave: https://codepen.io/anon/pen/BZVdaM?editors=0010

I'm using LocalStorage to remember the states of input[type=text] elements. I was able to push to a JSON fine

```<code>{"website": "value","behance": "value","dribbble": "value"}
</code>```

However, my problem now is I'm having difficulty populating the saved data on back in the inputs for page load.

On first run the string returned shouldn't have the quote outside of it; in addition, I noticed after 2nd run it wouldn't show any of the saved data.

Here's the result from Chrome Dev Tools (this is after the 2nd run adding text to another textbox)

Thus what am I doing wrong?

var arr = localStorage.getItem("socialValues") || {};
if ( localStorage.getItem("socialValues")) {
  var savedArrData = JSON.parse(arr);
  $.each(savedArrData, function(key, value) {
    $("[data-social=links] input#" + key).val(value);
  });
}
$("[data-social=links] input").on("change keyup", function() {
  var id = this.id;
  arr[id] = (this.value ? '"' + this.value + '"' : "");
  localStorage.removeItem("socialValues");
  localStorage.setItem("socialValues", JSON.stringify(arr));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="uk-nav uk-nav-default" data-social="links">
  <li>

      <span class="uk-margin-small-right" uk-icon="icon: world"></span>
      <input id="website" class="socialbox" type="text" placeholder="http://yoursite.com/" value="hello world">

  </li>
  <li>

      <span class="uk-margin-small-right" uk-icon="icon: behance"></span>
      <input id="behance" class="socialbox" type="text" placeholder="Your behance page">

  </li>
  <li>

      <span class="uk-margin-small-right" uk-icon="icon: dribbble"></span>
      <input id="dribbble" class="socialbox" type="text" placeholder="Your dribbble page">

  </li>
</ul></code>```

答:
Few observations :

Parse the JSON string which stored in local storage while assigning it into the arr variable.

```<code>var arr = JSON.parse(localStorage.getItem("socialValues")) || {};
</code>```

Working Demo

var arr = JSON.parse(localStorage.getItem("socialValues")) || {};

if (localStorage.getItem("socialValues")) {
  var savedArrData = JSON.parse(localStorage.getItem("socialValues"));
  $.each(savedArrData, function(key, value) {
    $("#" + key).val(value);
  });
}

$("[data-social=links] input").on("change keyup", function() {
  var id = this.id;
  arr[id] = (this.value ? this.value : "");
  localStorage.removeItem("socialValues");
  localStorage.setItem("socialValues", JSON.stringify(arr));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="uk-nav uk-nav-default" data-social="links">
  <li>

      <span class="uk-margin-small-right" uk-icon="icon: world"></span>
      <input id="website" class="socialbox" type="text" value="hello world">

  </li>
  <li>

      <span class="uk-margin-small-right" uk-icon="icon: behance"></span>
      <input id="behance" class="socialbox" type="text" placeholder="Your behance page">

  </li>
  <li>

      <span class="uk-margin-small-right" uk-icon="icon: dribbble"></span>
      <input id="dribbble" class="socialbox" type="text" placeholder="Your dribbble page">

  </li>
</ul></code>```

Title: LocalStorage TextBox's in JSON

Body:
Weave: https://codepen.io/anon/pen/BZVdaM?editors=0010

I'm using LocalStorage to remember the states of input[type=text] elements. I was able to push to a JSON fine

{"website": "value","behance": "value","dribbble": "value"}

However, my problem now is I'm having difficulty populating the saved data on back in the inputs for page load.

On first run the string returned shouldn't have the quote outside of it; in addition, I noticed after 2nd run it wouldn't show any of the saved data.

Here's the result from Chrome Dev Tools (this is after the 2nd run adding text to another textbox)

Thus what am I doing wrong?

var arr = localStorage.getItem("socialValues") || {};
if ( localStorage.getItem("socialValues")) {
  var savedArrData = JSON.parse(arr);
  $.each(savedArrData, function(key, value) {
    $("[data-social=links] input#" + key).val(value);
  });
}
$("[data-social=links] input").on("change keyup", function() {
  var id = this.id;
  arr[id] = (this.value ? '"' + this.value + '"' : "");
  localStorage.removeItem("socialValues");
  localStorage.setItem("socialValues", JSON.stringify(arr));
});

      <input id="website" class="socialbox" type="text" placeholder="http://yoursite.com/" value="hello world">

      <input id="behance" class="socialbox" type="text" placeholder="Your behance page">

      <input id="dribbble" class="socialbox" type="text" placeholder="Your dribbble page">

Body:
Few observations :

Parse the JSON string which stored in local storage while assigning it into the arr variable.

var arr = JSON.parse(localStorage.getItem("socialValues")) || {};

Working Demo

var arr = JSON.parse(localStorage.getItem("socialValues")) || {};

if (localStorage.getItem("socialValues")) {
  var savedArrData = JSON.parse(localStorage.getItem("socialValues"));
  $.each(savedArrData, function(key, value) {
    $("#" + key).val(value);
  });
}

$("[data-social=links] input").on("change keyup", function() {
  var id = this.id;
  arr[id] = (this.value ? this.value : "");
  localStorage.removeItem("socialValues");
  localStorage.setItem("socialValues", JSON.stringify(arr));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="uk-nav uk-nav-default" data-social="links">
  <li>
    <a href="#">
      <span class="uk-margin-small-right" uk-icon="icon: world"></span>
      <input id="website" class="socialbox" type="text" value="hello world">
    </a>
  </li>
  <li>
    <a href="#">
      <span class="uk-margin-small-right" uk-icon="icon: behance"></span>
      <input id="behance" class="socialbox" type="text" placeholder="Your behance page">
    </a>
  </li>
  <li>
    <a href="#">
      <span class="uk-margin-small-right" uk-icon="icon: dribbble"></span>
      <input id="dribbble" class="socialbox" type="text" placeholder="Your dribbble page">
    </a>
  </li>
</ul>