问:
Android: Listview select items
Using android studio and I have a large product list for a grocery store and want to be able to select items from that list. I then want the selected items to appear in another listview such as a users shopping cart.

#Updated
I have now created a checkable list view. How can I take the checked boxes and add them to another activity/listview that I have created.

```<code>enter code here import android.os.Bundle;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ListView;
import android.view.View;

public class MainActivity extends AppCompatActivity{
ArrayList<String> selectedItems=new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView chl=(ListView)findViewById(R.id.checkable_list);
    chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    String[] items={"Bacon","Sports Drinks","Detergent","Towels","Frozen
  Pizza","Water"};
    ArrayAdapter<String> adapter=new ArrayAdapter<String>
 (this,R.layout.rowlayout,R.id.txt_title,items);
    chl.setAdapter(adapter);
    chl.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String selectedItem=((TextView)view).getText().toString();
            if (selectedItem.contains(selectedItem)) {
                selectedItems.remove(selectedItem);
            }
                else
                    selectedItems.add(selectedItem);

            }
        });

}

public void showSelectedItems(View view){
    String items="";
    for (String item:selectedItems){
        items+="-"+item+"\n";
    }
    Toast.makeText(getApplicationContext(),"Added To Your Cart",Toast.LENGTH_SHORT).show();}}
</code>```

答:
Please give me MORE information for your Question.

First of all

You have to make a custom listview that call mOneListView and set method OnItemClickListener to mOneListView's ListViewAdapter.
and make another mTwoListView be called by mOneListView's Item.

I think your problem is do not know how to make a custom listview and make a listener for Item of List.
CHECK IT OUT.

Title: Android: Listview select items

Body:
Using android studio and I have a large product list for a grocery store and want to be able to select items from that list. I then want the selected items to appear in another listview such as a users shopping cart.

#Updated
I have now created a checkable list view. How can I take the checked boxes and add them to another activity/listview that I have created.

enter code here import android.os.Bundle;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ListView;
import android.view.View;

public class MainActivity extends AppCompatActivity{
ArrayList<String> selectedItems=new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView chl=(ListView)findViewById(R.id.checkable_list);
    chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    String[] items={"Bacon","Sports Drinks","Detergent","Towels","Frozen
  Pizza","Water"};
    ArrayAdapter<String> adapter=new ArrayAdapter<String>
 (this,R.layout.rowlayout,R.id.txt_title,items);
    chl.setAdapter(adapter);
    chl.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String selectedItem=((TextView)view).getText().toString();
            if (selectedItem.contains(selectedItem)) {
                selectedItems.remove(selectedItem);
            }
                else
                    selectedItems.add(selectedItem);

            }
        });

}

public void showSelectedItems(View view){
    String items="";
    for (String item:selectedItems){
        items+="-"+item+"\n";
    }
    Toast.makeText(getApplicationContext(),"Added To Your Cart",Toast.LENGTH_SHORT).show();}}


来源: stackexchange

问:
Calculate value based on amount of green against blue and red
A bit stuck on this one.

Here is my predicament:

A colour has 3 elements Red, Green and Blue (RGB).

All colours have a value from 0-255.

for example:

```<code>var red:int = 53;
var green:int = 150;
var blue:int = 28;
</code>```

My scoring system works that the greener the colour the higher score it will get out of 10.

so:

```<code>var red:int = 0;
var green:int = 255;
var blue:int = 0;
</code>```

Would receive the highest score(10) and:

```<code>var red:int = 255;
var green:int = 0;
var blue:int = 255;
</code>```

would receive the lowest score (0).

I need to produce an equation of some sort. Is Bayes' Theorum where I am meant to be?

really dont have a clue.

答:
You didn't specified what you want this equation for. I believe this was already said that you have function with 3 parameters but you give expected ouput only for two cases of single parameter and there are many function which could fulfill your expectations but between those two outputs work completely different.

I don't know If you've notice this but for example your colorFitness gives 50 score for 0x000000 - is that what you expect?

For the current state of your question I could also propose something like this.

```<code>function score(c:uint) {
    var g:uint = (c >>> 8) & 0xFF;
    var s:uint = g + (c >>> 16 & g ^ g);
    s = (s + (c & 0xFF & g ^ g)) / 0x2FD * 100;
    trace("score for", c.toString(16), ":", s);
}

score(0x00FF00); //100
score(0x000000); //0
score(0xFF00FF); //0
score(0xFF7FFF); //16
score(0xFFFFFF); //33
score(0x00FFFF); //66
score(0xFFFF00); //66
score(0x7FFF7F); //66
</code>```

But it would be nice if you tell us what you need that formula for or specify more precisely what it should do.

ContentLicense: CC BY-SA 3.0

Body:
A bit stuck on this one.

Here is my predicament:

A colour has 3 elements Red, Green and Blue (RGB).

All colours have a value from 0-255.

for example:

var red:int = 53;
var green:int = 150;
var blue:int = 28;

My scoring system works that the greener the colour the higher score it will get out of 10.

so:

var red:int = 0;
var green:int = 255;
var blue:int = 0;

Would receive the highest score(10) and:

var red:int = 255;
var green:int = 0;
var blue:int = 255;

would receive the lowest score (0).

I need to produce an equation of some sort. Is Bayes' Theorum where I am meant to be?

really dont have a clue.

Body:
You didn't specified what you want this equation for. I believe this was already said that you have function with 3 parameters but you give expected ouput only for two cases of single parameter and there are many function which could fulfill your expectations but between those two outputs work completely different.

I don't know If you've notice this but for example your colorFitness gives 50 score for 0x000000 - is that what you expect?

For the current state of your question I could also propose something like this.

function score(c:uint) {
    var g:uint = (c >>> 8) & 0xFF;
    var s:uint = g + (c >>> 16 & g ^ g);
    s = (s + (c & 0xFF & g ^ g)) / 0x2FD * 100;
    trace("score for", c.toString(16), ":", s);
}

score(0x00FF00); //100
score(0x000000); //0
score(0xFF00FF); //0
score(0xFF7FFF); //16
score(0xFFFFFF); //33
score(0x00FFFF); //66
score(0xFFFF00); //66
score(0x7FFF7F); //66

But it would be nice if you tell us what you need that formula for or specify more precisely what it should do.


问:
Xamarin form display alert pop up appear 2 times
i have created Xamarin pcl form project and ask confirmation when user press the logout button, its working fine both android and iOS but at the same i run as windows UWP project the pop up appears 2 time, i don't what happen. Please guide me some one how can i fix this issues.

i mentioned my code below what i used in my project.

I have used both option with await and without await keyword but no luck.

```<code>var resp = await DisplayAlert("","Are you sure want to Logout?","Yes", "No");
if (resp)
{
}
</code>```

答:
You're executing the popup by calling await DisplayAlert. By storing it into a variable, you're just saying that you want to get the output from the popup (Yes or no). The second popup is because you added it to your if condition. You should just do this:

```<code>  Device.BeginInvokeOnMainThread(new Action(async () =>
  {
       if(await DisplayAlert("", "Are you sure want to Logout?", "Yes", "No"))
       {

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

Hope it helps!

Body:
i have created Xamarin pcl form project and ask confirmation when user press the logout button, its working fine both android and iOS but at the same i run as windows UWP project the pop up appears 2 time, i don't what happen. Please guide me some one how can i fix this issues.

i mentioned my code below what i used in my project.

I have used both option with await and without await keyword but no luck.

var resp = await DisplayAlert("","Are you sure want to Logout?","Yes", "No");
if (resp)
{
}

Body:
You're executing the popup by calling await DisplayAlert. By storing it into a variable, you're just saying that you want to get the output from the popup (Yes or no). The second popup is because you added it to your if condition. You should just do this:

  Device.BeginInvokeOnMainThread(new Action(async () =>
  {
       if(await DisplayAlert("", "Are you sure want to Logout?", "Yes", "No"))
       {

       }
  }));

Hope it helps!


问:
how to remove numeric characters before any alphabetic characters
I have one variable which has values like this

```<code>VAL1="59809_RH_EA_TEST_1_P1_Q"
</code>```

or

```<code>VAL1="89292-RH_EA_TEST_1_P1_Q"
</code>```

How can I get only RH_EA_TEST_1_P1_Q using sed or any other bash command

答:
With Parameter Expansion

```<code>$ VAL1='59809_RH_EA_TEST_1_P1_Q'
$ echo "${VAL1#*[_-]}"
RH_EA_TEST_1_P1_Q

$ VAL1='89292-RH_EA_TEST_1_P1_Q'
$ echo "${VAL1#*[_-]}"
RH_EA_TEST_1_P1_Q
</code>```

This removes minimal match from start of string upto first occurrence of _ or -

Body:
I have one variable which has values like this

VAL1="59809_RH_EA_TEST_1_P1_Q"

or

VAL1="89292-RH_EA_TEST_1_P1_Q"

How can I get only RH_EA_TEST_1_P1_Q using sed or any other bash command

Body:
With Parameter Expansion

$ VAL1='59809_RH_EA_TEST_1_P1_Q'
$ echo "${VAL1#*[_-]}"
RH_EA_TEST_1_P1_Q

$ VAL1='89292-RH_EA_TEST_1_P1_Q'
$ echo "${VAL1#*[_-]}"
RH_EA_TEST_1_P1_Q

This removes minimal match from start of string upto first occurrence of _ or -


问:
What would be the best way to make a sort of drop-down-more-info div?
I have 4 divs with a more-info button on the bottom of each, like so:

http://codepen.io/anon/pen/VpVbPq

And when a user presses ' more info ' I would like for it to extend to the bottom and show extra info, obviously.

The problem is under the more-info div, text is seen, but what if I want to hide whats under it, even if its opacity is 0.6 ?

I thought it would've been the best if I draw what I need, so here:

Codepen code below:

html

```<code><body>
  <div class="wrapper">
  <div class="info">
      <p>
          dummy text
      </p>
        <div class="more-info">more info</div>
      </div>
      <div class="info"><div class="more-info">more info</div></div>
      <div class="info"><div class="more-info">more info</div></div>
      <div class="info"><div class="more-info">more info</div></div>
    </div>
