问:
Google map not showing in android activity?
In my android app I want to have a MainActivity with a google map occupying the entire screen.

My problem is that the google map does not display a map, only the google logo in the bottom left corner:

Here are the relevant parts of the main activity where the map should be displayed:

```<code>public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
        NavigationView.OnNavigationItemSelectedListener {

    private GoogleMap mMap;

    private FragmentManager mFragmentManager;

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

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        setupLayout();

        mFragmentManager = getSupportFragmentManager();
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
</code>```

Here is the xml for the content of the main activity which holds the google map fragment:

```<code><fragment xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:map="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/map"
          android:name="com.google.android.gms.maps.SupportMapFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          tools:context="com.purringcat.stray.view.activity.MainActivity"/>
</code>```

Here is the manifest file:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.purringcat.stray">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:name=".Stray"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".view.activity.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".view.activity.LoginActivity"
            android:label="@string/title_activity_login"
            android:theme="@style/AppTheme.NoActionBar">
        </activity>
        <activity android:name=".view.activity.SignUpActivity">
        </activity>
        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key"/>

    </application>

</manifest>
</code>```

答:
Add this permissions to menifest

```<code><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />
</code>```

OR Check in google console is API  ENABLED

OR Check your google_api_key

Body:
In my android app I want to have a MainActivity with a google map occupying the entire screen.

My problem is that the google map does not display a map, only the google logo in the bottom left corner:

Here are the relevant parts of the main activity where the map should be displayed:

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
        NavigationView.OnNavigationItemSelectedListener {

    private GoogleMap mMap;

    private FragmentManager mFragmentManager;

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

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        setupLayout();

        mFragmentManager = getSupportFragmentManager();
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

Here is the xml for the content of the main activity which holds the google map fragment:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:map="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/map"
          android:name="com.google.android.gms.maps.SupportMapFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          tools:context="com.purringcat.stray.view.activity.MainActivity"/>

Here is the manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.purringcat.stray">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:name=".Stray"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".view.activity.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".view.activity.LoginActivity"
            android:label="@string/title_activity_login"
            android:theme="@style/AppTheme.NoActionBar">
        </activity>
        <activity android:name=".view.activity.SignUpActivity">
        </activity>

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key"/>

    </application>

</manifest>

Body:
Add this permissions to menifest

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />

OR Check in google console is API  ENABLED

OR Check your google_api_key


来源: stackexchange

问:
stripping of white spaces from a string
I have the following string

```<code>argsStr = "server ('m1.labs.terada')ta.com') username ('user5') password('user)5') dbname ('default')";
</code>```

I want to extract the argument name i.e "server" "username" "password".

I am using the following regex to do that

```<code>boost::regex re1("\\(\'[!-~]+\'\\)");
boost::sregex_token_iterator x(argsStr.begin(), argsStr.end(), re1, -1),x1;   boost::sregex_token_iterator y;
std::copy(x, x1, std::back_inserter(v2));
</code>```

v2 is string vector, where I am extracting the tokens. However, The tokens I am getting are

```<code>"server "    INSTEAD of "server
" username "  INSTEAD of "username".
</code>```

How shall I remove these white spaces?

答:
I would recommend to use boost string algorithms</p>

```<code>#include <boost/algorithm/string.hpp>