</body>
</code>```

css

```<code>.wrapper  {
  width: 1045px;
  margin: 0 auto;
}
.info  {
  width: 500px; height: 200px;
  background-color: #1A5AB6;
  display: inline-block;
  margin: 10px;
  position: relative;
  font-size: 20px;
  overflow: hidden;
}
.more-info {
  width: 100%; height: 40px;
  background-color: #0C1B44;
  bottom: 0; left: 0;
  display: inline-block;
  position: absolute;
  font-size: 20px;
  color: white;
  line-height: 35px;
  text-align: center;
  opacity: 0.6;
}
.more-info:hover  {background-color: #010716;}
</code>```

答:
Your question: "what would be the best way to make a sort of drop-down-more-info div?"

There is a built in function in Boot Strap that allows you to use a "data" class that does all the crunching for you. Just call on their css and js files externally or host on your server. Familiarize yourself with their data classes and call on their css/js classes to simplify previously arduous coding, like revealing a hidden DIV on click!

Note the data-toggle="collapse" and data-target="#more_info" lines in my div that holds the span tag that is the control for revealing the hidden
:

```<code>`<div data-toggle="collapse" data-target="#more_info"><span class="glyphicon glyphicon-search"></span> <span title="Click for more info">more info</span></div>`
</code>```

Then note the class in my hidden div. Note the id of the hidden div and the data-target #more_info. This can be used for classes as well, ie: .more_info. Everything is explained in more detail at bootstrap Github or their official site: http://getbootstrap.com/

```<code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">        </script>
</head>

<body>
<div class="wrapper">
<div class="info">
  <p>
      Honestly, Bootstrap would be the easiest way to accomplish this without a doubt. Just click the more info button below.
  </p>
    <div data-toggle="collapse" data-target="#more_info"><span class="glyphicon glyphicon-search"></span> <span title="Click for more info">more info</span></div>
    <div id="more_info" class="collapse">Some hidden infomration you ony want to be seen when the user click on the control link.</div>
</div>
</code>```

or add three divs floating perfectly without all the css, each with drop downs more info.

```<code><body>
<div class="wrapper row">
    <div class="col-md-4">
        <p>
            Honestly, Bootstrap would be the easiest way to accomplish this without a doubt. Just click the more info button below.
        </p>
        <div data-toggle="collapse" data-target="#more_info">
            <span class="glyphicon glyphicon-search"></span>
            <span title="Click for more info">more info</span>                                                                                </div>
        <div id="more_info" class="collapse">
            Some hidden information you only want to be seen when the user click on the control link.
        </div>
    </div>
<div class="col-md-4">
    <p>
        Some other information we want to have a hidden drop down with more info for.
    </p>
    <div data-toggle="collapse" data-target="#more_info2">
        <span class="glyphicon glyphicon-search"></span>
        <span title="Click for more info">more info</span>
    </div>
    <div id="more_info2" class="collapse">
        Some hidden information you only want to be seen when the user click on the control link.</div>
    </div>
    <div class="col-md-4">
        <p>
            Yet another div with info that has a drop down menu for more info included below.
        </p>
    <div data-toggle="collapse" data-target="#more_info3">
        <span class="glyphicon glyphicon-search"></span>
        <span title="Click for more info">more info</span>
    </div>
    <div id="more_info3" class="collapse">
        Some hidden infomration you ony want to be seen when the user click on the control link.
    </div>
</div>
</code>```

Best of luck.

Body:
I have 4 divs with a more-info button on the bottom of each, like so:

http://codepen.io/anon/pen/VpVbPq

And when a user presses ' more info ' I would like for it to extend to the bottom and show extra info, obviously.

The problem is under the more-info div, text is seen, but what if I want to hide whats under it, even if its opacity is 0.6 ?

I thought it would've been the best if I draw what I need, so here:

Codepen code below:

html

          dummy text

more info

more info

more info

more info

css

.wrapper  {
  width: 1045px;
  margin: 0 auto;
}
.info  {
  width: 500px; height: 200px;
  background-color: #1A5AB6;
  display: inline-block;
  margin: 10px;
  position: relative;
  font-size: 20px;
  overflow: hidden;
}
.more-info {
  width: 100%; height: 40px;
  background-color: #0C1B44;
  bottom: 0; left: 0;
  display: inline-block;
  position: absolute;
  font-size: 20px;
  color: white;
  line-height: 35px;
  text-align: center;
  opacity: 0.6;
}
.more-info:hover  {background-color: #010716;}

Body:
Your question: "what would be the best way to make a sort of drop-down-more-info div?"

There is a built in function in Boot Strap that allows you to use a "data" class that does all the crunching for you. Just call on their css and js files externally or host on your server. Familiarize yourself with their data classes and call on their css/js classes to simplify previously arduous coding, like revealing a hidden DIV on click!

Note the data-toggle="collapse" and data-target="#more_info" lines in my div that holds the span tag that is the control for revealing the hidden <div id="more_info">:

`<div data-toggle="collapse" data-target="#more_info"><span class="glyphicon glyphicon-search"></span> <span title="Click for more info">more info</span></div>`

Then note the class in my hidden div. Note the id of the hidden div and the data-target #more_info. This can be used for classes as well, ie: .more_info. Everything is explained in more detail at bootstrap Github or their official site: http://getbootstrap.com/

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">        </script>
</head>

<body>
<div class="wrapper">
<div class="info">
  <p>
      Honestly, Bootstrap would be the easiest way to accomplish this without a doubt. Just click the more info button below.
  </p>
    <div data-toggle="collapse" data-target="#more_info"><span class="glyphicon glyphicon-search"></span> <span title="Click for more info">more info</span></div>
    <div id="more_info" class="collapse">Some hidden infomration you ony want to be seen when the user click on the control link.</div>
</div>

or add three divs floating perfectly without all the css, each with drop downs more info.

<body>
<div class="wrapper row">
    <div class="col-md-4">
        <p>
            Honestly, Bootstrap would be the easiest way to accomplish this without a doubt. Just click the more info button below.
        </p>
        <div data-toggle="collapse" data-target="#more_info">
            <span class="glyphicon glyphicon-search"></span>
            <span title="Click for more info">more info</span>                                                                                </div>
        <div id="more_info" class="collapse">
            Some hidden information you only want to be seen when the user click on the control link.
        </div>
    </div>
<div class="col-md-4">
    <p>
        Some other information we want to have a hidden drop down with more info for.
    </p>
    <div data-toggle="collapse" data-target="#more_info2">
        <span class="glyphicon glyphicon-search"></span>
        <span title="Click for more info">more info</span>
    </div>
    <div id="more_info2" class="collapse">
        Some hidden information you only want to be seen when the user click on the control link.</div>
    </div>
    <div class="col-md-4">
        <p>
            Yet another div with info that has a drop down menu for more info included below.
        </p>
    <div data-toggle="collapse" data-target="#more_info3">
        <span class="glyphicon glyphicon-search"></span>
        <span title="Click for more info">more info</span>
    </div>
    <div id="more_info3" class="collapse">
        Some hidden infomration you ony want to be seen when the user click on the control link.
    </div>
</div>

Best of luck.


问:
Android studio media player cannot work
I have an issue which media player cannot be played while pressing the play button even though the song is in the raw directory .

Here the code below.

```<code>public class MainActivity extends AppCompatActivity {

    private MediaPlayer mediaPlayer;

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

        mediaPlayer = MediaPlayer.create(this,R.raw.song);

        Button play = (Button) findViewById(R.id.play);

        Button pause = (Button) findViewById(R.id.pause);

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(MainActivity.this,"Play",Toast.LENGTH_SHORT).show();
                mediaPlayer.start();
            }
        });

        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(MainActivity.this,"Pause",Toast.LENGTH_SHORT).show();
                mediaPlayer.pause();
            }
        });

    }

}
</code>```

And here is the layout file below:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.android.musicplayer.MainActivity">

    <Button
        android:id="@+id/play"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Play"/>

    <Button
        android:id="@+id/pause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pause"/>

</LinearLayout>
</code>```

答:
I have found the SoundPoolPlayer which is better than the mediaplayer

SoundPoolPlayer custom extention from Android SoundPool with setOnCompletionListener without the low-efficiency drawback of MediaPlayer.

Creation:

```<code>SoundPoolPlayer mPlayer = SoundPoolPlayer.create(context, resId);
mPlayer.setOnCompletionListener(
    new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {  //mp will be null here
            Log.d("debug", "completed");
        }
    };
);
</code>```

play:

```<code>mPlayer.play()
</code>```

pause:

```<code>mPlayer.pause();
</code>```

stop:

```<code>mPlayer.stop();
</code>```

resume:

```<code>mPlayer.resume();
</code>```

isPlaying:

```<code>mPlayer.isPlaying();
</code>```

Here is the Link to Download the player Class

Enjoy- Happy Coding

Title: Android studio media player cannot work

Body:
I have an issue which media player cannot be played while pressing the play button even though the song is in the raw directory .

Here the code below.

public class MainActivity extends AppCompatActivity {

    private MediaPlayer mediaPlayer;

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

        mediaPlayer = MediaPlayer.create(this,R.raw.song);

        Button play = (Button) findViewById(R.id.play);

        Button pause = (Button) findViewById(R.id.pause);

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(MainActivity.this,"Play",Toast.LENGTH_SHORT).show();
                mediaPlayer.start();
            }
        });

        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(MainActivity.this,"Pause",Toast.LENGTH_SHORT).show();
                mediaPlayer.pause();
            }
        });

    }

}

And here is the layout file below:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.android.musicplayer.MainActivity">

    <Button
        android:id="@+id/play"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Play"/>

    <Button
        android:id="@+id/pause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pause"/>

</LinearLayout>

Body:
I have found the SoundPoolPlayer which is better than the mediaplayer

SoundPoolPlayer custom extention from Android SoundPool with setOnCompletionListener without the low-efficiency drawback of MediaPlayer.

Creation:

SoundPoolPlayer mPlayer = SoundPoolPlayer.create(context, resId);
mPlayer.setOnCompletionListener(
    new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {  //mp will be null here
            Log.d("debug", "completed");
        }
    };
);

play:

mPlayer.play()

pause:

mPlayer.pause();

stop:

mPlayer.stop();

resume:

mPlayer.resume();

isPlaying:

mPlayer.isPlaying();

Here is the Link to Download the player Class

Enjoy- Happy Coding


问:
Getting debugger context in C# interactive
C# Interactive seems a lot more powerful than the Immediate Window (at least it handles lambda expressions that are often used in LINQ - see Visual Studio debugging "quick watch" tool and lambda expressions), but it looks like it can't be used as a replacement as it doesn't know about the debugger context. Is there a way to have access to the debugger context?

I've seen Getting debugger context in F# interactive and it might require the same things, but maybe there are new/different things available.

http://extendedimmediatewin.codeplex.com/ could be useful but looks quite dead, although someone said on Oct 18 2011 that he was planning to port it to VB.Net ( http://extendedimmediatewin.codeplex.com/discussions/75589 ).

答:
Not a complete solution, but in VS2015, after you've run Initialize Interactive with Project, you can use Debug > Attach to Process to connect to the InteractiveHost.exe process.

You can then debug functions from your project. You won't be able to debug one-off functions in the Interactive window, though, as Kevin explained.

As as side note, https://stackoverflow.com/a/40650343/467110 points out that you may have to have a C# Interactive window open before you open your solution in order to successfully Initialize Interactive with Project


问:
rxJava2 CompositeDisposable in presenter
I'm migrating my app to the rxJava2 and would like to clarify some things.
In my BasePresenter class I do following:

```<code>@Override
public void attachView(T mvpView) {
    this.mvpView = mvpView;
    compositeDisposable = new CompositeDisposable();
}

@Override
public void detachView() {
    compositeDisposable.dispose();
    mvpView = null;
}
</code>```

So if I call compositeDisposable.dispose(); when I detach the view then onNext(), onError() or onComplete() are not going to be called and there is no reason to check isViewAttached() in onNext()?
Is this the right way of using CompositeDisposable in the presenter?

答: Yes, that is correct. CompositeDisposable is essentially what CompositeSubscription was in the previous version of rxJava.</p>

Body:
I'm migrating my app to the rxJava2 and would like to clarify some things.
In my BasePresenter class I do following:

@Override
public void attachView(T mvpView) {
    this.mvpView = mvpView;
    compositeDisposable = new CompositeDisposable();
}

@Override
public void detachView() {
    compositeDisposable.dispose();
    mvpView = null;
}

So if I call compositeDisposable.dispose(); when I detach the view then onNext(), onError() or onComplete() are not going to be called and there is no reason to check isViewAttached() in onNext()?
Is this the right way of using CompositeDisposable in the presenter?


问:
Access query, if two values exist in one column, omit one
I have a series of queries that generate reports that contain chemical data. There are two compounds A and B where A is the total amount and B is a speciated amount (like total iron and ferrous iron, for example).

There are about one hundred total compounds in the query result, and I need a criteria to filter the results such that if both Compounds A and B are present, only Compound B is displayed. So far I've tried adding a few iif statements to the criteria section in the query builder with no luck.

Here is what I have so far:

```<code>SELECT Table1.KEY_ANLT
FROM Table1
WHERE (((Table1.KEY_ANLT)=IIf([Table1].[KEY_ANLT]=1223 And [Table1].[KEY_ANLT]=70,70,1223)));
</code>```

This filters out Compound A but does not include the rest of the compounds. How can I modify the query to also include the other compounds?

答:
So, to clarify some of the comments above, the problem here is you don't have (or haven't specified above) a way to identify values that go together. You gave 70 and 1223 as an example, but if you gave us a list of all the numbers, how would we be able to identify which ones go together? You might say "chemistry expertise", but that's based on another column with the compounds' names, right? So really, your query should use that column. But then there's still the problem of how to connect associated names (e.g., "total iron" and "ferrous iron" might be connected because they both have the word "iron", but what about "permanganate" and "manganese"?). In short, you need another column to specify the thing in common between these separate rows, whether it's element, ion, charge, etc. You would also need a column identifying which row in each "group" you would want to include in your query (or, which ones to exclude). For example:

```<code>+----------+-----------------+---------+---------+
| KEY_ANLT |    Compound     | Element | Primary |
+----------+-----------------+---------+---------+
|       70 | total iron      | Fe      | Y       |
|     1223 | ferrous iron    | Fe      |         |
|     1224 | ferric iron     | Fe      |         |
|      900 | total manganese | Mn      | Y       |
|      901 | permanganate    | Mn      |         |
+----------+-----------------+---------+---------+
</code>```

Then, to get a query that shows just the "primary" rows, it's pretty trivial:

```<code>SELECT * FROM Table1 WHERE Primary='Y';
</code>```

Without that [Primary] column, you'd have to decide how to choose each row. Perhaps you'd want the one with the smallest KEY_ANLT?

```<code>SELECT Table1.*
FROM
    (SELECT Element, min(KEY_ANLT) AS MinKey FROM Table1 GROUP BY Element) AS Subquery
    INNER JOIN Table1 ON
        Subquery.Element=Table1.Element AND
        Subquery.MinKey=Table1.KEY_ANLT
</code>```

The reason your query doesn't work is that the WHERE clause operates row-by-row, and doesn't compare different rows to one another. So in your SQL:

```<code>IIf([Table1].[KEY_ANLT]=1223 And [Table1].[KEY_ANLT]=70,70,1223)
</code>```

NONE of the rows will evaluate this as 70, because no single row has KEY_ANLT=1223 AND KEY_ANLT=70. Each row only has one value for KEY_ANLT. So then that IIF expression evaluates as 1223 for every row, and your condition will only return rows where KEY_ANLT=1223 (compound B).

Body:
I have a series of queries that generate reports that contain chemical data. There are two compounds A and B where A is the total amount and B is a speciated amount (like total iron and ferrous iron, for example).

There are about one hundred total compounds in the query result, and I need a criteria to filter the results such that if both Compounds A and B are present, only Compound B is displayed. So far I've tried adding a few iif statements to the criteria section in the query builder with no luck.

Here is what I have so far:

SELECT Table1.KEY_ANLT
FROM Table1
WHERE (((Table1.KEY_ANLT)=IIf([Table1].[KEY_ANLT]=1223 And [Table1].[KEY_ANLT]=70,70,1223)));

This filters out Compound A but does not include the rest of the compounds. How can I modify the query to also include the other compounds?

Body:
So, to clarify some of the comments above, the problem here is you don't have (or haven't specified above) a way to identify values that go together. You gave 70 and 1223 as an example, but if you gave us a list of all the numbers, how would we be able to identify which ones go together? You might say "chemistry expertise", but that's based on another column with the compounds' names, right? So really, your query should use that column. But then there's still the problem of how to connect associated names (e.g., "total iron" and "ferrous iron" might be connected because they both have the word "iron", but what about "permanganate" and "manganese"?). In short, you need another column to specify the thing in common between these separate rows, whether it's element, ion, charge, etc. You would also need a column identifying which row in each "group" you would want to include in your query (or, which ones to exclude). For example:

+----------+-----------------+---------+---------+
| KEY_ANLT |    Compound     | Element | Primary |
+----------+-----------------+---------+---------+
|       70 | total iron      | Fe      | Y       |
|     1223 | ferrous iron    | Fe      |         |
|     1224 | ferric iron     | Fe      |         |
|      900 | total manganese | Mn      | Y       |
|      901 | permanganate    | Mn      |         |
+----------+-----------------+---------+---------+

Then, to get a query that shows just the "primary" rows, it's pretty trivial:

SELECT * FROM Table1 WHERE Primary='Y';

Without that [Primary] column, you'd have to decide how to choose each row. Perhaps you'd want the one with the smallest KEY_ANLT?

SELECT Table1.*
FROM
    (SELECT Element, min(KEY_ANLT) AS MinKey FROM Table1 GROUP BY Element) AS Subquery
    INNER JOIN Table1 ON
        Subquery.Element=Table1.Element AND
        Subquery.MinKey=Table1.KEY_ANLT

The reason your query doesn't work is that the WHERE clause operates row-by-row, and doesn't compare different rows to one another. So in your SQL:

IIf([Table1].[KEY_ANLT]=1223 And [Table1].[KEY_ANLT]=70,70,1223)

NONE of the rows will evaluate this as 70, because no single row has KEY_ANLT=1223 AND KEY_ANLT=70. Each row only has one value for KEY_ANLT. So then that IIF expression evaluates as 1223 for every row, and your condition will only return rows where KEY_ANLT=1223 (compound B).


问:
How can i show alphabets on the top of product table
```<code>public class Producttable {

public static void main(String[] args) {

    int tableSize = 4;

    printMultiplicationTable(tableSize);
}

public static void printMultiplicationTable(int tableSize) {

    // first print the top header row
    System.out.format("      ");

    for(int i = 1; i<=tableSize;i++ ) {

        System.out.format("%4d",i);
    }
    System.out.println();

    System.out.println("__________________________");

    for(int i = 1 ;i<=tableSize;i++) {
        // print left most column first

        System.out.format("%4d |",i);

        for(int j=1;j<=tableSize;j++) {
            System.out.format("%4d",i*j);
        }
        System.out.println();
    }
}
</code>```