std::string str("hello world! ");
boost::trim_right(str);
</code>```

ContentLicense: CC BY-SA 3.0

Title: stripping of white spaces from a string

Body:
I have the following string

argsStr = "server ('m1.labs.terada')ta.com') username ('user5') password('user)5') dbname ('default')";

I want to extract the argument name i.e "server" "username" "password".

I am using the following regex to do that

boost::regex re1("\\(\'[!-~]+\'\\)");
boost::sregex_token_iterator x(argsStr.begin(), argsStr.end(), re1, -1),x1;   boost::sregex_token_iterator y;
std::copy(x, x1, std::back_inserter(v2));

v2 is string vector, where I am extracting the tokens. However, The tokens I am getting are

"server "    INSTEAD of "server
" username "  INSTEAD of "username".

How shall I remove these white spaces?

Body:
I would recommend to use boost string algorithms

#include <boost/algorithm/string.hpp>

std::string str("hello world! ");
boost::trim_right(str);


问:
How to validate for checkbox selection if all checkbox have same name?
Hi All
I have a group of check box having same name so as to get the array of single variable when it is posted on serverside for exampleL

```<code><input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
</code>```

I need a javascript validation to check whether any checkbox is selected or not?

Thanks and Regards

NOTE: I need javascript validation

答:
use id's

```<code><input type="checkbox" name="midlevelusers[]" id="mlu1" value="1">
<input type="checkbox" name="midlevelusers[]" id="mlu2" value="2">
<input type="checkbox" name="midlevelusers[]" id="mlu3" value="3">
<input type="checkbox" name="midlevelusers[]" id="mlu4" value="4">
</code>```

now you can do

```<code>for (var i=1;i<5;i++){
  var el = document.getElementById('mlu'+i);
  if (el.checked) { /* do something */}
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hi All
I have a group of check box having same name so as to get the array of single variable when it is posted on serverside for exampleL

<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">

I need a javascript validation to check whether any checkbox is selected or not?

Thanks and Regards

NOTE: I need javascript validation

Body:
use id's

<input type="checkbox" name="midlevelusers[]" id="mlu1" value="1">
<input type="checkbox" name="midlevelusers[]" id="mlu2" value="2">
<input type="checkbox" name="midlevelusers[]" id="mlu3" value="3">
<input type="checkbox" name="midlevelusers[]" id="mlu4" value="4">

now you can do

for (var i=1;i<5;i++){
  var el = document.getElementById('mlu'+i);
  if (el.checked) { /* do something */}
}


问:
c/c++ - How to write an array of boolean value into a text file?
I have a very big array of boolean values, and I want to write it to a .txt file.

I tried fwrite() and when I use cat command to print the output .txt file, it print some strange symbols on the screen.

I want it to show as 0 and 1. How to do that?

```<code>bool* tmp = new bool[size]; // tmp has actual values in it, this is just used to show what are tmp and size
FILE* f = fopen("result.txt", "wb");
        for (int i=0; i<size; i++) {
                fwrite(tmp, sizeof(bool), num_sample_per_point, f);
                fwrite("\n", sizeof(char), 1, f); // insert new line
        }
        fclose(f);
</code>```

Also, I've thought about converting those values to int values, but is that too costy because the size of the array is quite big.

答:
Writing the binary representation of a type T to file will not give you a human readable text file (except for the type char). Writing a bool type with value true, could produce the binary pattern 00000001 and using cat on the file will not print the letter 1.

If you want the file to contain letters with 0 for false and 1 for true, you have to convert the bool value first.

Keeping your code style, it could look like:

```<code>int main(void) {
  const int size = 3;
  bool tmp[size] = {false, true, false};
  FILE* f = fopen("result.txt", "w");
  for (int i=0; i<size; i++) {
    fwrite(tmp[i] ? "1" : "0", sizeof(char), 1, f);
    //     ^^^^^^^^^^^^^^^^^
    //     convert bool to letter
  }
  fwrite("\n", sizeof(char), 1, f); // insert new line
  fclose(f);
  return 0;
}
</code>```

Notice: If you are writing c++ you should take a look at std::ofstream

Body:
I have a very big array of boolean values, and I want to write it to a .txt file.

I tried fwrite() and when I use cat command to print the output .txt file, it print some strange symbols on the screen.

I want it to show as 0 and 1. How to do that?

bool* tmp = new bool[size]; // tmp has actual values in it, this is just used to show what are tmp and size
FILE* f = fopen("result.txt", "wb");
        for (int i=0; i<size; i++) {
                fwrite(tmp, sizeof(bool), num_sample_per_point, f);
                fwrite("\n", sizeof(char), 1, f); // insert new line
        }
        fclose(f);

Also, I've thought about converting those values to int values, but is that too costy because the size of the array is quite big.

Body:
Writing the binary representation of a type T to file will not give you a human readable text file (except for the type char). Writing a bool type with value true, could produce the binary pattern 00000001 and using cat on the file will not print the letter 1.

If you want the file to contain letters with 0 for false and 1 for true, you have to convert the bool value first.

Keeping your code style, it could look like:

int main(void) {
  const int size = 3;
  bool tmp[size] = {false, true, false};
  FILE* f = fopen("result.txt", "w");
  for (int i=0; i<size; i++) {
    fwrite(tmp[i] ? "1" : "0", sizeof(char), 1, f);
    //     ^^^^^^^^^^^^^^^^^
    //     convert bool to letter
  }
  fwrite("\n", sizeof(char), 1, f); // insert new line
  fclose(f);
  return 0;
}

Notice: If you are writing c++ you should take a look at std::ofstream


问:
How to read CSV file having empty columns in java and few columns with only some data?
I have my Test.csv file like below,Now i want to read the csv file (Using JAVA) by skipping empty columns if any.
If total column is comming as empty then i want to skip that column

```<code>111, ,John,2000,   ,US
222, ,Alle,3000,   ,China
333, ,Kite,4000,LCD,IND
444, ,King,5000,LED,Aust

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
    public class Test {
        public static void main(String[] args)
        {
            Scanner s = null;
            try {
                s = new Scanner(new File("D:/sri/Test.txt"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            while (s.hasNextLine()) {
                String line = s.nextLine();
            }
        }
    }
</code>```

Here Iam able to read empty columns also.Could you please suggest regarding this

答:
You can use a util method to check if it is empty string or not.

```<code>public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }
</code>```

and use it in your reader like below

```<code>Scanner s = null;
        try {
            s = new Scanner(new File("D:/sri/Test.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        while (s.hasNextLine()) {
            String[] line = s.nextLine().split(",");
            for (String element : line) {
                if (!isBlank(element))
                    System.out.println(element);
            }

        }
</code>```

Body:
I have my Test.csv file like below,Now i want to read the csv file (Using JAVA) by skipping empty columns if any.
If total column is comming as empty then i want to skip that column

111, ,John,2000,   ,US
222, ,Alle,3000,   ,China
333, ,Kite,4000,LCD,IND
444, ,King,5000,LED,Aust

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
    public class Test {
        public static void main(String[] args)
        {
            Scanner s = null;
            try {
                s = new Scanner(new File("D:/sri/Test.txt"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            while (s.hasNextLine()) {
                String line = s.nextLine();
            }
        }
    }

Here Iam able to read empty columns also.Could you please suggest regarding this

Body:
You can use a util method to check if it is empty string or not.

public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

and use it in your reader like below

Scanner s = null;
        try {
            s = new Scanner(new File("D:/sri/Test.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        while (s.hasNextLine()) {
            String[] line = s.nextLine().split(",");
            for (String element : line) {
                if (!isBlank(element))
                    System.out.println(element);
            }

        }


问:
Unable to attach database in Amazon RDS SQL Server
I'm trying to detach and attach a database in AWS RDS. I'm able to detach the database without any issues. But while I try to attach the database, I'm getting few errors.

When I run the attach command for the first time, I get the following error:

Unable to create database: User, group, or role 'sa' already exists in the current database.

When I execute for the second time, I get this:

Msg 1802, Level 16, State 7.

  CREATE DATABASE failed. Some file names listed could not be created. Check related errors.

Msg 5120, Level 16, State 101.

  Unable to open the physical file "D:\RDSDBDATA\DATA\DBattachTest.mdf". Operating system error 2: "2(The system cannot find the file specified.)". (Line 6)

Please advise

答:
I'm not sure what you are trying to do but you should be using backup and restore functionality to move DBs around. Attach and detach will not work as they do in a traditional SQL environment: RDS is a managed service and you have extremely limited access to the underlying OS.

From AWS docs:

Restoring a Database

To restore your database, you call the rds_restore_database stored procedure.

The following parameters are required:

@restore_db_name – The name of the database to restore.

@s3_arn_to_restore_from – The Amazon S3 bucket that contains the backup file, and the name of the file.

The following parameters are optional:

@kms_master_key_arn – If you encrypted the backup file, the key to use to decrypt the file.

Example Without Encryption

```<code>exec msdb.dbo.rds_restore_database
    @restore_db_name='database_name',
    @s3_arn_to_restore_from='arn:aws:s3:::bucket_name/file_name_and_extension';
</code>```

Example With Encryption

```<code>exec msdb.dbo.rds_restore_database
    @restore_db_name='database_name',
    @s3_arn_to_restore_from='arn:aws:s3:::bucket_name/file_name_and_extension',
    @kms_master_key_arn='arn:aws:kms:region:account-id:key/key-id';
</code>```

Body:
I'm not sure what you are trying to do but you should be using backup and restore functionality to move DBs around. Attach and detach will not work as they do in a traditional SQL environment: RDS is a managed service and you have extremely limited access to the underlying OS.

From AWS docs:

Restoring a Database

To restore your database, you call the rds_restore_database stored procedure.

The following parameters are required:

@restore_db_name – The name of the database to restore.

@s3_arn_to_restore_from – The Amazon S3 bucket that contains the backup file, and the name of the file.

The following parameters are optional:

@kms_master_key_arn – If you encrypted the backup file, the key to use to decrypt the file.

Example Without Encryption

exec msdb.dbo.rds_restore_database
    @restore_db_name='database_name',
    @s3_arn_to_restore_from='arn:aws:s3:::bucket_name/file_name_and_extension';

Example With Encryption

exec msdb.dbo.rds_restore_database
    @restore_db_name='database_name',
    @s3_arn_to_restore_from='arn:aws:s3:::bucket_name/file_name_and_extension',
    @kms_master_key_arn='arn:aws:kms:region:account-id:key/key-id';


问:
Need Help for Developing XML file based Android App with Editable Item List
I am currently working on an Android Application which shows Data from XML file and can be also edited.

This app parses XML document and displays contents of nodes in List of EditText Views, XML file contains nodes of items with child nodes as follows

Item Image Path

Item Name

Item Price

Later i want to edit this information in Android app and update XML with this newly edited data.

What I have tried :

Used RecyclerView but this doesn't allowed to get text from EditText which are invisible in view.

Also used ListView but it doesn't allowed to edit text of EditText. When tried to edit focus goes somewhere else.

(XML Parsing and writing XML part is done.)

Can anyone tell me number of possible ways to do that.(I am Rookie in Android Development).****App Screenshot****

答:
You can absolutely get the entered text in the edit text,you can use the OnFocusChangeListener to the edit text and in listview u need to add this xml attribute :

```<code>android:descendantFocusability="beforeDescendants"
</code>```

and in manifest add this:

```<code> <activity
            android:name=".youractivity"
          .....
            android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />
</code>```

Body:
You can absolutely get the entered text in the edit text,you can use the OnFocusChangeListener to the edit text and in listview u need to add this xml attribute :

android:descendantFocusability="beforeDescendants"

and in manifest add this:

 <activity
            android:name=".youractivity"
          .....
            android:windowSoftInputMode="stateAlwaysHidden|adjustPan" />


问:
Can't use debugger for xamarin android project: System.IO.FileNotFoundException: Could not load file or assembly Mono.Posix
After upgrading my visual studio 2017 to 15.2v (26430.12)

Xamarin.Android SDK 7.3.1.2 (9dbc4c5)

Can't use the debugger anymore. The project builds successfully and deployment finishes but then this error happens:

Could not load file or assembly Mono.Posix

Full error message:

答:
For me it helped to;

Disable "Use Shared Runtime" on the Android project.

Delete the App from the emulator.

Delete the Mono runtime from the emulator

Clean -> Rebuild -> Deploy without debugging and then starting a debug session

Later on I could switch "Use Shared Runtime" back on and it has been working since.


答:
This function would alert whether or not a checkbox has any values checked.

```<code>function isChecked(checkboxarray){
    for (counter = 0; counter < checkboxarray.length; counter++){
        if (checkboxarray[counter].checked){
            alert("Checkbox has at least one checked");
        else{
            alert("None checked");
        }
</code>```

You would need to add a bit more to do what you actually want to do with it but that will get you on the right track I think!

Title: How to validate for checkbox selection if all checkbox have same name?

Body:
This function would alert whether or not a checkbox has any values checked.

function isChecked(checkboxarray){
    for (counter = 0; counter < checkboxarray.length; counter++){
        if (checkboxarray[counter].checked){
            alert("Checkbox has at least one checked");
        else{
            alert("None checked");
        }

You would need to add a bit more to do what you actually want to do with it but that will get you on the right track I think!


问:
How to get content of ScrolledText?
I'm trying to get content of a ScrolledText but so far success is not with me :)
I don't understand where i'm wrong.
Here a very simple example of not working code...</p>

```<code>from Tkinter import Tk
from ScrolledText import ScrolledText

def returnPressed(value):
    print "CONTENT: " + value

root = Tk()
st = ScrolledText(root)
st.bind("<Return>", lambda event, i=st.get("1.0", "end-1c"): returnPressed(i))
st.insert("insert", "TEST")
st.pack()
root.mainloop()
</code>```

答:
Ok this is because of lambda definition.
By this way, function is created with constant "i" value, which is the value at declaration of function.

By rewording lambda as it, it works!

```<code>st.bind("<Return>", lambda event: returnPressed(st.get("1.0", "end-1c")))
</code>```

Title: How to get content of ScrolledText?

Body:
I'm trying to get content of a ScrolledText but so far success is not with me :)
I don't understand where i'm wrong.
Here a very simple example of not working code...

from Tkinter import Tk
from ScrolledText import ScrolledText

def returnPressed(value):
    print "CONTENT: " + value

root = Tk()
st = ScrolledText(root)
st.bind("<Return>", lambda event, i=st.get("1.0", "end-1c"): returnPressed(i))
st.insert("insert", "TEST")
st.pack()
root.mainloop()

Body:
Ok this is because of lambda definition.
By this way, function is created with constant "i" value, which is the value at declaration of function.

By rewording lambda as it, it works!

st.bind("<Return>", lambda event: returnPressed(st.get("1.0", "end-1c")))


问:
How to Perform/Run Coded UI Test as part of release management in VSTS 2015?
My solution got Coded UI test for my simple Project. I'm able to build and release code to azure. Now, i want to run Coded UI test run after release (include/add this Coded UI Test in release pipeline).

Thanks in advance

答:
You could use Visual Studio Test Agent Deployment and  Run Functional Tests in your release pipeline just like build definition. About how to run Code UI test in TFS, you could refer below links:

Setup for Test Servers to Run Coded UI Tests from VSO/TFS 2015

Integrate Visual Studio Coded UI Test with VSTS/TFS Build pipeline

If you are using VSTS, also need to pay attention to some tiny cathes, take a look at this blog: Run Functional (Coded) UI Tests in your VSTS Release Pipeline

Update

you need to either set WinRM to use HTTPS (rather than the default HTTP), or add the machine you're connecting from as a Trusted Host on the machine you're connecting to.


问:
allowed_host changes not effective
I've got an address say example.com and have added it to the allowed_hosts list. But when I access the site I get
 ALLOWED_HOSTS ['127.0.0.1', '::1', '178.XX.XX.XXX', 'xx80::xx81:xxx:xx3x:x12x%eth0']

in the debug error page, while the actual settings.py file reads ['178.XX.XX.XXX','example.com']. I figured the changes to settings.py aren't registered as I can remove 178.XX.XX.XXX from the list and still access the site (after clearing the browser cache) I've restarted nginx, gunicorn and the whole server to no avail. The whole thing is set up on ubuntu 16.04 running django 1.8 and using nginx and gunicorn. Any ideas where this override of allowed_hosts could be coming from?

答:
Ok this is embarassing but the One-cick install for django on 16.04 from Digital Ocean adds a line at the very end of settings.py where ALLOWED_HOSTS is redefined.

```<code># Find out what the IP addresses are at run time
# This is necessary because otherwise Gunicorn will reject the connections
def ip_addresses():
    ip_list = []
    for interface in netifaces.interfaces():
        addrs = netifaces.ifaddresses(interface)
        for x in (netifaces.AF_INET, netifaces.AF_INET6):
            if x in addrs:
                ip_list.append(addrs[x][0]['addr'])
    return ip_list

# Discover our IP address
ALLOWED_HOSTS = ip_addresses()
ALLOWED_HOSTS.append('.example.com') #I added this line
</code>```

So adding an append to the line fixes the problem.

Title: allowed_host changes not effective

Body:
Ok this is embarassing but the One-cick install for django on 16.04 from Digital Ocean adds a line at the very end of settings.py where ALLOWED_HOSTS is redefined.

# Find out what the IP addresses are at run time
# This is necessary because otherwise Gunicorn will reject the connections
def ip_addresses():
    ip_list = []
    for interface in netifaces.interfaces():
        addrs = netifaces.ifaddresses(interface)
        for x in (netifaces.AF_INET, netifaces.AF_INET6):
            if x in addrs:
                ip_list.append(addrs[x][0]['addr'])
    return ip_list

# Discover our IP address
ALLOWED_HOSTS = ip_addresses()
ALLOWED_HOSTS.append('.example.com') #I added this line

So adding an append to the line fixes the problem.


问:
Google Oauth2 redirect_uri_mismatch when send request from localhost
I use Google OAuth2 for my codeigniter application and i send request using the HybridIgniter.

REDIRECT URIS : http://localhost/college-rating-system/hauth/endpoint.

JAVASCRIPT ORIGINS : http://localhost

When send request from localhost then we get 400 error that is,

Error : redirect_uri_mismatch

Any idea ..?

答:
Redirect URIs

http://localhost:8000/      this / at end solve my problem
JavaScript origins

http://localhost:8000

NOTE: localhost and 127.0.0.1 conflicts can create problems for you sometime


问:
How to get city information in android by longitude and latitude
I am making android app now. I got some problem about getting locations.

In my code, I made my app get longitude and latitude by GPS. However, I have continued to fail to get city name by longitude and latitude. I don't know why my code goes to Exception even though there are no wrong things in my code.

Here is my code for getting city name

```<code>    ackage org.androidtown.getcurrentlocation;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class GetCurrentLocation extends AppCompatActivity implements View.OnClickListener {
    private LocationManager locationManager = null;
    private LocationListener locationListener = null;

    private Button btnGetLocation = null;
    private EditText editLocation = null;
    private ProgressBar pb = null;

    private static final String TAG = "Debug";
    private Boolean flag = false;

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

        pb = (ProgressBar) findViewById(R.id.progressBar1);
        pb.setVisibility(View.INVISIBLE);

        editLocation = (EditText) findViewById(R.id.editTextLocation);

        btnGetLocation = (Button) findViewById(R.id.btnLocation);
        btnGetLocation.setOnClickListener(this);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    public void onClick(View v) {
        flag = displayGpsStatus();
        if (flag) {
            Log.v(TAG, "onClick");

            editLocation.setText("Please!! move your device to see the changes in coordinates.\nWait..");

            pb.setVisibility(View.VISIBLE);
            locationListener = new MyLocationListener();
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {return;}

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);

            }
        else{
            alertbox("GPS Status!!", "Your GPS is : OFF");
        }
    }

    private Boolean displayGpsStatus(){
        ContentResolver contentResolver = getBaseContext().getContentResolver();
        boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
        if(gpsStatus){
            return true;
        }
    else{
            return false;
        }
    }

    protected void alertbox(String title, String mymessage){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Your Device's GPS is Disable").setCancelable(false).setTitle("**GPS Status**").setPositiveButton("Gps On", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                Intent myIntent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
                startActivity(myIntent);
                dialog.cancel();
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    private class MyLocationListener implements LocationListener{
        @Override
        public void onLocationChanged(Location loc){
            editLocation.setText("");
            pb.setVisibility(View.INVISIBLE);
            Toast.makeText(getBaseContext(), "Location changed : Lat " + loc.getLatitude() +"Lng: "+loc.getLongitude(),
                    Toast.LENGTH_SHORT).show();
            String longtitude = "Longtitude: "+loc.getLongitude();
            Log.v(TAG, longtitude);
            String latitude = "Latitude: "+loc.getLatitude();
            Log.v(TAG, latitude);

            String cityName = "default";
            Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
            // addresses
            try{
                List<Address> addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
                if(addresses.size()>0) {
                    System.out.println(addresses.get(0).getLocality());
                    cityName = addresses.get(0).getLocality();
                }
            }catch(IOException e){
                e.printStackTrace();
            }

            String s = longtitude + "\n" + latitude +
                    "\n\nMy Current City is : "+ cityName;
                    editLocation.setText(s);
        }

        @Override
        public void onProviderDisabled(String provider){

        }

        @Override
        public void onProviderEnabled(String provider){

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras){

        }

    }
}
</code>```

On the above code, this part is main code to get city name by longitude and latitude. There is no problem to get longitude and latitude. The only problem is to get city name.

```<code>String cityName = "default";
            Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
            // addresses
            try{
                List<Address> addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
                if(addresses.size()>0) {
                    System.out.println(addresses.get(0).getLocality());
                    cityName = addresses.get(0).getLocality();
                }
            }catch(IOException e){
                e.printStackTrace();
            }

            String s = longtitude + "\n" + latitude +
                    "\n\nMy Current City is : "+ cityName;
                    editLocation.setText(s);
        }
</code>```

Thank you for reading my question. Have a great day(?) midnight.

答:
```<code>First thing you shouldn't call getFromLocation from main thread as this method is synchronous and may take a long time to do its work, so you should not call it from the main, user interface (UI) thread of your app. you should use Intent service class.
Here is code for it:

public class GetAddressService extends IntentService {
    // TODO: Rename actions, choose action names that describe tasks that this
    // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
    protected ResultReceiver mReceiver;
    //protected DataEntry.AddressResultReceiver mReceiver;
    private static final String TAG = "GetAddressService";

    public GetAddressService() {
        super("GetAddressService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        mReceiver = intent.getParcelableExtra(Constants.RECEIVER);
        Log.e(TAG,"mReceiver"+mReceiver);
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = null;
                String errorMessage = "";
                // Get the location passed to this service through an extra.
                Location mCurrentLocation = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
                try {
                    addresses = geocoder.getFromLocation(mCurrentLocation.getLatitude(),
                            mCurrentLocation.getLongitude(), 1);

                } catch (IOException e) {
                    errorMessage = "Service error: ";
                    Log.e(TAG, errorMessage, e);
                } catch (IllegalArgumentException illegalArgumentException) {
                    // Catch invalid latitude or longitude values.
                    errorMessage = "invalid_lat_long_used";
                    Log.e(TAG, errorMessage + ". " +
                            "Latitude = " + mCurrentLocation.getLatitude() +
                            ", Longitude = " +
                            mCurrentLocation.getLongitude(), illegalArgumentException);
                }
                // Handle case where no address was found.
                if (addresses == null || addresses.size() == 0) {
                    if (errorMessage.isEmpty()) {
                        errorMessage = "no_address_found";
                        Log.e(TAG, errorMessage);
                    }
                    deliverResultToReceiver(Constants.FAILURE_RESULT,errorMessage);
                }else {
                    String cityName = addresses.get(0).getLocality();
                    String countryName = addresses.get(0).getCountryName();
                    String rLocation = cityName + "," + countryName;
                    Log.e(TAG, "location: " + rLocation);
                    deliverResultToReceiver(Constants.SUCCESS_RESULT,rLocation);
                }
    }

//To deliver the result back to the activity which started the service

    private void deliverResultToReceiver(int resultCode, String message) {
        //mReceiver = new ResultReceiver(this);
        Bundle bundle = new Bundle();
        bundle.putString(Constants.RESULT_DATA_KEY, message);
        mReceiver.send(resultCode, bundle);
        Log.e(TAG,"Delivering result"+message);
    }

}

//Constant class to store all constants in one place

public final class Constants {
    public static final int SUCCESS_RESULT = 0;
    public static final int FAILURE_RESULT = 1;
    public static final String PACKAGE_NAME =
            "your package name";
    public static final String RECEIVER = PACKAGE_NAME + ".RECEIVER";
    public static final String RESULT_DATA_KEY = PACKAGE_NAME +
            ".RESULT_DATA_KEY";
    public static final String LOCATION_DATA_EXTRA = PACKAGE_NAME +
            ".LOCATION_DATA_EXTRA";

}

//call this GetAddressService from your activity

private AddressResultReceiver mResultReceiver;

private class MyLocationListener implements LocationListener{
        @Override
        public void onLocationChanged(Location loc){
        Intent intent = new Intent(this,GetAddressService.class);
        intent.putExtra(Constants.RECEIVER,mResultReceiver);
        intent.putExtra(Constants.LOCATION_DATA_EXTRA,loc);
        startService(intent);
        }

//class to receive the address back from the service
 class AddressResultReceiver extends ResultReceiver{

        /**
         * Create a new ResultReceive to receive results.  Your
         * {@link #onReceiveResult} method will be called from the thread running
         * <var>handler</var> if given, or from an arbitrary thread if null.
         *
         * @param handler
         */
        public AddressResultReceiver(Handler handler) {
            super(handler);
        }

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            super.onReceiveResult(resultCode, resultData);
            mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
            Log.e(TAG,"Address is:"+mAddressOutput);
        }
    }
</code>```

Body:
I am making android app now. I got some problem about getting locations.

In my code, I made my app get longitude and latitude by GPS. However, I have continued to fail to get city name by longitude and latitude. I don't know why my code goes to Exception even though there are no wrong things in my code.

Here is my code for getting city name

    ackage org.androidtown.getcurrentlocation;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class GetCurrentLocation extends AppCompatActivity implements View.OnClickListener {
    private LocationManager locationManager = null;
    private LocationListener locationListener = null;

    private Button btnGetLocation = null;
    private EditText editLocation = null;
    private ProgressBar pb = null;

    private static final String TAG = "Debug";
    private Boolean flag = false;

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

        pb = (ProgressBar) findViewById(R.id.progressBar1);
        pb.setVisibility(View.INVISIBLE);

        editLocation = (EditText) findViewById(R.id.editTextLocation);

        btnGetLocation = (Button) findViewById(R.id.btnLocation);
        btnGetLocation.setOnClickListener(this);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    public void onClick(View v) {
        flag = displayGpsStatus();
        if (flag) {
            Log.v(TAG, "onClick");

            editLocation.setText("Please!! move your device to see the changes in coordinates.\nWait..");

            pb.setVisibility(View.VISIBLE);
            locationListener = new MyLocationListener();
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {return;}

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);

            }
        else{
            alertbox("GPS Status!!", "Your GPS is : OFF");
        }
    }

    private Boolean displayGpsStatus(){
        ContentResolver contentResolver = getBaseContext().getContentResolver();
        boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
        if(gpsStatus){
            return true;
        }
    else{
            return false;
        }
    }

    protected void alertbox(String title, String mymessage){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Your Device's GPS is Disable").setCancelable(false).setTitle("**GPS Status**").setPositiveButton("Gps On", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                Intent myIntent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
                startActivity(myIntent);
                dialog.cancel();
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    private class MyLocationListener implements LocationListener{
        @Override
        public void onLocationChanged(Location loc){
            editLocation.setText("");
            pb.setVisibility(View.INVISIBLE);
            Toast.makeText(getBaseContext(), "Location changed : Lat " + loc.getLatitude() +"Lng: "+loc.getLongitude(),
                    Toast.LENGTH_SHORT).show();
            String longtitude = "Longtitude: "+loc.getLongitude();
            Log.v(TAG, longtitude);
            String latitude = "Latitude: "+loc.getLatitude();
            Log.v(TAG, latitude);

            String cityName = "default";
            Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
            // addresses
            try{
                List<Address> addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
                if(addresses.size()>0) {
                    System.out.println(addresses.get(0).getLocality());
                    cityName = addresses.get(0).getLocality();
                }
            }catch(IOException e){
                e.printStackTrace();
            }

            String s = longtitude + "\n" + latitude +
                    "\n\nMy Current City is : "+ cityName;
                    editLocation.setText(s);
        }

        @Override
        public void onProviderDisabled(String provider){

        }

        @Override
        public void onProviderEnabled(String provider){

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras){

        }

    }
}

On the above code, this part is main code to get city name by longitude and latitude. There is no problem to get longitude and latitude. The only problem is to get city name.

String cityName = "default";
            Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
            // addresses
            try{
                List<Address> addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
                if(addresses.size()>0) {
                    System.out.println(addresses.get(0).getLocality());
                    cityName = addresses.get(0).getLocality();
                }
            }catch(IOException e){
                e.printStackTrace();
            }

            String s = longtitude + "\n" + latitude +
                    "\n\nMy Current City is : "+ cityName;
                    editLocation.setText(s);
        }

Thank you for reading my question. Have a great day(?) midnight.


问:
Angular 2 - get datas from a json file
How can I get my datas from a JSON in an angular 2 project? I tried (code below) but this doesn't work. Maybe I forgot some details... thanks a lot for an answer

Ps. I need to display on my html that "uno" included in json file.

app.component.ts:

```<code>     import { Component } from '@angular/core';
     import {Http} from '@angular/http';

    @Component({
        selector: 'app-header',
        templateUrl: '../partials/app.header.html',
        styleUrls: ['../css/partials/app.header.css']
    })
        export class AppComponent {
          title = 'app works!';
          data;
          constructor(private http:Http) {
                this.http.get('app/header.json')
               .subscribe(res => this.data = res.json());
          }
        }
</code>```

app.module.ts:

```<code>    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import { AppComponent } from './app.component';

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

app.header.html:

```<code><header>
    {{title}}//this works
    {{elemento}}//here i want to show "uno" included in json file
    ...
</header>
</code>```

header.json:

```<code>    {
        "elemento": "uno"
    }
</code>```

答:
get method should be returned so use RX js observable pattern
just like this :http://davidpine.net/blog/angular-2-http/

   import { Component } from '@angular/core';
     import {Http} from '@angular/http';
     import * from rxjs;

    @Component({
        selector: 'app-header',
        templateUrl: '../partials/app.header.html',
        styleUrls: ['../css/partials/app.header.css'],
        providers:[]
    })

  export class AppComponent {
          title = 'app works!';
          data :any;
          constructor(private http:Http) {
                this.http.get('app/header.json')
               .subscribe(res => this.data = res.json())
                .map((res: Response) => <observable[]>response.json())
                            .catch(this.handleError);
          }
        }
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
    {{title}}
    {{data?.elemento}}
</header></code>```

Title: Angular 2 - get datas from a json file

Body:
How can I get my datas from a JSON in an angular 2 project? I tried (code below) but this doesn't work. Maybe I forgot some details... thanks a lot for an answer

Ps. I need to display on my html that "uno" included in json file.

app.component.ts:

     import { Component } from '@angular/core';
     import {Http} from '@angular/http';

    @Component({
        selector: 'app-header',
        templateUrl: '../partials/app.header.html',
        styleUrls: ['../css/partials/app.header.css']
    })
        export class AppComponent {
          title = 'app works!';
          data;
          constructor(private http:Http) {
                this.http.get('app/header.json')
               .subscribe(res => this.data = res.json());
          }
        }

app.module.ts:

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import { AppComponent } from './app.component';

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

app.header.html:

    {{title}}//this works
    {{elemento}}//here i want to show "uno" included in json file
    ...

header.json:

    {
        "elemento": "uno"
    }

Body:
get method should be returned so use RX js observable pattern
just like this :http://davidpine.net/blog/angular-2-http/

   import { Component } from '@angular/core';
     import {Http} from '@angular/http';
     import * from rxjs;

    @Component({
        selector: 'app-header',
        templateUrl: '../partials/app.header.html',
        styleUrls: ['../css/partials/app.header.css'],
        providers:[]
    })

  export class AppComponent {
          title = 'app works!';
          data :any;
          constructor(private http:Http) {
                this.http.get('app/header.json')
               .subscribe(res => this.data = res.json())
                .map((res: Response) => <observable[]>response.json())
                            .catch(this.handleError);
          }
        }

<header>
    {{title}}
    {{data?.elemento}}
</header>


问:
Custom Dialog pops up unwantedly
I'm working on an Android App, recently I found out a small bug. Thing is, even If I don't call the Custom Alert Dialogbox function, The Alert Dialog is popping up unwantedly. What must be the reason ?

Providing the code I'm using:-

```<code>if (booking.isPayable()) {

                        goToActivity(PaymentActivity.class);
                        postModelSticky(booking);
                        finish();
                    }
                    getBookingConfirmation();
</code>```

If the condition is true, then go to a activity, else show the dialogBox.
getBookingConfirmation() is a function which opens the Alert
DialogBox. But Even if the condition is true, The dialog is popped up before the transition happens.

答:
```<code>if (booking.isPayable()) {
   goToActivity(PaymentActivity.class);
   postModelSticky(booking);
   finish();
}
else{
   getBookingConfirmation();
 }
</code>```

Use Else Case cause getBookingConfirmation will be called even after finish

Title: Custom Dialog pops up unwantedly

Body:
I'm working on an Android App, recently I found out a small bug. Thing is, even If I don't call the Custom Alert Dialogbox function, The Alert Dialog is popping up unwantedly. What must be the reason ?

Providing the code I'm using:-

if (booking.isPayable()) {

                        goToActivity(PaymentActivity.class);
                        postModelSticky(booking);
                        finish();
                    }
                    getBookingConfirmation();

If the condition is true, then go to a activity, else show the dialogBox.
getBookingConfirmation() is a function which opens the Alert
DialogBox. But Even if the condition is true, The dialog is popped up before the transition happens.

Body:
if (booking.isPayable()) {
   goToActivity(PaymentActivity.class);
   postModelSticky(booking);
   finish();
}
else{
   getBookingConfirmation();
 }

Use Else Case cause getBookingConfirmation will be called even after finish


问:
How can I resolve 'npm ERR! code ELIFECYCLE' in Project.js during npm start
I was following the getting started with create react native app to create my first react native application. But I am getting the following error -

```<code>npm start
</code>```

```<code>2:11:42 PM: Starting packager...

2:11:46 PM: Error starting packager:
Error: Couldn't start project. Please fix the errors and restart the
project.

at /xdl/src/Project.js:1039:11
at Generator.next (<anonymous>)
at step (/Users/xyz/my-app/node_modules/xdl/build/Project.js:1461:191)
at /Users/xyz/my-app/node_modules/xdl/build/Project.js:1461:361
at <anonymous>
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! my-app@0.1.0 start: `react-native-scripts start`
npm ERR! Exit status 1
npm ERR! Failed at the my-app@0.1.0 start script.
</code>```

The line of code this trace is referring to in the file Project.js -

```<code>function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
</code>```

As suggested here npm ERR! code ELIFECYCLE I've tried to do a npm run clean and delete node_modules and npm install. But that didn't help either.

Version details -

```<code>➜ npm -v
 5.0.1

➜ node -v
v8.0.0
</code>```

答:
The React code should be fine.

Did you maybe move your project to another folder?
Similar problem on github

Try the following:

Remove your node_modules folder in your project root rm -rf node_modules

Go to your project root and run npm install

Body:
I was following the getting started with create react native app to create my first react native application. But I am getting the following error -

npm start

2:11:42 PM: Starting packager...

2:11:46 PM: Error starting packager:
Error: Couldn't start project. Please fix the errors and restart the
project.

at /xdl/src/Project.js:1039:11
at Generator.next (<anonymous>)
at step (/Users/xyz/my-app/node_modules/xdl/build/Project.js:1461:191)
at /Users/xyz/my-app/node_modules/xdl/build/Project.js:1461:361
at <anonymous>
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! my-app@0.1.0 start: `react-native-scripts start`
npm ERR! Exit status 1
npm ERR! Failed at the my-app@0.1.0 start script.

The line of code this trace is referring to in the file Project.js -

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

As suggested here npm ERR! code ELIFECYCLE I've tried to do a npm run clean and delete node_modules and npm install. But that didn't help either.

Version details -

➜ npm -v
 5.0.1

➜ node -v
v8.0.0


答:
AlertDialoge.

So plz First You try it....
using this Solve your error

gradle Librery:

```<code>compile 'cn.pedant.sweetalert:library:1.3'
</code>```

Dialoge Example:

```<code>if (booking.isPayable()) {

                        goToActivity(PaymentActivity.class);
                        postModelSticky(booking);
                        finish();
                    }
                    getBookingConfirmation();

 new SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("Oops... No Internet Connection")
                        .setContentText("No internet connection on your device. Would you like to enable it?")
                        .setConfirmText("Enable Internet")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                Intent dialogIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                                dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(dialogIntent);
                            }
                        })
                        .setConfirmText("Cancel")
                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                finish();
                            }
                        })
                        .show();
</code>```

Title: Custom Dialog pops up unwantedly

Body:
AlertDialoge.

So plz First You try it....
using this Solve your error

gradle Librery:

compile 'cn.pedant.sweetalert:library:1.3'

Dialoge Example:

if (booking.isPayable()) {

                        goToActivity(PaymentActivity.class);
                        postModelSticky(booking);
                        finish();
                    }
                    getBookingConfirmation();

 new SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("Oops... No Internet Connection")
                        .setContentText("No internet connection on your device. Would you like to enable it?")
                        .setConfirmText("Enable Internet")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                Intent dialogIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                                dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(dialogIntent);
                            }
                        })
                        .setConfirmText("Cancel")
                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                finish();
                            }
                        })
                        .show();


问:
Between Date function MM/DD/YYYY Mysql
I'm trying to get all the records between two dates. However, I'm getting only record with 1 date only. My date structure is Varchar(20).

Here's my query:

Can you help me with this? :(

```<code>SELECT a.DOB as `DATE`,
       (CASE when f.INHOUR > 12 or f.INHour = 12 Then 'PM'
             else 'AM' END) as Shift,
       concat(b.FIRSTNAME, ' ', b.LASTNAME) Fullname,
       a.Amount as DECLARED,
       SUM(c.Amount) as CALCULATED,
       a.AMOUNT as `NET OF SPECIAL SALES`,
       d.Amount as `CASH OVER SHORT`,
       a.AMOUNT as `CASH DEPOSIT`
FROM   gndsale a
INNER  JOIN emp b
ON     a.ID= b.ID
INNER JOIN gndsale c
ON     b.ID= c.ID
INNER JOIN gndsale d
on     b.ID = d.ID
INNER JOIN adjtime f
on    a.ID= f.ID
WHERE a.type = "22"
AND   c.type = "4"
AND   d.type = "42"
and (a.DOB BETWEEN '5/1/2017' AND '5/19/2017')
GROUP BY b.ID
</code>```

答:
```<code>SELECT a.DOB as `DATE`, (CASE when f.INHOUR > 12 or f.INHour = 12 Then 'PM'
else 'AM' END) as Shift, concat(b.FIRSTNAME, ' ', b.LASTNAME) Fullname,
a.Amount as DECLARED, SUM(c.Amount) as CALCULATED, a.AMOUNT as `NET OF
SPECIAL SALES`, d.Amount as `CASH OVER SHORT`, a.AMOUNT as `CASH DEPOSIT`
FROM gndsale a INNER JOIN emp b ON a.ID= b.ID INNER JOIN gndsale c ON
b.ID= c.ID INNER JOIN gndsale d on b.ID = d.ID INNER JOIN
adjtime f on a.ID= f.ID WHERE a.type = "22" AND c.type = "4"
AND d.type = "42" and (STR_TO_DATE(a.DOB BETWEEN,'%m-%d-%Y') STR_TO_DATE('5/1/2017','%m-%d-%Y') AND '5/19/2017','%m-%d-%Y')) GROUP BY
b.ID
</code>```

Title: Between Date function MM/DD/YYYY Mysql

Body:
I'm trying to get all the records between two dates. However, I'm getting only record with 1 date only. My date structure is Varchar(20).

Here's my query:

Can you help me with this? :(

SELECT a.DOB as `DATE`,
       (CASE when f.INHOUR > 12 or f.INHour = 12 Then 'PM'
             else 'AM' END) as Shift,
       concat(b.FIRSTNAME, ' ', b.LASTNAME) Fullname,
       a.Amount as DECLARED,
       SUM(c.Amount) as CALCULATED,
       a.AMOUNT as `NET OF SPECIAL SALES`,
       d.Amount as `CASH OVER SHORT`,
       a.AMOUNT as `CASH DEPOSIT`
FROM   gndsale a
INNER  JOIN emp b
ON     a.ID= b.ID
INNER JOIN gndsale c
ON     b.ID= c.ID
INNER JOIN gndsale d
on     b.ID = d.ID
INNER JOIN adjtime f
on    a.ID= f.ID
WHERE a.type = "22"
AND   c.type = "4"
AND   d.type = "42"
and (a.DOB BETWEEN '5/1/2017' AND '5/19/2017')
GROUP BY b.ID


问:
Run script if selected value is changed
I want to run a PHP script if the value is changed in my dropdown. The PHP script should run an if else statement. Is it possible to run this script, without a form POST?

Here is my dropdown:

```<code><select id="data" name="data" class="select2_single form-control">
  <option value="1">Data 1</option>
  <option value="2">Data 2</option>
</select>
</code>```

Here is the script I want to execute:

```<code><?php
  if($_POST['data'] != '1') {
    echo  'Value 1 is selected';
  }
  if($_POST['data'] != '2') {
    echo 'Value 1 is selected';
  } else {
    echo  'No value selected';
  }
?>
</code>```

答:
Also you can do this using just plain JavaScript:

var dataEl = document.querySelector('#data'),
    outputEl = document.querySelector('#output');

dataEl.onchange = function() {
  outputEl.innerText = dataEl.value
    ? 'Value ' + dataEl.value + ' is selected'
    : 'No value selected';
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="data" name="data" class="select2_single form-control">
  <option value="">Select...</option>
  <option value="1">Data 1</option>
  <option value="2">Data 2</option>
</select>

<p id="output"></p></code>```

Title: Run script if selected value is changed

Body:
I want to run a PHP script if the value is changed in my dropdown. The PHP script should run an if else statement. Is it possible to run this script, without a form POST?

Here is my dropdown:

<select id="data" name="data" class="select2_single form-control">
  <option value="1">Data 1</option>
  <option value="2">Data 2</option>
</select>

Here is the script I want to execute:

<?php
  if($_POST['data'] != '1') {
    echo  'Value 1 is selected';
  }
  if($_POST['data'] != '2') {
    echo 'Value 1 is selected';
  } else {
    echo  'No value selected';
  }
?>

Body:
Also you can do this using just plain JavaScript:

var dataEl = document.querySelector('#data'),
    outputEl = document.querySelector('#output');

dataEl.onchange = function() {
  outputEl.innerText = dataEl.value
    ? 'Value ' + dataEl.value + ' is selected'
    : 'No value selected';
};

<select id="data" name="data" class="select2_single form-control">
  <option value="">Select...</option>
  <option value="1">Data 1</option>
  <option value="2">Data 2</option>
</select>

<p id="output"></p>


问:
TypeError: integer argument expected, got float python 2.7
I am using the following code to detecion pattern. Why does it throw a TypeError?

```<code># loop over the contours
</code>```

for c in cnts:

```<code># compute the center of the contour
M = cv2.moments(c)

    cX = (M["m10"] / (M["m00"] + 1e-7))
cY = (M["m01"] / (M["m00"] + 1e-7))

# draw the contour and center of the shape on the image
cv2.drawContours(frame1, [c], -1, (0, 255, 0), 2)
cv2.circle(frame1, (cX, cY), 7, (255, 255, 255), -1)
cv2.putText(frame1, "center", (cX - 20, cY - 20),
    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
</code>```

This massage error

```<code>    cv2.circle(frame1, (cX, cY), 7, (255, 255, 255), -1)
</code>```

TypeError: integer argument expected, got float

答:
(cX, cY) is an OpenCV point. It represents x-y coordinates, in other words a pixel position. If the function you are calling says it expects an integer there, then it expects an integer. Whatever you think it should expect.

cv2.moments() returns a dictionary of 10 floats. If you want to use the values that it returns as coordinate points then you will need to convert them to integers somehow.

Body:
I am using the following code to detecion pattern. Why does it throw a TypeError?

# loop over the contours

for c in cnts:

# compute the center of the contour
M = cv2.moments(c)

    cX = (M["m10"] / (M["m00"] + 1e-7))
cY = (M["m01"] / (M["m00"] + 1e-7))

# draw the contour and center of the shape on the image
cv2.drawContours(frame1, [c], -1, (0, 255, 0), 2)
cv2.circle(frame1, (cX, cY), 7, (255, 255, 255), -1)
cv2.putText(frame1, "center", (cX - 20, cY - 20),
    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)

This massage error

    cv2.circle(frame1, (cX, cY), 7, (255, 255, 255), -1)

TypeError: integer argument expected, got float


问:
How can I create a RegEx for Strings with Tabulator?
I have an input string/text like this:

```<code>    <span id="salutation">

            Mister

</span><div class="c"></div>
</code>```

With which pattern can I get the string Mister?

This pattern:

```<code>string pattern = "<span id=\"salutation\"> (.*) </span>";
</code>```

have no success for me.

答:
The correct regex is:

```<code><span id="salutation">\s*(.*?)\s*</span>
</code>```

which leaves out all the spaces (\s) around "Mister".

But, as in some other language, you have to double escape because of the slash:

```<code>"<span id=\"salutation\">\\s*(.*?)\\s*</span>"
</code>```

In C# you can even use this trick:

```<code>@"<span id=""salutation"">\s*(.*?)\s*</span>"
</code>```

Anyway, regex are not the best tool for this. Try to use an HTML parser (see What is the best way to parse html in C#? [closed]).

Body:
I have an input string/text like this:

            Mister

With which pattern can I get the string Mister?

This pattern:

string pattern = " (.*) ";

have no success for me.

Body:
The correct regex is:

<span id="salutation">\s*(.*?)\s*</span>

which leaves out all the spaces (\s) around "Mister".

But, as in some other language, you have to double escape because of the slash:

"<span id=\"salutation\">\\s*(.*?)\\s*</span>"

In C# you can even use this trick:

@"<span id=""salutation"">\s*(.*?)\s*</span>"

Anyway, regex are not the best tool for this. Try to use an HTML parser (see What is the best way to parse html in C#? [closed]).


问:
Javascript for loop not repeating strings
very new to Javascript here, and I think I'm having a logic issue. So basically for class I'm building a hangman game, and I am having trouble with double letters. for instance if the word is food, when I enter an "O" it will pass through the for loop, hit that first O, push it to the screen, and stop dead in its tracks. I can do whatever I want to that first "O" but a second one or any other repeated letter gets ignored. Now the alert I wrote directly under the start of the for() loop, will successfully print both "O's", as will logging it to the console, or even flat out writing document.write(splitWord[m]);

So to me, I think it has to be my if statement. I could be 100% wrong on this, but I assume that the if statement tells it to see the first "O", do what's in the bracket, and then move on to the next letter skipping any doubles. If I am right about this, what would be a better option to keep the loop going, so both "O's" would be filled. And if I am completely wrong, what would be a better course of action to accomplish this task. Any help would be very greatly appreciated.

Thanks

var remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];

var removedLetters =[];
var wordList = ["django", "the#good#the#bad#and#the#ugly", "a#fistful#of#dollars","for#a#few#dollars#more","once#upon#a#time#in#the#west","the#wild#bunch","pale#rider"];
var titleList =["django", "The Good The Bad And The Ugly", "A Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"];
var songList =["Jango", "The Good The Bad And The Ugly", "Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"]

var selectedWord;
console.log(selectedWord);

var livesRemaining = 12;
var score = 0;
var wordWorth = 0;
var wins = 0;
var losses = 0;
var gameOn = false;

function chooseAWord(){
 selectedWord = wordList[Math.floor(Math.random() * wordList.length)];
 console.log(selectedWord);
}

function printWord(){
  document.getElementById("wordDisplayer").innerHTML = selectedWord;
}

function buildTiles(){
  // create a new div element
  // and give it some content
  var splitWord = selectedWord.split("");
  for(i = 0; i < splitWord.length; i++){
   if (splitWord[i] != '#'){
     // var newTile = document.createElement("div");
    //var newContent = document.createTextNode("");
      //newTile.appendChild(newContent); //add the text node to the newly created div.

  document.getElementById("wordTiles").innerHTML += '

';

   wordWorth++;

    // add the newly created element and its content into the DOM
    //var currentDiv = document.getElementById("wordTiles");
     //currentDiv.appendChild(newTile, currentDiv);

    // newTile.setAttribute("class", "tileStyle");
     }else if(splitWord[i] == '#'){
      var blankTile = document.createElement("div");
      var spaceContent = document.createTextNode("");
      blankTile.appendChild(spaceContent);

      document.getElementById("wordTiles").innerHTML += '

';
     }
    }
}

function clearTiles(){
 var myNode = document.getElementById("wordTiles");
 while (myNode.firstChild) {
     myNode.removeChild(myNode.firstChild);
 }

}

function refreshAlphabet(){
 remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
 displayAvailableLetters();
}

function keyPressed(){
 checkPlayerChoiceNew();
}

var playerGuess = document.onkeyup = function myKeyDown(event){
 playerGuess = event.key;
 if(gameOn==true){
  keyPressed();
 }else{

 }
}

function checkPlayerGuess(){
 document.getElementById("isThisWorking").innerHTML = playerGuess;

}

// function myFunction() {
//    var str = "Tha bast things in lifa ara free";
//    var patt = new RegExp(playerGuess);
 //   var res = patt.test(selectedWord.toLowerCase());
//    document.getElementById("demo").innerHTML = res;
//}

function displayAvailableLetters(){
 document.getElementById("lettersStillAvailable").innerHTML = remainingLetters;
 console.log(remainingLetters);

}

function displayRemovedLetters(){
 document.getElementById("lettersUsed").innerHTML = removedLetters;
}

function updateScore(){
 document.getElementById("scoreTotal").innerHTML = score;
}

function updateWins(){
 document.getElementById("winTotals").innerHTML = wins;
}
function updateLosses(){
 document.getElementById("lossTotals").innerHTML = losses;
}

function checkScore(){
 if(score == selectedWord.length && livesRemaining > 0){
  document.getElementById("gameOver").innerHTML = "WINNER! Congratulations!!!";
  wins++;
  updateWins();
  gameOn=false;
 }else if (livesRemaining == 0){
  livesRemaining == -1;
  document.getElementById("gameOver").innerHTML = "You have failed!";
  losses++;
  updateLosses();
  gameOn=false;
 }else{
  document.getElementById("gameOver").innerHTML = "Good Luck!";
 }
}

function checkPlayerChoiceNew(){
 var splitWord = selectedWord.split("");
 var choice = new RegExp(playerGuess);
 var compareWord = choice.test(selectedWord.toLowerCase());
 var compareAlphabet = choice.test(remainingLetters);
 var compareRemovedList = choice.test(removedLetters);

 for (m = 0; m < splitWord.length; m++){
  //alert(splitWord[m]);
  if(playerGuess == splitWord[m]){
   document.getElementById(splitWord[m]).innerHTML = playerGuess;

  }
 }
}
//check playerGuess against selectedWord
function checkPlayerChoice(){
 var choice = new RegExp(playerGuess);
 var compareWord = choice.test(selectedWord.toLowerCase());
 var compareAlphabet = choice.test(remainingLetters);
 var compareRemovedList = choice.test(removedLetters);

 if(compareWord == true && compareAlphabet == true ){
  document.getElementById("demo").innerHTML = playerGuess;

  remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
  displayAvailableLetters();
  displayRemovedLetters();
  score++;
  updateScore();
  checkScore();
 }else if(compareWord == true && compareAlphabet == false){
  document.getElementById("demo").innerHTML = "Already tried that one";
 }else if(compareWord == false && compareAlphabet == true){
  livesRemaining--;
  document.getElementById("lives").innerHTML = livesRemaining;
  removedLetters.push(playerGuess.toLowerCase());
  remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
  updateScore();
  checkScore();
  displayAvailableLetters();
  displayRemovedLetters();
 }else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){
  document.getElementById("demo").innerHTML = "Already tried that one ;)";
 }else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){

 }else{
  /*livesRemaining--;
  document.getElementById("lives").innerHTML = livesRemaining;
  removedLetters.push(playerGuess.toLowerCase());
  updateScore();
  checkScore();
  displayAvailableLetters();
  displayRemovedLetters();*/
  document.getElementById("demo").innerHTML = "Not a Valid Key";
 }
}

//document.onkeyup = function myKeyDown(event){
// playerGuess = event.key;

//}

//start / Restart the game
function resetGame() {
 livesRemaining = 12;
 score =0;
 wordWorth = 0;
 clearTiles();
 document.getElementById("lives").innerHTML = livesRemaining;
 chooseAWord();
 printWord();
 buildTiles();
 refreshAlphabet();
 gameOn=true;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tileStyle{
 width:30px;
 height:30px;
 border:1px solid black;
 background-color:green;
 float:left;
 margin-left:10px;
 margin-right:10px;
 margin-bottom:10px;
 margin-top:10px;
}
.blankStyle{
 width:30px;
 height:30px;
 background-color:orange;
 float:left;
 margin-left:10px;
 margin-right:10px;
 margin-bottom:10px;
 margin-top:10px;
}
.fixer{
 width:100%;
 height:10px;
 clear:both;
}</code>```

<button onclick="checkPlayerChoice()">Try it</button>

 lives:

 0

 Score:

0

wins

0

losses

0

<button onclick ="resetGame()">New Game</button>

Here is the word

Press New Game to Start

<button onclick ="checkPlayerGuess()">What Key was Pressed?</button>

What will I say?

Letters Still Available

Bad Guesses

```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>selectedWord ="food";
function checkPlayerChoiceNew(){
 var splitWord = selectedWord.split("");
 var choice = new RegExp(playerGuess);
 var compareWord = choice.test(selectedWord.toLowerCase());
 var compareAlphabet = choice.test(remainingLetters);
 var compareRemovedList = choice.test(removedLetters);

 for (m = 0; m < splitWord.length; m++){
  //alert(splitWord[m]);
  if(playerGuess == splitWord[m]){
   document.getElementById(splitWord[m]).innerHTML = choice;

  }
 }
}</code>```

答:
You can refer this below logic. In this example, I have given some inputs.

var selectedWord ="food";
var displayString = [];
for(var i = 0; i < selectedWord.length; i++){
  displayString[i] = "-"
}
var outputEle = document.getElementById("output");
var div = document.createElement('div');
div.innerText = displayString.join(" ");
outputEle.appendChild(div);
function checkPlayerChoiceNew(playerGuess){
  var newWord = "";
  var regExp = new RegExp(playerGuess,'ig')
 selectedWord.replace(regExp, function(value, index){
    displayString[index] = value;
    return value;
  });
  var div = document.createElement('div');
  div.innerText = displayString.join(" ");
  outputEle.appendChild(div);
  newWord = displayString.join("");
  if(selectedWord == newWord){ alert("You Won the game"); }
  //outputEle.innerText = displayString.join(" ");
}
checkPlayerChoiceNew('o');
checkPlayerChoiceNew('g');
checkPlayerChoiceNew('d');
checkPlayerChoiceNew('f');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="output">

</div></code>```

Body:
very new to Javascript here, and I think I'm having a logic issue. So basically for class I'm building a hangman game, and I am having trouble with double letters. for instance if the word is food, when I enter an "O" it will pass through the for loop, hit that first O, push it to the screen, and stop dead in its tracks. I can do whatever I want to that first "O" but a second one or any other repeated letter gets ignored. Now the alert I wrote directly under the start of the for() loop, will successfully print both "O's", as will logging it to the console, or even flat out writing document.write(splitWord[m]);

So to me, I think it has to be my if statement. I could be 100% wrong on this, but I assume that the if statement tells it to see the first "O", do what's in the bracket, and then move on to the next letter skipping any doubles. If I am right about this, what would be a better option to keep the loop going, so both "O's" would be filled. And if I am completely wrong, what would be a better course of action to accomplish this task. Any help would be very greatly appreciated.

Thanks

var remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];

var removedLetters =[];
var wordList = ["django", "the#good#the#bad#and#the#ugly", "a#fistful#of#dollars","for#a#few#dollars#more","once#upon#a#time#in#the#west","the#wild#bunch","pale#rider"];
var titleList =["django", "The Good The Bad And The Ugly", "A Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"];
var songList =["Jango", "The Good The Bad And The Ugly", "Fistful of Dollars", "For a few Dollars More", "Once Upon a Time in the West", "The Wild Bunch", "Pale Rider"]

var selectedWord;
console.log(selectedWord);

var livesRemaining = 12;
var score = 0;
var wordWorth = 0;
var wins = 0;
var losses = 0;
var gameOn = false;

function chooseAWord(){
 selectedWord = wordList[Math.floor(Math.random() * wordList.length)];
 console.log(selectedWord);
}

function printWord(){
  document.getElementById("wordDisplayer").innerHTML = selectedWord;
}

function buildTiles(){
  // create a new div element
  // and give it some content
  var splitWord = selectedWord.split("");
  for(i = 0; i < splitWord.length; i++){
   if (splitWord[i] != '#'){
     // var newTile = document.createElement("div");
    //var newContent = document.createTextNode("");
      //newTile.appendChild(newContent); //add the text node to the newly created div.

  document.getElementById("wordTiles").innerHTML += '

';

   wordWorth++;

    // add the newly created element and its content into the DOM
    //var currentDiv = document.getElementById("wordTiles");
     //currentDiv.appendChild(newTile, currentDiv);

    // newTile.setAttribute("class", "tileStyle");
     }else if(splitWord[i] == '#'){
      var blankTile = document.createElement("div");
      var spaceContent = document.createTextNode("");
      blankTile.appendChild(spaceContent);

      document.getElementById("wordTiles").innerHTML += '

';
     }
    }
}

function clearTiles(){
 var myNode = document.getElementById("wordTiles");
 while (myNode.firstChild) {
     myNode.removeChild(myNode.firstChild);
 }

}

function refreshAlphabet(){
 remainingLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
 displayAvailableLetters();
}

function keyPressed(){
 checkPlayerChoiceNew();
}

var playerGuess = document.onkeyup = function myKeyDown(event){
 playerGuess = event.key;
 if(gameOn==true){
  keyPressed();
 }else{

 }
}

function checkPlayerGuess(){
 document.getElementById("isThisWorking").innerHTML = playerGuess;

}

// function myFunction() {
//    var str = "Tha bast things in lifa ara free";
//    var patt = new RegExp(playerGuess);
 //   var res = patt.test(selectedWord.toLowerCase());
//    document.getElementById("demo").innerHTML = res;
//}

function displayAvailableLetters(){
 document.getElementById("lettersStillAvailable").innerHTML = remainingLetters;
 console.log(remainingLetters);

}

function displayRemovedLetters(){
 document.getElementById("lettersUsed").innerHTML = removedLetters;
}

function updateScore(){
 document.getElementById("scoreTotal").innerHTML = score;
}

function updateWins(){
 document.getElementById("winTotals").innerHTML = wins;
}
function updateLosses(){
 document.getElementById("lossTotals").innerHTML = losses;
}

function checkScore(){
 if(score == selectedWord.length && livesRemaining > 0){
  document.getElementById("gameOver").innerHTML = "WINNER! Congratulations!!!";
  wins++;
  updateWins();
  gameOn=false;
 }else if (livesRemaining == 0){
  livesRemaining == -1;
  document.getElementById("gameOver").innerHTML = "You have failed!";
  losses++;
  updateLosses();
  gameOn=false;
 }else{
  document.getElementById("gameOver").innerHTML = "Good Luck!";
 }
}

function checkPlayerChoiceNew(){
 var splitWord = selectedWord.split("");
 var choice = new RegExp(playerGuess);
 var compareWord = choice.test(selectedWord.toLowerCase());
 var compareAlphabet = choice.test(remainingLetters);
 var compareRemovedList = choice.test(removedLetters);

 for (m = 0; m < splitWord.length; m++){
  //alert(splitWord[m]);
  if(playerGuess == splitWord[m]){
   document.getElementById(splitWord[m]).innerHTML = playerGuess;

  }
 }
}
//check playerGuess against selectedWord
function checkPlayerChoice(){
 var choice = new RegExp(playerGuess);
 var compareWord = choice.test(selectedWord.toLowerCase());
 var compareAlphabet = choice.test(remainingLetters);
 var compareRemovedList = choice.test(removedLetters);

 if(compareWord == true && compareAlphabet == true ){
  document.getElementById("demo").innerHTML = playerGuess;

  remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
  displayAvailableLetters();
  displayRemovedLetters();
  score++;
  updateScore();
  checkScore();
 }else if(compareWord == true && compareAlphabet == false){
  document.getElementById("demo").innerHTML = "Already tried that one";
 }else if(compareWord == false && compareAlphabet == true){
  livesRemaining--;
  document.getElementById("lives").innerHTML = livesRemaining;
  removedLetters.push(playerGuess.toLowerCase());
  remainingLetters.splice(remainingLetters.indexOf(playerGuess),1);
  updateScore();
  checkScore();
  displayAvailableLetters();
  displayRemovedLetters();
 }else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){
  document.getElementById("demo").innerHTML = "Already tried that one ;)";
 }else if (compareWord == false && compareAlphabet == false && compareRemovedList == true){

 }else{
  /*livesRemaining--;
  document.getElementById("lives").innerHTML = livesRemaining;
  removedLetters.push(playerGuess.toLowerCase());
  updateScore();
  checkScore();
  displayAvailableLetters();
  displayRemovedLetters();*/
  document.getElementById("demo").innerHTML = "Not a Valid Key";
 }
}

//document.onkeyup = function myKeyDown(event){
// playerGuess = event.key;

//}

//start / Restart the game
function resetGame() {
 livesRemaining = 12;
 score =0;
 wordWorth = 0;
 clearTiles();
 document.getElementById("lives").innerHTML = livesRemaining;
 chooseAWord();
 printWord();
 buildTiles();
 refreshAlphabet();
 gameOn=true;
}

.tileStyle{
 width:30px;
 height:30px;
 border:1px solid black;
 background-color:green;
 float:left;
 margin-left:10px;
 margin-right:10px;
 margin-bottom:10px;
 margin-top:10px;
}
.blankStyle{
 width:30px;
 height:30px;
 background-color:orange;
 float:left;
 margin-left:10px;
 margin-right:10px;
 margin-bottom:10px;
 margin-top:10px;
}
.fixer{
 width:100%;
 height:10px;
 clear:both;
}

<button onclick="checkPlayerChoice()">Try it</button>

 lives:

 0

 Score:

0

wins

0

losses

0

<button onclick ="resetGame()">New Game</button>

Here is the word

Press New Game to Start

<button onclick ="checkPlayerGuess()">What Key was Pressed?</button>

What will I say?

Letters Still Available

Bad Guesses

selectedWord ="food";
function checkPlayerChoiceNew(){
 var splitWord = selectedWord.split("");
 var choice = new RegExp(playerGuess);
 var compareWord = choice.test(selectedWord.toLowerCase());
 var compareAlphabet = choice.test(remainingLetters);
 var compareRemovedList = choice.test(removedLetters);

 for (m = 0; m < splitWord.length; m++){
  //alert(splitWord[m]);
  if(playerGuess == splitWord[m]){
   document.getElementById(splitWord[m]).innerHTML = choice;

  }
 }
}

Body:
You can refer this below logic. In this example, I have given some inputs.

var selectedWord ="food";
var displayString = [];
for(var i = 0; i < selectedWord.length; i++){
  displayString[i] = "-"
}
var outputEle = document.getElementById("output");
var div = document.createElement('div');
div.innerText = displayString.join(" ");
outputEle.appendChild(div);
function checkPlayerChoiceNew(playerGuess){
  var newWord = "";
  var regExp = new RegExp(playerGuess,'ig')
 selectedWord.replace(regExp, function(value, index){
    displayString[index] = value;
    return value;
  });
  var div = document.createElement('div');
  div.innerText = displayString.join(" ");
  outputEle.appendChild(div);
  newWord = displayString.join("");
  if(selectedWord == newWord){ alert("You Won the game"); }
  //outputEle.innerText = displayString.join(" ");
}
checkPlayerChoiceNew('o');
checkPlayerChoiceNew('g');
checkPlayerChoiceNew('d');
checkPlayerChoiceNew('f');

<div id="output">

</div>


答:
PLEASE TRY:::

```<code>SELECT a.DOB as `DATE`,
   (CASE when f.INHOUR > 12 or f.INHour = 12 Then 'PM'
         else 'AM' END) as Shift,
   concat(b.FIRSTNAME, ' ', b.LASTNAME) Fullname,
   a.Amount as DECLARED,
   SUM(c.Amount) as CALCULATED,
   a.AMOUNT as `NET OF SPECIAL SALES`,
   d.Amount as `CASH OVER SHORT`,
   a.AMOUNT as `CASH DEPOSIT`
FROM   gndsale a
INNER  JOIN emp b
ON     a.ID= b.ID
INNER JOIN gndsale c
ON     b.ID= c.ID
INNER JOIN gndsale d
on     b.ID = d.ID
INNER JOIN adjtime f
on    a.ID= f.ID
WHERE a.type = "22"
AND   c.type = "4"
AND   d.type = "42"
AND (a.DOB BETWEEN CAST('5/1/2017') as date) AND CAST('5/19/2017' as date) )
GROUP BY b.ID
</code>```

THE BETWEEN CLAUSE CANNOT BE USED WITH DATES IN THE FORM OF CHARACTER STRING.
(IT CAN BE, BUT THAT WOULD NOT BE LOGICAL)

CHEERS

Title: Between Date function MM/DD/YYYY Mysql

Body:
PLEASE TRY:::

SELECT a.DOB as `DATE`,
   (CASE when f.INHOUR > 12 or f.INHour = 12 Then 'PM'
         else 'AM' END) as Shift,
   concat(b.FIRSTNAME, ' ', b.LASTNAME) Fullname,
   a.Amount as DECLARED,
   SUM(c.Amount) as CALCULATED,
   a.AMOUNT as `NET OF SPECIAL SALES`,
   d.Amount as `CASH OVER SHORT`,
   a.AMOUNT as `CASH DEPOSIT`
FROM   gndsale a
INNER  JOIN emp b
ON     a.ID= b.ID
INNER JOIN gndsale c
ON     b.ID= c.ID
INNER JOIN gndsale d
on     b.ID = d.ID
INNER JOIN adjtime f
on    a.ID= f.ID
WHERE a.type = "22"
AND   c.type = "4"
AND   d.type = "42"
AND (a.DOB BETWEEN CAST('5/1/2017') as date) AND CAST('5/19/2017' as date) )
GROUP BY b.ID

THE BETWEEN CLAUSE CANNOT BE USED WITH DATES IN THE FORM OF CHARACTER STRING.
(IT CAN BE, BUT THAT WOULD NOT BE LOGICAL)

CHEERS


问:
What's the best way to synchronize XmlWriter access to a file to prevent IOExceptions?
There are multiple places in an application which call XmlWriter.Create on the same file, all accessed through the following function. When one calls while another is still writing, I get an IOException. What's the best way to lock or synchronize access?

Here's the function that's being used:

```<code>        public void SaveToDisk()
    {
        try
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            using (XmlWriter writer = XmlWriter.Create(SaveFileAbsolutePath, settings))
            {
                XamlWriter.Save(this, writer);
                writer.Close();
            }

        }
        catch (Exception ex)
        {
            // Log the error
            System.Diagnostics.Debug.WriteLine(ex.Message);

            // Rethrow so we know about the error
            throw;
        }
    }
</code>```

UPDATE: It looks like the problem isn't just from calls to this function, but because another thread is reading the file while this function is writing to is. What's the best way to lock so we don't try to write to the file while it's being read?

答:
Using a lock can solve your concurrency problem and thus avoid the IOException, but you must remember to use the same object either on SaveToDisk and ReadFromDisk (i assume this is the reading function), otherwise it's totally useless to lock only when you read.</p>

```<code>private static readonly object syncLock = new object();

public void SaveToDisk()
{
     lock(syncLock)
     {
          ... write code ...
     }
}

public void ReadFromDisk()
{
     lock(syncLock)
     {
          ... read code ...
     }
}
</code>```

OwnerDisplayName: Jon Galloway

Body:
There are multiple places in an application which call XmlWriter.Create on the same file, all accessed through the following function. When one calls while another is still writing, I get an IOException. What's the best way to lock or synchronize access?

Here's the function that's being used:

        public void SaveToDisk()
    {
        try
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            using (XmlWriter writer = XmlWriter.Create(SaveFileAbsolutePath, settings))
            {
                XamlWriter.Save(this, writer);
                writer.Close();
            }

        }
        catch (Exception ex)
        {
            // Log the error
            System.Diagnostics.Debug.WriteLine(ex.Message);

            // Rethrow so we know about the error
            throw;
        }
    }

UPDATE: It looks like the problem isn't just from calls to this function, but because another thread is reading the file while this function is writing to is. What's the best way to lock so we don't try to write to the file while it's being read?

LastEditorDisplayName: Jon Galloway

Body:
Using a lock can solve your concurrency problem and thus avoid the IOException, but you must remember to use the same object either on SaveToDisk and ReadFromDisk (i assume this is the reading function), otherwise it's totally useless to lock only when you read.

private static readonly object syncLock = new object();

public void SaveToDisk()
{
     lock(syncLock)
     {
          ... write code ...
     }
}

public void ReadFromDisk()
{
     lock(syncLock)
     {
          ... read code ...
     }
}


问:
How to validate for checkbox selection if all checkbox have same name?
Hi All
I have a group of check box having same name so as to get the array of single variable when it is posted on serverside for exampleL

```<code><input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
</code>```

I need a javascript validation to check whether any checkbox is selected or not?

Thanks and Regards

NOTE: I need javascript validation

答:
try,   </p>

```<code>function validate() {
    var chk = document.getElementsByName('midlevelusers[]')
    var len = chk.length

    for(i=0;i<len;i++)
    {
         if(chk[i].checked){
        return true;
          }
    }
    return false;
    }
</code>```

Body:
Hi All
I have a group of check box having same name so as to get the array of single variable when it is posted on serverside for exampleL

<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">

I need a javascript validation to check whether any checkbox is selected or not?

Thanks and Regards

NOTE: I need javascript validation

Body:
try,

function validate() {
    var chk = document.getElementsByName('midlevelusers[]')
    var len = chk.length

    for(i=0;i<len;i++)
    {
         if(chk[i].checked){
        return true;
          }
    }
    return false;
    }