Teacher gave us task to make a product table This is the product table that i am getting with this code
Everything is good here but instead of numbers on the top head of the table i want alphabets like (A B C D). can anybody help me please?

答:
You can make the following changes:</p>

```<code> class Producttable {

public static void main(String[] args) {

    int tableSize = 4;

    printMultiplicationTable(tableSize);
}

public static void printMultiplicationTable(int tableSize) {

    // first print the top header row
    System.out.format("      ");

    for(int i = 1; i<=tableSize;i++ ) {

        char c = (char)(64+i);
        System.out.format("%4s",String.valueOf(c));
    }
    System.out.println();

    System.out.println("__________________________");

    for(int i = 1 ;i<=tableSize;i++) {
        // print left most column first

        System.out.format("%4d |",i);

        for(int j=1;j<=tableSize;j++) {
            System.out.format("%4d",i*j);
        }
        System.out.println();
    }
}
}
</code>```

Body:
public class Producttable {

public static void main(String[] args) {

    int tableSize = 4;

    printMultiplicationTable(tableSize);
}

public static void printMultiplicationTable(int tableSize) {

    // first print the top header row
    System.out.format("      ");

    for(int i = 1; i<=tableSize;i++ ) {

        System.out.format("%4d",i);
    }
    System.out.println();

    System.out.println("__________________________");

    for(int i = 1 ;i<=tableSize;i++) {
        // print left most column first

        System.out.format("%4d |",i);

        for(int j=1;j<=tableSize;j++) {
            System.out.format("%4d",i*j);
        }
        System.out.println();
    }
}

Teacher gave us task to make a product table This is the product table that i am getting with this code
Everything is good here but instead of numbers on the top head of the table i want alphabets like (A B C D). can anybody help me please?

Body:
You can make the following changes:

 class Producttable {

public static void main(String[] args) {

    int tableSize = 4;

    printMultiplicationTable(tableSize);
}

public static void printMultiplicationTable(int tableSize) {

    // first print the top header row
    System.out.format("      ");

    for(int i = 1; i<=tableSize;i++ ) {

        char c = (char)(64+i);
        System.out.format("%4s",String.valueOf(c));
    }
    System.out.println();

    System.out.println("__________________________");

    for(int i = 1 ;i<=tableSize;i++) {
        // print left most column first

        System.out.format("%4d |",i);

        for(int j=1;j<=tableSize;j++) {
            System.out.format("%4d",i*j);
        }
        System.out.println();
    }
}
}


问:
How do I convert a String object into a Hash object?
I have a string which looks like a hash:

```<code>"{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, :key_b => { :key_1b => 'value_1b' } }"
</code>```

How do I get a Hash out of it? like:

```<code>{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, :key_b => { :key_1b => 'value_1b' } }
</code>```

The string can have any depth of nesting. It has all the properties how a valid Hash is typed in Ruby.

答:
I built a gem hash_parser that first checks if a hash is safe or not using ruby_parser gem. Only then, it applies the eval.

You can use it as

```<code>require 'hash_parser'

# this executes successfully
a = "{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' },
       :key_b => { :key_1b => 'value_1b' } }"
p HashParser.new.safe_load(a)

# this throws a HashParser::BadHash exception
a = "{ :key_a => system('ls') }"
p HashParser.new.safe_load(a)
</code>```

The tests in https://github.com/bibstha/ruby_hash_parser/blob/master/test/test_hash_parser.rb give you more examples of the things I've tested to make sure eval is safe.

ContentLicense: CC BY-SA 2.5

Body:
I have a string which looks like a hash:

"{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, :key_b => { :key_1b => 'value_1b' } }"

How do I get a Hash out of it? like:

{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, :key_b => { :key_1b => 'value_1b' } }

The string can have any depth of nesting. It has all the properties how a valid Hash is typed in Ruby.

Body:
I built a gem hash_parser that first checks if a hash is safe or not using ruby_parser gem. Only then, it applies the eval.

You can use it as

require 'hash_parser'

# this executes successfully
a = "{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' },
       :key_b => { :key_1b => 'value_1b' } }"
p HashParser.new.safe_load(a)

# this throws a HashParser::BadHash exception
a = "{ :key_a => system('ls') }"
p HashParser.new.safe_load(a)

The tests in https://github.com/bibstha/ruby_hash_parser/blob/master/test/test_hash_parser.rb give you more examples of the things I've tested to make sure eval is safe.


问:
How to display data in Primeng Datatable from Json file
I have Data in Object form and I want to display it in Primeng Datatable but it display No record found.

data in json file

```<code>{
  "value1": "Value1",
  "value2": "value2",
  "value": "Value3"
}
</code>```

this is how i get it in component file

```<code>this.http.get("app/components/my.json").subscribe((data) => {
        this.value = data.json();
    });
</code>```

and here is how i am trying to display it

```<code><p-dataTable [value]="values">
    <p-column field="value1" header="Value1"></p-column>
</p-dataTable>
</code>```

答:
The gridMenuOptions object needs to be an array type to bind to the value input property on the PrimeNG datagrid component.

It's not quite clear from the question but it doesn't look like your data is in that format? It would need to in this shape:

```<code>gridMenuOptions = [
  {quantity: 1, section: 'A', row: 1},
  {quantity: 2, section: 'B', row: 3}
];
</code>```

Then you can bind it to a datatable definition e.g.

```<code><p-dataTable [value]="gridMenuOptions">
    <p-column field="quantity" header="Quantity"></p-column>
    <p-column field="row" header="Row"></p-column>
    <p-column field="section" header="Section"></p-column>
</p-dataTable>
</code>```

Body:
I have Data in Object form and I want to display it in Primeng Datatable but it display No record found.

data in json file

{
  "value1": "Value1",
  "value2": "value2",
  "value": "Value3"
}

this is how i get it in component file

this.http.get("app/components/my.json").subscribe((data) => {
        this.value = data.json();
    });

and here is how i am trying to display it

Body:
The gridMenuOptions object needs to be an array type to bind to the value input property on the PrimeNG datagrid component.

It's not quite clear from the question but it doesn't look like your data is in that format? It would need to in this shape:

gridMenuOptions = [
  {quantity: 1, section: 'A', row: 1},
  {quantity: 2, section: 'B', row: 3}
];

Then you can bind it to a datatable definition e.g.

<p-dataTable [value]="gridMenuOptions">
    <p-column field="quantity" header="Quantity"></p-column>
    <p-column field="row" header="Row"></p-column>
    <p-column field="section" header="Section"></p-column>
</p-dataTable>


问:
Concurrent Ajax requests with Rxjs
I'am currently switched from promises to observables. I am using Redux-Observable for my react app. Basically, I am looking for the best operator that will enable mutliple, concurrent ajax calls and return the responses when all the observables have sucessfully finished executing.
Here is a code snippet from my app.

```<code>let epicPostAd = (action$, store, {ajax}) =>
  action$.ofType(POST_AD)
   .debounceTime(1000)
   .mergeMap(({ payload }) =>
     ajax(generateAjaxRequestSetting(POSTS_URL, 'post', payload,CT_JSON))
      .map(response => postAdSuccessful(response))
      .catch(e => Observable.of(postAdUnsuccessful(e.xhr.response)))
      .takeUntil(action$.ofType(LOCATION_CHANGE))
    )
</code>```

It is a simple ajax request that posts given ad and dispatches POST_AD_SUCCESSFUL when response is 201 else dispatches POST_AD_UNSUCCESSFUL on error.
But the issues is I want to make subsequent ajax observable stream when there is a response. Such as

```<code>.map(response => /* start a stream of ajax observables then process the response */)
</code>```

I will appreciate if you show me the optimal way of achieving this.

答:
Sounds like you're looking for the forkJoin operator.

It will subscribe to all the Observables you pass to it and after they all complete, it will emit the last value from each inside an array.

It wasn't entirely clear where in your Epic you wanted to do this, so I just made a generic example:

```<code>const somethingEpic = (action$, store, { ajax }) =>
  action$.ofType(SOMETHING)
    .mergeMap(() =>
      Observable.forkJoin(
        ajax('/first'),
        ajax('/second'),
        ajax('/third')
      )
      .do(results => {
        // the results is an array, containing each
        const [first, second, third] = results;
        console.log(first, second, third);
      })
      .map(results => ({
        type: 'SOME_RESULTS',
        results
      }))
    );
</code>```

Technically, it supports a final resultSelector argument you can use instead of using the map operator after it, but I tend not to use it because I've found it's less clear with only negligible performance benefits in common redux-observable style cases. But it's still good to know. Can be handy for more "data-normalization" stuff rather than "transform this into an action" stuff.

```<code>const somethingEpic = (action$, store, { ajax }) =>
  action$.ofType(SOMETHING)
    .mergeMap(() =>
      Observable.forkJoin(
        ajax('/first'),
        ajax('/second'),
        ajax('/third'),
        results => ({
          type: 'SOME_RESULTS',
          results
        })
      )
    );
</code>```

ALSO, if you're asking yourself "what operator do I use?" you should try the operator wizard located in the documentation: http://reactivex.io/rxjs/

Scroll down to the part that says:

Do you need to find an operator for your problem? Start by choosing an option from the list below:

I have one existing Observable, and...

I have some Observables to combine together as one Observable, and...

I have no Observables yet, and...

Hint: open your DevTools to experiment with RxJS.

Though in this case, forkJoin is correctly suggested but when you click on it, it isn't yet documented :sadface: But a google search would present many different websites explaining what it does and how to use it (in RxJS and in other Rx implementations in other languages). Like this helpful website

Title: Concurrent Ajax requests with Rxjs

Body:
I'am currently switched from promises to observables. I am using Redux-Observable for my react app. Basically, I am looking for the best operator that will enable mutliple, concurrent ajax calls and return the responses when all the observables have sucessfully finished executing.
Here is a code snippet from my app.

let epicPostAd = (action$, store, {ajax}) =>
  action$.ofType(POST_AD)
   .debounceTime(1000)
   .mergeMap(({ payload }) =>
     ajax(generateAjaxRequestSetting(POSTS_URL, 'post', payload,CT_JSON))
      .map(response => postAdSuccessful(response))
      .catch(e => Observable.of(postAdUnsuccessful(e.xhr.response)))
      .takeUntil(action$.ofType(LOCATION_CHANGE))
    )

It is a simple ajax request that posts given ad and dispatches POST_AD_SUCCESSFUL when response is 201 else dispatches POST_AD_UNSUCCESSFUL on error.
But the issues is I want to make subsequent ajax observable stream when there is a response. Such as

.map(response => /* start a stream of ajax observables then process the response */)

I will appreciate if you show me the optimal way of achieving this.

Body:
Sounds like you're looking for the forkJoin operator.

It will subscribe to all the Observables you pass to it and after they all complete, it will emit the last value from each inside an array.

It wasn't entirely clear where in your Epic you wanted to do this, so I just made a generic example:

const somethingEpic = (action$, store, { ajax }) =>
  action$.ofType(SOMETHING)
    .mergeMap(() =>
      Observable.forkJoin(
        ajax('/first'),
        ajax('/second'),
        ajax('/third')
      )
      .do(results => {
        // the results is an array, containing each
        const [first, second, third] = results;
        console.log(first, second, third);
      })
      .map(results => ({
        type: 'SOME_RESULTS',
        results
      }))
    );

Technically, it supports a final resultSelector argument you can use instead of using the map operator after it, but I tend not to use it because I've found it's less clear with only negligible performance benefits in common redux-observable style cases. But it's still good to know. Can be handy for more "data-normalization" stuff rather than "transform this into an action" stuff.

const somethingEpic = (action$, store, { ajax }) =>
  action$.ofType(SOMETHING)
    .mergeMap(() =>
      Observable.forkJoin(
        ajax('/first'),
        ajax('/second'),
        ajax('/third'),
        results => ({
          type: 'SOME_RESULTS',
          results
        })
      )
    );

ALSO, if you're asking yourself "what operator do I use?" you should try the operator wizard located in the documentation: http://reactivex.io/rxjs/

Scroll down to the part that says:

Do you need to find an operator for your problem? Start by choosing an option from the list below:

I have one existing Observable, and...

I have some Observables to combine together as one Observable, and...

I have no Observables yet, and...

Hint: open your DevTools to experiment with RxJS.

Though in this case, forkJoin is correctly suggested but when you click on it, it isn't yet documented :sadface: But a google search would present many different websites explaining what it does and how to use it (in RxJS and in other Rx implementations in other languages). Like this helpful website


问:
Not able to uninstall VS 2013 professional with update 3
I am trying to UNINSTALL VS - 2013 professional but I am not able to do so. Error I am getting is "Visual Studio Core features fatal error during installation"

When I check log file I get this message inside. after long list of text I find this somewhere in the log file

```<code>[11DC:14D4][2017-03-28T11:44:48]i000: MUX:  ExecuteError: Package (vs_professionalcore) failed: Error Message Id: 1305 ErrorMessage: Error 1305.Error reading from file C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualStudio.QualityTools.CommandLine\v4.0_12.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.QualityTools.CommandLine.dll.  Verify that the file exists and that you can access it.
[13DC:1608][2017-03-28T11:46:08]e000: Error 0x80070643: Failed to uninstall MSI package.
[13DC:1608][2017-03-28T11:46:08]e000: Error 0x80070643: Failed to execute MSI package.
</code>```

Kindly tell me how to fix it. I want to uninstall VS. Please help.

答: To clean up and delete Preview, RC and final releases of Visual Studio 2013 and Visual Studio 2015, as well as early previews of Visual Studio 2017, you can have a try with the VisualStudioUninstall tool: https://github.com/Microsoft/VisualStudioUninstaller </p>

Body:
I am trying to UNINSTALL VS - 2013 professional but I am not able to do so. Error I am getting is "Visual Studio Core features fatal error during installation"

When I check log file I get this message inside. after long list of text I find this somewhere in the log file

[11DC:14D4][2017-03-28T11:44:48]i000: MUX:  ExecuteError: Package (vs_professionalcore) failed: Error Message Id: 1305 ErrorMessage: Error 1305.Error reading from file C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.VisualStudio.QualityTools.CommandLine\v4.0_12.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.QualityTools.CommandLine.dll.  Verify that the file exists and that you can access it.
[13DC:1608][2017-03-28T11:46:08]e000: Error 0x80070643: Failed to uninstall MSI package.
[13DC:1608][2017-03-28T11:46:08]e000: Error 0x80070643: Failed to execute MSI package.

Kindly tell me how to fix it. I want to uninstall VS. Please help.


问:
How to generate JavaDoc using buildr?
I want to automatically generate the JavaDoc using buildr. I tried using the approach suggested in the official Guide PDF from the Homepage. However, it did not work.

```<code>define "SharedState_ebBP", :layout=>eclipse_layout do
project.version = VERSION_NUMBER
project.group = GROUP
</code>```

doc :windowtitle => "Abandon All Hope, Ye Who Enter Here", :private => true
  end

The error message is as follows:
RuntimeError: Don't know how to generate documentation from windowtitleAbandon ......

答:
The correct syntax for setting the window title is

```<code>doc.using(:windowtitle => "Abandon All Hope", :private => true)
</code>```

and with end on a line by itself.  However that in and of itself does not cause the doc task to get run automatically.

To automatically build the JavaDoc when you run buildr simply add to the end of your buildfile:

```<code>task :default => [:build, :doc]
</code>```

This redefines the default task to first build and then doc.

Title: How to generate JavaDoc using buildr?

Body:
I want to automatically generate the JavaDoc using buildr. I tried using the approach suggested in the official Guide PDF from the Homepage. However, it did not work.

define "SharedState_ebBP", :layout=>eclipse_layout do
project.version = VERSION_NUMBER
project.group = GROUP

doc :windowtitle => "Abandon All Hope, Ye Who Enter Here", :private => true
  end

The error message is as follows:
RuntimeError: Don't know how to generate documentation from windowtitleAbandon ......

Body:
The correct syntax for setting the window title is

doc.using(:windowtitle => "Abandon All Hope", :private => true)

and with end on a line by itself.  However that in and of itself does not cause the doc task to get run automatically.

To automatically build the JavaDoc when you run buildr simply add to the end of your buildfile:

task :default => [:build, :doc]

This redefines the default task to first build and then doc.


问:
What is the best way to check if a variable is a list?
I found this 3 ways to check it, but I don't know which of them is the best:

```<code>x = ['Bla', 'Bla', 'Bla', 'etc']

if isinstance(a, list): print('Perfect!')
if type(a) is list:     print('Incredible!')
if type(a) == type([]): print('Awesome!')
</code>```

Which of these is better?

Also, Can I use these ways to check whether an x is a string, tuple, dictionary, int, float, etc? If this is possible, in the first two methods do I have to convert a list to a tuple, string, dictionary, int, float, etc (no?), but in the third? I have to use (), {}, '', and what more for int and float?

答:
These all express different things, so really it depends on exactly what you wish to achieve:

isinstance(x, list) check if the type of x is either list or has list as a parent class (lets ignore ABCs for simplicity etc);

type(x) is list checks if the type of x is precisely list;

type(x) == list checks for equality of types, which is not the same as being identical types as the metaclass could conceivably override __eq__

So in order they express the following:

isinstance(x, list): is x like a list

type(x) is list: is x precisely a list and not a sub class

type(x) == list: is x a list, or some other type using metaclass magic to masquerade as a list.

ContentLicense: CC BY-SA 4.0

Body:
I found this 3 ways to check it, but I don't know which of them is the best:

x = ['Bla', 'Bla', 'Bla', 'etc']

if isinstance(a, list): print('Perfect!')
if type(a) is list:     print('Incredible!')
if type(a) == type([]): print('Awesome!')

Which of these is better?

Also, Can I use these ways to check whether an x is a string, tuple, dictionary, int, float, etc? If this is possible, in the first two methods do I have to convert a list to a tuple, string, dictionary, int, float, etc (no?), but in the third? I have to use (), {}, '', and what more for int and float?


问:
TypeError: unsupported operand type(s) for /: 'str' and 'float'
I am using Python 2 but I'm getting an error:

```
TypeError: unsupported operand type(s) for /: 'str' and 'float'
```

when the script runs to the last line.  I don't understand which variable is still a string type.

```<code>from sys import argv
script, age, height=argv
print 'you\'re %r old'%age
weight=input('and i need your weight to calculate BMI, can you tell me:')
print 'your BMI is %r'%weight/((float(height)/100)**2)
</code>```

答:
```<code>from sys import argv
script, age, height=argv
print 'you\'re %r old'%age
weight=input('and i need your weight to calculate BMI, can you tell me:')
print 'your BMI is %r'%(weight/((float(height)/100)**2))
</code>```

<p>i found the solution, it's because a formula after % must be in () </p>

Body:
I am using Python 2 but I'm getting an error:

TypeError: unsupported operand type(s) for /: 'str' and 'float'

when the script runs to the last line.  I don't understand which variable is still a string type.

from sys import argv
script, age, height=argv
print 'you\'re %r old'%age
weight=input('and i need your weight to calculate BMI, can you tell me:')
print 'your BMI is %r'%weight/((float(height)/100)**2)

Body:
from sys import argv
script, age, height=argv
print 'you\'re %r old'%age
weight=input('and i need your weight to calculate BMI, can you tell me:')
print 'your BMI is %r'%(weight/((float(height)/100)**2))

i found the solution, it's because a formula after % must be in ()


问:
PHP - How to get Network Contents That appears in Chrome using file_get_contents with PHP
When I go to a website in Chrome, one of the things that is loaded in the network tab of the ChromeDev Tools is this JSON file.

I want to be able to get this JSON file with file_get_contents; but that only brings back the HTML of the webpage.

If I right click on this I can see the request headers and options to copy as cURL cmd. Does anyone know how to get this from PHP?

答:
Found a post that answers this. I can use something like PhantomJS to emulate a browser environment apparently.

php file_get_contents - AFTER javascript executes


问:
Can strings be used as an array index?
Can a string be used as array index in C?

Ex:
String      Corresponding value
"ONE"       1
"TWO"       2
"FIVE"      5
"TEN"       10

When a string in the above list is passed to the function, the function must return the corresponding value indicated above. Can this be achieved by declaring a constant array with string as index

```<code>int *x;
x["ONE"]  = 1;
x["TWO"]  = 2;
x["FIVE"] = 5;
x["TEN"]  = 5;

return x["string received by the function"];
</code>```

The above logic does not work as expected; is there a workaround to implement the above logic in order to have a string-indexed array?

答:
This is an old thread, but I thought this might still be useful for anyone out there looking for an implementation. It doesn't take too much code; I did mine in ~100 lines of without any extra library like Hank Gay suggested. I called it a dictionary since it parallels (sort of) the python datatype. Here is the code:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

typedef struct hollow_list hollow_list;

struct hollow_list{
    unsigned int size;
    void *value;
    bool *written;
    hollow_list *children;
};

//Creates a hollow list and allocates all of the needed memory
hollow_list hollow_list_create(unsigned int size){
    hollow_list output;
    output = (hollow_list) {.size = size, .value = (void *) 0, .written = calloc(size, sizeof(bool)), .children = calloc(size, sizeof(hollow_list))};
    return output;
}

//Frees all memory of associated with a hollow list and its children
void hollow_list_free(hollow_list *l, bool free_values){
    int i;
    for(i = 0; i < l->size; i++){
        hollow_list_free(l->children + i, free_values);
    }
    if(free_values){
        free(l->value);
    }
    free(l);
}

//Reads from the hollow list and returns a pointer to the item's data
void *hollow_list_read(hollow_list *l, unsigned int index){
    if(index == 0){
        return l->value;
    }
    unsigned int bit_checker;
    bit_checker = 1<<(l->size - 1);
    int i;
    for(i = 0; i < l->size; i++){
        if(bit_checker & index){
            if(l->written[i] == true){
                return hollow_list_read(l->children + i, bit_checker ^ index);
            } else {
                return (void *) 0;
            }
        }
        bit_checker >>= 1;
    }
}

//Writes to the hollow list, allocating memory only as it needs
void hollow_list_write(hollow_list *l, unsigned int index, void *value){
    if(index == 0){
        l->value = value;
    } else {
        unsigned int bit_checker;
        bit_checker = 1<<(l->size - 1);
        int i;
        for(i = 0; i < l->size; i++){
            if(bit_checker & index){
                if(!l->written[i]){
                    l->children[i] = hollow_list_create(l->size - i - 1);
                    l->written[i] = true;
                }
                hollow_list_write(l->children + i, bit_checker ^ index, value);
                break;
            }
            bit_checker >>= 1;
        }
    }
}

typedef struct dictionary dictionary;

struct dictionary{
    void *value;
    hollow_list *child;
};

dictionary dictionary_create(){
    dictionary output;
    output.child = malloc(sizeof(hollow_list));
    *output.child = hollow_list_create(8);
    output.value = (void *) 0;
    return output;
}

void dictionary_write(dictionary *dict, char *index, unsigned int strlen, void *value){
    void *hollow_list_value;
    dictionary *new_dict;
    int i;
    for(i = 0; i < strlen; i++){
        hollow_list_value = hollow_list_read(dict->child, (int) index[i]);
        if(hollow_list_value == (void *) 0){
            new_dict = malloc(sizeof(dictionary));
            *new_dict = dictionary_create();
            hollow_list_write(dict->child, (int) index[i], new_dict);
            dict = new_dict;
        } else {
            dict = (dictionary *) hollow_list_value;
        }
    }
    dict->value = value;
}

void *dictionary_read(dictionary *dict, char *index, unsigned int strlen){
    void *hollow_list_value;
    dictionary *new_dict;
    int i;
    for(i = 0; i < strlen; i++){
        hollow_list_value = hollow_list_read(dict->child, (int) index[i]);
        if(hollow_list_value == (void *) 0){
            return hollow_list_value;
        } else {
            dict = (dictionary *) hollow_list_value;
        }
    }
    return dict->value;
}

int main(){
    char index0[] = "hello, this is a test";
    char index1[] = "hello, this is also a test";
    char index2[] = "hello world";
    char index3[] = "hi there!";
    char index4[] = "this is something";
    char index5[] = "hi there";

    int item0 = 0;
    int item1 = 1;
    int item2 = 2;
    int item3 = 3;
    int item4 = 4;

    dictionary d;
    d = dictionary_create();
    dictionary_write(&d, index0, 21, &item0);
    dictionary_write(&d, index1, 26, &item1);
    dictionary_write(&d, index2, 11, &item2);
    dictionary_write(&d, index3, 13, &item3);
    dictionary_write(&d, index4, 17, &item4);

    printf("%d\n", *((int *) dictionary_read(&d, index0, 21)));
    printf("%d\n", *((int *) dictionary_read(&d, index1, 26)));
    printf("%d\n", *((int *) dictionary_read(&d, index2, 11)));
    printf("%d\n", *((int *) dictionary_read(&d, index3, 13)));
    printf("%d\n", *((int *) dictionary_read(&d, index4, 17)));
    printf("%d\n", ((int) dictionary_read(&d, index5, 8)));
}
</code>```

Unfortunately you can't replicate the list[x] syntax, but this is the best alternative I have come up with.

OwnerDisplayName: Kanakagiri

LastEditorDisplayName: Hank Gay

Title: Can strings be used as an array index?

Body:
Can a string be used as array index in C?

Ex:
String      Corresponding value
"ONE"       1
"TWO"       2
"FIVE"      5
"TEN"       10

When a string in the above list is passed to the function, the function must return the corresponding value indicated above. Can this be achieved by declaring a constant array with string as index

int *x;
x["ONE"]  = 1;
x["TWO"]  = 2;
x["FIVE"] = 5;
x["TEN"]  = 5;

return x["string received by the function"];

The above logic does not work as expected; is there a workaround to implement the above logic in order to have a string-indexed array?

Body:
This is an old thread, but I thought this might still be useful for anyone out there looking for an implementation. It doesn't take too much code; I did mine in ~100 lines of without any extra library like Hank Gay suggested. I called it a dictionary since it parallels (sort of) the python datatype. Here is the code:

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

typedef struct hollow_list hollow_list;

struct hollow_list{
    unsigned int size;
    void *value;
    bool *written;
    hollow_list *children;
};

//Creates a hollow list and allocates all of the needed memory
hollow_list hollow_list_create(unsigned int size){
    hollow_list output;
    output = (hollow_list) {.size = size, .value = (void *) 0, .written = calloc(size, sizeof(bool)), .children = calloc(size, sizeof(hollow_list))};
    return output;
}

//Frees all memory of associated with a hollow list and its children
void hollow_list_free(hollow_list *l, bool free_values){
    int i;
    for(i = 0; i < l->size; i++){
        hollow_list_free(l->children + i, free_values);
    }
    if(free_values){
        free(l->value);
    }
    free(l);
}

//Reads from the hollow list and returns a pointer to the item's data
void *hollow_list_read(hollow_list *l, unsigned int index){
    if(index == 0){
        return l->value;
    }
    unsigned int bit_checker;
    bit_checker = 1<<(l->size - 1);
    int i;
    for(i = 0; i < l->size; i++){
        if(bit_checker & index){
            if(l->written[i] == true){
                return hollow_list_read(l->children + i, bit_checker ^ index);
            } else {
                return (void *) 0;
            }
        }
        bit_checker >>= 1;
    }
}

//Writes to the hollow list, allocating memory only as it needs
void hollow_list_write(hollow_list *l, unsigned int index, void *value){
    if(index == 0){
        l->value = value;
    } else {
        unsigned int bit_checker;
        bit_checker = 1<<(l->size - 1);
        int i;
        for(i = 0; i < l->size; i++){
            if(bit_checker & index){
                if(!l->written[i]){
                    l->children[i] = hollow_list_create(l->size - i - 1);
                    l->written[i] = true;
                }
                hollow_list_write(l->children + i, bit_checker ^ index, value);
                break;
            }
            bit_checker >>= 1;
        }
    }
}

typedef struct dictionary dictionary;

struct dictionary{
    void *value;
    hollow_list *child;
};

dictionary dictionary_create(){
    dictionary output;
    output.child = malloc(sizeof(hollow_list));
    *output.child = hollow_list_create(8);
    output.value = (void *) 0;
    return output;
}

void dictionary_write(dictionary *dict, char *index, unsigned int strlen, void *value){
    void *hollow_list_value;
    dictionary *new_dict;
    int i;
    for(i = 0; i < strlen; i++){
        hollow_list_value = hollow_list_read(dict->child, (int) index[i]);
        if(hollow_list_value == (void *) 0){
            new_dict = malloc(sizeof(dictionary));
            *new_dict = dictionary_create();
            hollow_list_write(dict->child, (int) index[i], new_dict);
            dict = new_dict;
        } else {
            dict = (dictionary *) hollow_list_value;
        }
    }
    dict->value = value;
}

void *dictionary_read(dictionary *dict, char *index, unsigned int strlen){
    void *hollow_list_value;
    dictionary *new_dict;
    int i;
    for(i = 0; i < strlen; i++){
        hollow_list_value = hollow_list_read(dict->child, (int) index[i]);
        if(hollow_list_value == (void *) 0){
            return hollow_list_value;
        } else {
            dict = (dictionary *) hollow_list_value;
        }
    }
    return dict->value;
}

int main(){
    char index0[] = "hello, this is a test";
    char index1[] = "hello, this is also a test";
    char index2[] = "hello world";
    char index3[] = "hi there!";
    char index4[] = "this is something";
    char index5[] = "hi there";

    int item0 = 0;
    int item1 = 1;
    int item2 = 2;
    int item3 = 3;
    int item4 = 4;

    dictionary d;
    d = dictionary_create();
    dictionary_write(&d, index0, 21, &item0);
    dictionary_write(&d, index1, 26, &item1);
    dictionary_write(&d, index2, 11, &item2);
    dictionary_write(&d, index3, 13, &item3);
    dictionary_write(&d, index4, 17, &item4);

    printf("%d\n", *((int *) dictionary_read(&d, index0, 21)));
    printf("%d\n", *((int *) dictionary_read(&d, index1, 26)));
    printf("%d\n", *((int *) dictionary_read(&d, index2, 11)));
    printf("%d\n", *((int *) dictionary_read(&d, index3, 13)));
    printf("%d\n", *((int *) dictionary_read(&d, index4, 17)));
    printf("%d\n", ((int) dictionary_read(&d, index5, 8)));
}

Unfortunately you can't replicate the list[x] syntax, but this is the best alternative I have come up with.


问:
How to use multi-key words in the MSSQL (ANSISQL)
I know how to do in Oracle as following example code, however how can i do in ANSI SQL like MSSQL to do the same script, please help me to handle this question.

PS: this script is for multi-key words(PNO,CASENO,SCRN,IRBCODE,ITEMCODE,MMHCODE,ROWNO)

For example

```<code>SELECT * FROM TEST
WHERE (PNO,CASENO,SCRN,IRBCODE,ITEMCODE,MMHCODE,ROWNO)
IN
(
    SELECT PNO,CASENO,SCRN,IRBCODE,ITEMCODE,MMHCODE,ROWNO FROM TEST
    WHERE CASENO > 0 AND TO_CHAR(SCRN,'YYYY') = '2017'
)
</code>```

Please let me know if my question isn't very clear

答:
You can use EXISTS in any database:

```<code>SELECT t.*
FROM TEST t
WHERE EXISTS (SELECT 1
              FROM TEST t2
              WHERE t2.CASENO > 0 AND
                    YEAR(t2.SCRN) = 2017 AND
                    t2.PNO = t.PNO AND
                    t2.CASENO = t.CASE_NO AND
                    t2.SCRN = t.SCRN AND
                    t2.IRBCODE = t.IRBCODE AND
                    t2.ITEMCODE = t.ITEMCODE AND
                    t2.MMHCODE = t.MMHCODE AND
                    t2.ROWNO = t.ROWNO
             );
</code>```

Given that you are testing for being in the same table, I think the following does the same thing:

```<code>SELECT t.*
FROM TEST t
WHERE t.CASENO > 0 AND TO_CHAR(t.SCRN, 'YYYY') = '2017';
</code>```

Body:
I know how to do in Oracle as following example code, however how can i do in ANSI SQL like MSSQL to do the same script, please help me to handle this question.

PS: this script is for multi-key words(PNO,CASENO,SCRN,IRBCODE,ITEMCODE,MMHCODE,ROWNO)

For example

SELECT * FROM TEST
WHERE (PNO,CASENO,SCRN,IRBCODE,ITEMCODE,MMHCODE,ROWNO)
IN
(
    SELECT PNO,CASENO,SCRN,IRBCODE,ITEMCODE,MMHCODE,ROWNO FROM TEST
    WHERE CASENO > 0 AND TO_CHAR(SCRN,'YYYY') = '2017'
)

Please let me know if my question isn't very clear

Body:
You can use EXISTS in any database:

SELECT t.*
FROM TEST t
WHERE EXISTS (SELECT 1
              FROM TEST t2
              WHERE t2.CASENO > 0 AND
                    YEAR(t2.SCRN) = 2017 AND
                    t2.PNO = t.PNO AND
                    t2.CASENO = t.CASE_NO AND
                    t2.SCRN = t.SCRN AND
                    t2.IRBCODE = t.IRBCODE AND
                    t2.ITEMCODE = t.ITEMCODE AND
                    t2.MMHCODE = t.MMHCODE AND
                    t2.ROWNO = t.ROWNO
             );

Given that you are testing for being in the same table, I think the following does the same thing:

SELECT t.*
FROM TEST t
WHERE t.CASENO > 0 AND TO_CHAR(t.SCRN, 'YYYY') = '2017';


问:
Romanian diacritics in database
I'm inputting Romanian diacritics in some of my database fields and they are not showing up as expected.

Romanian diacritics are: Ă ă Â â Î î Ș ș Ț ț

The whole line above displays as: Ä‚ Äƒ Ã‚ Ã¢ ÃŽ Ã® È˜ È™ Èš È›

When I save a word containing ã it displays as Ã£

I'd like to know what collation should I set for the table for this to work

or

just stop using them all together and just save them as normal letters when they are inputed, in which case:

Inputing

ã would get saved as a

â would get saved as a

î would get saved as i

ș would get saved as s

ț would get saved as t

Any thoughts? I've tried setting multiple utf-8 as collation for the table, including utf_8_unicode_ci, as well as latin1 but that doesn't solve the problem.

Current collation set for the tables in question is utf_8_general_ci

Using MysQL.

Please do let me know in a comment if I left anything out and you require more details

答:
Set the table to utf16_unicode_ci, and that should do the trick.

I did a simple test with a table with 2 columns, one as utf8 and unicode, and another as utf_16 and unicode. The first column stores the data correctly, but is displays as in your question. The second column displays correctly, but only when the web page encoding is set to utf16 and unicode.

Title: Romanian diacritics in database


问:
AFrame light change not working
Running

document.querySelector("[light]").components.light.data.color="#A00";

Doesn't do anything, it will add color="#A00" if flushToDOM as an attribute but not change the light.

Changing light="color:#BBB" does work by hand, but what is the best way programmatically to do this now?

答:
Modifying the data object directly isn't supported - you'll want to use setAttribute instead. Example:

```<code>var lightEl = document.querySelector('[light]');
lightEl.setAttribute('light', {color: '#a00'});
</code>```

Title: AFrame light change not working

Body:
Modifying the data object directly isn't supported - you'll want to use setAttribute instead. Example:

var lightEl = document.querySelector('[light]');
lightEl.setAttribute('light', {color: '#a00'});


问:
How to render absoulute element inside ListView or FlatList?
Here's a fun one i've been poking at for while:

I have a FlatList (same issue with ListView) and I want to render an element INSIDE the internal scrolling container with the following characteristics:

Absolutely Positioned (thus having no effect on position of list elements)

Position XX distance from top (translateY or top)

zIndex (above list elements)

The use case is i'm rendering a day view calendar grid with a horizontal bar at the current time position fixed at X distance from the beginning of the internal scrollview so it appears as the user scrolls pass that position.

So far i've tried wrapping wrapping FlatList/ListView with another ScrollView... also tried rendering this element as the header element which only works while the header/footer are visible (trashed when out of view).

Any and all ideas welcomed. :)

Thanks

Screenshot Below (red bar is what i'm trying to render):

答:
Here's a working demo of what it sounds like you're trying to achieve: https://sketch.expo.io/BkreW1che. You can click "preview" to see it in your browser.

And here's the main code you need to measure the height of the ListView and place the indicator on top of it (visit the link above to see the full source):

```<code>  handleLayout(event) {
    const { y, height } = event.nativeEvent.layout;

    // Now we know how tall the ListView is; let's put the indicator in the middle.
    this.setState({ indicatorOffset: y + (height / 2) });
  }

  renderIndicator() {
    const { indicatorOffset } = this.state;

    // Once we know how tall the ListView is, put the indicator on top.
    return indicatorOffset ? (
      <View style={[{ position: 'absolute', left: 0, right: 0, top: indicatorOffset }]} />
    ) : null;
  }

  render() {
    return (
      <View style={styles.container}>
        <ListView
          onLayout={(event) => this.handleLayout(event)}
          dataSource={this.state.dataSource}
          renderRow={this.renderRow}
        />
        {this.renderIndicator()}
      </View>
    );
  }
</code>```

Edit: I now understand that you want the indicator to scroll along with the list. That's a simple change from above, just add an onScroll listener to the ListView: https://sketch.expo.io/HkEjDy92e

```<code>  handleScroll(event) {
    const { y } = event.nativeEvent.contentOffset;

    // Keep the indicator at the same position in the list using this offset.
    this.setState({ scrollOffset: y });
  },
</code>```

With this change, the indicator actually seems to lag behind a bit because of the delay in the onScroll callback.

If you want better performance, you might consider rendering the indicator as part of your renderRow method instead. For example, if you know the indicator should appear at 10:30 am, then you would render it right in the middle of your 10am row.

Body:
Here's a working demo of what it sounds like you're trying to achieve: https://sketch.expo.io/BkreW1che. You can click "preview" to see it in your browser.

And here's the main code you need to measure the height of the ListView and place the indicator on top of it (visit the link above to see the full source):

  handleLayout(event) {
    const { y, height } = event.nativeEvent.layout;

    // Now we know how tall the ListView is; let's put the indicator in the middle.
    this.setState({ indicatorOffset: y + (height / 2) });
  }

  renderIndicator() {
    const { indicatorOffset } = this.state;

    // Once we know how tall the ListView is, put the indicator on top.
    return indicatorOffset ? (
      <View style={[{ position: 'absolute', left: 0, right: 0, top: indicatorOffset }]} />
    ) : null;
  }

  render() {
    return (
      <View style={styles.container}>
        <ListView
          onLayout={(event) => this.handleLayout(event)}
          dataSource={this.state.dataSource}
          renderRow={this.renderRow}
        />
        {this.renderIndicator()}
      </View>
    );
  }

Edit: I now understand that you want the indicator to scroll along with the list. That's a simple change from above, just add an onScroll listener to the ListView: https://sketch.expo.io/HkEjDy92e

  handleScroll(event) {
    const { y } = event.nativeEvent.contentOffset;

    // Keep the indicator at the same position in the list using this offset.
    this.setState({ scrollOffset: y });
  },

With this change, the indicator actually seems to lag behind a bit because of the delay in the onScroll callback.

If you want better performance, you might consider rendering the indicator as part of your renderRow method instead. For example, if you know the indicator should appear at 10:30 am, then you would render it right in the middle of your 10am row.


问:
react native login username not find
can someone help me, i dont what will i do. this code always error if i setting the username and password. i'am a newbie, this my first work build app with react native

```<code>export default class Login extends Component {

   constructor(props) {
    super(props);
    this.state = {
     username: '',
     password: ''};
  }

  async loginAjax() {
    try {
      let response = await fetch('http://panel.erzap.com/web_services/login_json/new.json', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          erzap: {
            username: this.state.username,
            password: this.state.password,
            }
        })
      });
      let responseJson = await response.json();
      Alert.alert(responseJson.notice);
    } catch(error) {
      Alert.alert(error);
      console.error(error);
    }
  }
</code>```

enter image description here

答:
I edited my code and now it works perfectly.

<TouchableHighlight onPress={this.loginAjax.bind(this)}>
<Text style={styles.btn}>Login</Text>
</TouchableHighlight>```

Title: react native login username not find

Body:
can someone help me, i dont what will i do. this code always error if i setting the username and password. i'am a newbie, this my first work build app with react native

export default class Login extends Component {

   constructor(props) {
    super(props);
    this.state = {
     username: '',
     password: ''};
  }

  async loginAjax() {
    try {
      let response = await fetch('http://panel.erzap.com/web_services/login_json/new.json', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          erzap: {
            username: this.state.username,
            password: this.state.password,
            }
        })
      });
      let responseJson = await response.json();
      Alert.alert(responseJson.notice);
    } catch(error) {
      Alert.alert(error);
      console.error(error);
    }
  }

enter image description here


问:
Issues with DB after publishing via Database Publishing Wizard from MSFT
I work on quite a few DotNetNuke sites, and occasionally (I haven't figured out the common factor yet), when I use the Database Publishing Wizard from Microsoft to create scripts for the site I've created on my Dev server, after running the scripts at the host (usually GoDaddy.com), and uploading the site files, I get an error...  I'm 99.9% sure that it's not file related, so not sure where to begin in the DB.  Unfortunately with DotNetNuke you don't get the YSOD, but a generic error, with no real way to find the actual exception that has occured.

I'm just curious if anyone has had similar deployment issues using the Database Publishing Wizard, and if so, how they overcame them?  I own the RedGate toolset, but some hosts like GoDaddy don't allow you to direct connect to their servers...

答: Just read your follow up. In every case that I've had your problem, it was always something to do with the connection string in web.config. Even after hours of staring at it, it was always a connection string issue in web.config. Get up, take a walk and then come back.</p>

OwnerDisplayName: Purple Ant

OwnerDisplayName: AndrewDotHay


问:
How much low-level stuff to expose in an API?
When designing the public API of a generic library, how much of the low-level stuff that's used internally should be exposed?  On the one hand, users should not depend too heavily on implementation details, and too many low-level functions/classes might clutter the API.  Therefore, the knee-jerk response might be "none".  On the other hand, some of the low-level functionality might be useful to people, and exposing more of it can prevent abstraction inversion (the re-implementing of low-level constructs on top of high-level constructs).

Furthermore, exposing more low-level details could provide performance shortcuts.  For example, let's say you have a function to find the median of an array.  The principle of least surprise says that you should duplicate the array so that users of your API don't have to care that its implementation involves the side effect of reordering elements.  Should you, in this case, note that median() costs a memory allocation and provide another function that bypasses the allocation, but will arbitrarily reorder the user's input?

What are some general guidelines for how much of this kind of detail to expose?

答: The unix way of doing it is to provide mechanisms, not policies. Just provide the right tools to do things (say, a knife), but try not to anticipate how they are going to be used (to peel apples or to sharpen pencils).  </p>

OwnerDisplayName: dsimcha

OwnerDisplayName: PolyThinker


问:
How can a Windows program temporarily change its time zone?
I've written a function to return the time_t value corresponding to midnight on a given day. When there is no midnight for a given day, it returns the earliest time available; that situation can occur, for example, when Egypt enters daylight-saving time. This year, the time change takes effect at midnight on the night of April 29, so the clock goes directly from 23:59 to 01:00.

Now I'm writing unit tests for this function, and one of the tests should replicate the Egypt scenario. In Unix, I can accomplish it like this:

```<code>putenv("TZ", "Egypt", true);
tzset();
</code>```

After doing that, further calls to localtime behave as if they're in Egypt instead of Minnesota, and my tests pass. Merely setting the environment variable doesn't have any effect on Windows, though. What can I do to make the unit test think it's somewhere else without affecting the rest of the programs running on the system?

答:
Check out _putenv_s and _tzset. In theory, you should be able to set the TZ environment variable for your process with _putenv_s and then use _tzset to set the actual local time zone for your process to what the TZ environment variable is set to.

I know that this works on Linux with putenv and tzset, and from the documentation of _putenv_s and _tzset, it appears that you should be able to do the same with them on Windows. I haven't actually tried it though.

Body:
I've written a function to return the time_t value corresponding to midnight on a given day. When there is no midnight for a given day, it returns the earliest time available; that situation can occur, for example, when Egypt enters daylight-saving time. This year, the time change takes effect at midnight on the night of April 29, so the clock goes directly from 23:59 to 01:00.

Now I'm writing unit tests for this function, and one of the tests should replicate the Egypt scenario. In Unix, I can accomplish it like this:

putenv("TZ", "Egypt", true);
tzset();

After doing that, further calls to localtime behave as if they're in Egypt instead of Minnesota, and my tests pass. Merely setting the environment variable doesn't have any effect on Windows, though. What can I do to make the unit test think it's somewhere else without affecting the rest of the programs running on the system?


问:
How to check every 3rd element in a list and count the vowels in that string?
a.  Define a list of strings called wordlist. The list should contain at least 10 strings.

b.  Starting with the first element (i.e. element 0) check every 3rd element of the list in a loop, (i.e. 0th element, 3th element, 6th element, 9th element  … and so on) and count the number of vowels in that string.

c.  Print the string and the number of vowels in the strung with a suitable message.

d.  If the string contains 3 or more vowels, exit the loop (don’t need to check remaining elements).

e.  If you exited the loop  after finding a string with 3 or more vowels, print ‘Found string with 3 or more vowels!’; otherwise print “Did not find suitable string.”

EXAMPLE OUTPUT:

I am having trouble with part B if someone can guide me in the proper direction that would help

```<code>wordlist = ['hat' ,'bat' ,'cat','dog','bird','bear','lion','tiger','frog','mouse']
</code>```

答:
```<code>every_third_string = (string for i, string in enumerate(wordlist) if i % 3 == 0)
vowels = {'a': 0, 'e': 0, 'i': 0, 'o': 0 'u': 0}
for string in every_third_string:
    for char in string.lower():
        if char in vowels:
            vowels[char] += 1
</code>```

This sounds like your homework. Make sure to go through this carefully, line-by-line, and understand why it works.

For example, what happens if we omit if char in vowels?
What does i % 3 == 0 mean? What do we get if we try i % 3 == 1 instead?

Why is it important to use string.lower()?

Body:
a.  Define a list of strings called wordlist. The list should contain at least 10 strings.

b.  Starting with the first element (i.e. element 0) check every 3rd element of the list in a loop, (i.e. 0th element, 3th element, 6th element, 9th element  … and so on) and count the number of vowels in that string.

c.  Print the string and the number of vowels in the strung with a suitable message.

d.  If the string contains 3 or more vowels, exit the loop (don’t need to check remaining elements).

e.  If you exited the loop  after finding a string with 3 or more vowels, print ‘Found string with 3 or more vowels!’; otherwise print “Did not find suitable string.”

EXAMPLE OUTPUT:

I am having trouble with part B if someone can guide me in the proper direction that would help

wordlist = ['hat' ,'bat' ,'cat','dog','bird','bear','lion','tiger','frog','mouse']

Body:
every_third_string = (string for i, string in enumerate(wordlist) if i % 3 == 0)
vowels = {'a': 0, 'e': 0, 'i': 0, 'o': 0 'u': 0}
for string in every_third_string:
    for char in string.lower():
        if char in vowels:
            vowels[char] += 1

This sounds like your homework. Make sure to go through this carefully, line-by-line, and understand why it works.

For example, what happens if we omit if char in vowels?
What does i % 3 == 0 mean? What do we get if we try i % 3 == 1 instead?

Why is it important to use string.lower()?