问:
How to calculate weight to minimize variance?
given several vectors:

```<code>x1 = [3 4 6]
x2 = [2 8 1]
x3 = [5 5 4]
x4 = [6 2 1]
</code>```

I wanna find weight w1, w2, w3 to each item, and get the weighted sum of each vector: yi = w1*i1 + w2*i2 + w3*i3. for example, y1 = 3*w1 + 4*w2 + 6*w3
to make the variance of these values(y1, y2, y3, y4) to be minimized.

notice: w1, w2, w3 should > 0, and w1 + w2 + w3 = 1

I don't know what kind of problems it should be... and how to solve it in python or matlab?

答:
I don't know much about optimization problem, but I get the idea of gradient descent so I tried to reduce the weight between the max score and min score, my script is below:

```<code># coding: utf-8
import numpy as np
#7.72
#7.6
#8.26

def get_max(alist):
    max_score = max(alist)
    idx = alist.index(max_score)
    return max_score, idx

def get_min(alist):
    max_score = min(alist)
    idx = alist.index(max_score)
    return max_score, idx

def get_weighted(alist,aweight):
    res = []
    for i in range(0, len(alist)):
        res.append(alist[i]*aweight[i])
    return res

def get_sub(list1, list2):
    res = []
    for i in range(0, len(list1)):
        res.append(list1[i] - list2[i])
    return res

def grad_dec(w,dist, st = 0.001):
    max_item, max_item_idx = get_max(dist)
    min_item, min_item_idx = get_min(dist)
    w[max_item_idx] = w[max_item_idx] - st
    w[min_item_idx] = w[min_item_idx] + st

def cal_score(w, x):
    score = []
    print 'weight', w ,x
    for i in range(0, len(x)):
        score_i = 0
        for j in range(0,5):
            score_i = w[j]*x[i][j] + score_i
        score.append(score_i)
    # check variance is small enough
    print 'score', score
    return score

    # cal_score(w,x)

if __name__ == "__main__":
    init_w = [0.2, 0.2, 0.2, 0.2, 0.2, 0.2]
    x = [[7.3, 10, 8.3, 8.8, 4.2], [6.8, 8.9, 8.4, 9.7, 4.2], [6.9, 9.9, 9.7, 8.1, 6.7]]
    score = cal_score(init_w,x)
    variance = np.var(score)
    round = 0
    for round in range(0, 100):
        if variance < 0.012:
            print 'ok'
            break
        max_score, idx = get_max(score)
        min_score, idx2 = get_min(score)
        weighted_1 = get_weighted(x[idx], init_w)
        weighted_2 = get_weighted(x[idx2], init_w)
        dist = get_sub(weighted_1, weighted_2)
        # print max_score, idx, min_score, idx2, dist
        grad_dec(init_w, dist)
        score = cal_score(init_w, x)
        variance = np.var(score)
        print 'variance', variance

    print score
</code>```

In my practice it really can reduce the variance. I am very glad but I don't know whether my solution is solid in math.

Body:
given several vectors:

x1 = [3 4 6]
x2 = [2 8 1]
x3 = [5 5 4]
x4 = [6 2 1]

I wanna find weight w1, w2, w3 to each item, and get the weighted sum of each vector: yi = w1*i1 + w2*i2 + w3*i3. for example, y1 = 3*w1 + 4*w2 + 6*w3
to make the variance of these values(y1, y2, y3, y4) to be minimized.

notice: w1, w2, w3 should > 0, and w1 + w2 + w3 = 1

I don't know what kind of problems it should be... and how to solve it in python or matlab?

Body:
I don't know much about optimization problem, but I get the idea of gradient descent so I tried to reduce the weight between the max score and min score, my script is below:

# coding: utf-8
import numpy as np
#7.72
#7.6
#8.26

def get_max(alist):
    max_score = max(alist)
    idx = alist.index(max_score)
    return max_score, idx

def get_min(alist):
    max_score = min(alist)
    idx = alist.index(max_score)
    return max_score, idx

def get_weighted(alist,aweight):
    res = []
    for i in range(0, len(alist)):
        res.append(alist[i]*aweight[i])
    return res

def get_sub(list1, list2):
    res = []
    for i in range(0, len(list1)):
        res.append(list1[i] - list2[i])
    return res

def grad_dec(w,dist, st = 0.001):
    max_item, max_item_idx = get_max(dist)
    min_item, min_item_idx = get_min(dist)
    w[max_item_idx] = w[max_item_idx] - st
    w[min_item_idx] = w[min_item_idx] + st

def cal_score(w, x):
    score = []
    print 'weight', w ,x
    for i in range(0, len(x)):
        score_i = 0
        for j in range(0,5):
            score_i = w[j]*x[i][j] + score_i
        score.append(score_i)
    # check variance is small enough
    print 'score', score
    return score

    # cal_score(w,x)

if __name__ == "__main__":
    init_w = [0.2, 0.2, 0.2, 0.2, 0.2, 0.2]
    x = [[7.3, 10, 8.3, 8.8, 4.2], [6.8, 8.9, 8.4, 9.7, 4.2], [6.9, 9.9, 9.7, 8.1, 6.7]]
    score = cal_score(init_w,x)
    variance = np.var(score)
    round = 0
    for round in range(0, 100):
        if variance < 0.012:
            print 'ok'
            break
        max_score, idx = get_max(score)
        min_score, idx2 = get_min(score)
        weighted_1 = get_weighted(x[idx], init_w)
        weighted_2 = get_weighted(x[idx2], init_w)
        dist = get_sub(weighted_1, weighted_2)
        # print max_score, idx, min_score, idx2, dist
        grad_dec(init_w, dist)
        score = cal_score(init_w, x)
        variance = np.var(score)
        print 'variance', variance

    print score

In my practice it really can reduce the variance. I am very glad but I don't know whether my solution is solid in math.


来源: stackexchange

问:
Jquery check for integer?
I have this code:

```<code>    jQuery(function( $ ){

    // If no speed is set (when loading the page) set default speed

    if (!$moveSpeed) {
        var $moveSpeed = 4000;
    }

    // Move the damn autocue

 $('a.goDown').click(function(){
        alert($moveSpeed);
  $.scrollTo('#footer', $moveSpeed);
  return false;
 });

    $('a.goUp').click(function(){
        alert($moveSpeed);
  $.scrollTo('#header', $moveSpeed);
  return false;
 });

    // Speed settings for autocue

    $('a.changeSpeed').click(function(){
  $moveSpeed = $(this).attr('speed');
  return false;
 });
});

</script>
</code>```

and if the changeSpeed is clicked, the alert box shows it is changed to the given number but it aint an integer, is there a way to convert a variable in to an integer?

thx :)

答:
I don't think it's the actual problem you're having, so I'm making this answer a CW, but FYI:

```<code>jQuery(function( $ ){

    // If no speed is set (when loading the page) set default speed

    if (!$moveSpeed) {
        var $moveSpeed = 4000;
    }
</code>```

That if statement is completely non-functional, the body of it is always run. The !$moveSpeed condition will always be true. This is because var declares a variable within the current function, regardless of where the var statement actually is or whether it's inside a condition or loop. More details in this article, but basically the interpreter sees that code like this:

```<code>jQuery(function( $ ){
    var $moveSpeed;

    // If no speed is set (when loading the page) set default speed

    if (!$moveSpeed) {
        $moveSpeed = 4000;
    }
</code>```

...and since the value of a variable that isn't initialized yet is undefined, and !undefined is true, you'll always set $moveSpeed to 4000.

ContentLicense: CC BY-SA 2.5

Title: Jquery check for integer?

Body:
I have this code:

    jQuery(function( $ ){

    // If no speed is set (when loading the page) set default speed

    if (!$moveSpeed) {
        var $moveSpeed = 4000;
    }

    // Move the damn autocue

 $('a.goDown').click(function(){
        alert($moveSpeed);
  $.scrollTo('#footer', $moveSpeed);
  return false;
 });

    $('a.goUp').click(function(){
        alert($moveSpeed);
  $.scrollTo('#header', $moveSpeed);
  return false;
 });

    // Speed settings for autocue

    $('a.changeSpeed').click(function(){
  $moveSpeed = $(this).attr('speed');
  return false;
 });
});

</script>

and if the changeSpeed is clicked, the alert box shows it is changed to the given number but it aint an integer, is there a way to convert a variable in to an integer?

thx :)

Body:
I don't think it's the actual problem you're having, so I'm making this answer a CW, but FYI:

jQuery(function( $ ){

    // If no speed is set (when loading the page) set default speed

    if (!$moveSpeed) {
        var $moveSpeed = 4000;
    }

That if statement is completely non-functional, the body of it is always run. The !$moveSpeed condition will always be true. This is because var declares a variable within the current function, regardless of where the var statement actually is or whether it's inside a condition or loop. More details in this article, but basically the interpreter sees that code like this:

jQuery(function( $ ){
    var $moveSpeed;

    // If no speed is set (when loading the page) set default speed

    if (!$moveSpeed) {
        $moveSpeed = 4000;
    }

...and since the value of a variable that isn't initialized yet is undefined, and !undefined is true, you'll always set $moveSpeed to 4000.


问:
Facebook share shows 404 page not found
While sharing the following link https://cargo2share.com/ru/blog/aerophobia in facebook I am getting 404 page not found preview. When I share it in Google+, Vk.com or in another networks it shows the correct page and image in preview. Any ideas?

答:
try this:</p>

```<code><a href="http://www.facebook.com/share.php?u=https://cargo2share.com/ru/blog/aerophobia&title=[YOUR TITLE HERE]">facebook share</a>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Facebook share shows 404 page not found

Body:
try this:

<a href="http://www.facebook.com/share.php?u=https://cargo2share.com/ru/blog/aerophobia&title=[YOUR TITLE HERE]">facebook share</a>


问:
Checking if part of the elements of a list are repeated
I have a list that I am filling up in the following way:

```<code>complete = []
for (i,j) in list:
    complete.append('%s %s %s'%(i,j,R[i,j]))
</code>```

The list has (as an example) the following elements:

```<code>complete = ['B A 1', 'A H 1', 'P B 1', 'H B 1', 'B W 1', 'B M 9', 'M R 9', 'R P 9', 'P A 9', 'C S 7', 'B C 7', 'B A 7', 'A H 7', 'B P 7', 'M B 7', 'P B 7', 'H B 7']
</code>```

I want to check which letters are repeated, and on that case add the numbers corresponding to them.
On this example, (B A) is repeated with 1 and 7, so one of the outputs would have to be 'B A 8'.

I could also change the way I am appending the elements to complete, but I do not know how other way.

Thanks!

答:
You can try this:

```<code>from collections import Counter, defaultdict
complete =  ['ASO BAIS 1', 'HEL CIO 5']

d = Counter([i[:-1] for i in complete])

new_d = defaultdict(int)

for i in complete:
   if d[i[:-1]] > 0:
     new_d[i[:-1]] += int(i[-1])

print(dict(new_d))
#maximum value:
maximum = max(new_d.values())
print(maximum)
</code>```

Output:

```<code>{'HEL CIO ': 5, 'ASO BAIS ': 1}
</code>```

Body:
I have a list that I am filling up in the following way:

complete = []
for (i,j) in list:
    complete.append('%s %s %s'%(i,j,R[i,j]))

The list has (as an example) the following elements:

complete = ['B A 1', 'A H 1', 'P B 1', 'H B 1', 'B W 1', 'B M 9', 'M R 9', 'R P 9', 'P A 9', 'C S 7', 'B C 7', 'B A 7', 'A H 7', 'B P 7', 'M B 7', 'P B 7', 'H B 7']

I want to check which letters are repeated, and on that case add the numbers corresponding to them.
On this example, (B A) is repeated with 1 and 7, so one of the outputs would have to be 'B A 8'.

I could also change the way I am appending the elements to complete, but I do not know how other way.

Thanks!

Body:
You can try this:

from collections import Counter, defaultdict
complete =  ['ASO BAIS 1', 'HEL CIO 5']

d = Counter([i[:-1] for i in complete])

new_d = defaultdict(int)

for i in complete:
   if d[i[:-1]] > 0:
     new_d[i[:-1]] += int(i[-1])

print(dict(new_d))
#maximum value:
maximum = max(new_d.values())
print(maximum)

Output:

{'HEL CIO ': 5, 'ASO BAIS ': 1}


问:
Android Studio - Error:Process 'command '/home/draven/Downloads/android-studio/jre/bin/java'' finished with non-zero exit value 2
After trying about 5 or 6 accepted answers on here and also trying a few of my own, i have done everything i know how from a fresh install to deleting the .gradle folder to changing the dex options in build.gradle and after every time i get this error:

Error:Process 'command '/home/draven/Downloads/android-studio/jre/bin/java'' finished with non-zero exit value 2

Im sorry for a lack of information as i am a bit frustrated, but i will give all relevant information needed.

Log:
Pastebin of the Log

Here is  a screenshot of the error, the IDE is a fresh install.

Screenshot of the IDE

答: For default, android studio use a embedded java, you can try change it for a external one, in file -> project structure -> sdk location section -> jdk location. That worked for me. Regards! </p>


问:
Marquee is not working when seek bar gets updated
I'm making a music player and have implemented a marquee for the song and artist name. But as soon as the seek bar gets updated, the text view comes back to the original position. So in this way, a kind of back and forth motion of text is seen.

Here is my XML code:

```<code>  <?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      android:id="@+id/mainFullPlayerContainer"
      android:layout_width="match_parent"
      android:layout_height="match_parent"

   tools:context="com.musicplayer.integrated.sanket.music.MainFullPlayer"
    android:background="@color/defaultBackground">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/relativeLayout"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true">

    <ImageView
        android:id="@+id/imageView_full_player_more"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="20dp"
        android:layout_marginRight="15dp"
        app:srcCompat="@drawable/icon_more" />
</RelativeLayout>

<ImageView
    android:id="@+id/imageView_full_player_album_art"
    android:layout_width="300dp"
    android:layout_height="300dp"
    app:srcCompat="@drawable/default_album_art"
    android:layout_marginTop="29dp"
    android:layout_below="@+id/relativeLayout"
    android:layout_centerHorizontal="true" />

<SeekBar
    android:id="@+id/seekBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:progressTint="@color/defaultTextColor"
    android:thumbTint="@color/defaultTextColor"
    android:layout_above="@+id/imageView_full_player_play"

    android:layout_marginBottom="37dp" />

<ImageView
    android:id="@+id/imageView_full_player_play"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="31dp"
    app:srcCompat="@drawable/icon_play_small" />

<ImageView
    android:id="@+id/imageView_full_player_next"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/imageView_full_player_play"
    android:layout_marginStart="39dp"
    android:layout_toEndOf="@+id/imageView_full_player_play"
    app:srcCompat="@drawable/icon_fast_next_small" />

<ImageView
    android:id="@+id/imageView_full_player_prev"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/imageView_full_player_play"
    android:layout_marginEnd="38dp"
    android:layout_toStartOf="@+id/imageView_full_player_play"
    app:srcCompat="@drawable/icon_rewind_prev_small" />

<TextView
    android:id="@+id/textView_full_player_song"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/imageView_full_player_album_art"
    android:layout_alignStart="@+id/imageView_full_player_album_art"
    android:layout_below="@+id/imageView_full_player_album_art"
    android:layout_marginTop="12dp"
    android:ellipsize="marquee"
    android:focusable="true"
    android:marqueeRepeatLimit="marquee_forever"
    android:scrollHorizontally="true"
    android:singleLine="true"
    android:text="Song Name"
    android:textAlignment="center"
    android:textColor="@color/defaultTextColor"
    android:textSize="18sp" />

<TextView
    android:id="@+id/textView_current_time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0:00"
    android:textColor="@color/defaultTextColor"
    android:textSize="12sp"

    android:layout_marginBottom="18dp"
    android:layout_above="@+id/imageView_full_player_prev"
    android:layout_alignStart="@+id/textView_full_player_artist" />

<TextView
    android:id="@+id/textView_total_length"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="5:00"
    android:textSize="12sp"
    android:textColor="@color/defaultTextColor"
    android:layout_alignBaseline="@+id/textView_current_time"
    android:layout_alignBottom="@+id/textView_current_time"
    android:layout_alignEnd="@+id/textView_full_player_artist" />

<TextView
    android:id="@+id/textView_full_player_artist"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/textView_full_player_song"
    android:layout_alignStart="@+id/textView_full_player_song"
    android:layout_below="@+id/textView_full_player_song"
    android:layout_marginTop="12dp"
    android:text="Artist"
    android:textAlignment="center"
    android:textColor="@color/defaultTextColor"
    android:textSize="15sp"
    android:ellipsize="marquee"
    android:singleLine="true"
    android:marqueeRepeatLimit="marquee_forever"
    android:focusable="true"
    android:scrollHorizontally="true"
    />

  </RelativeLayout>
</code>```

Here is my Java code:

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

 private static RelativeLayout  fullPlayer;
 private static ImageView fullPlayer_play , fullPlayer_next ,
 fullPlayer_prev,fullPlayer_album;
 private static TextView fullPlayer_song , fullPlayer_artist ,
 fullPlayer_currentTime , fullPlayer_maxTime;
 private    static SeekBar seekBar;
 private Songs song;
 private static Handler progressHandler;
 private static Runnable   progressRunnable;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_full_player);
    fullPlayer = (RelativeLayout)findViewById(R.id.mainFullPlayerContainer);
    fullPlayer_play = (ImageView)findViewById(R.id.imageView_full_player_play);
    fullPlayer_next = (ImageView)findViewById(R.id.imageView_full_player_next);
    fullPlayer_prev = (ImageView)findViewById(R.id.imageView_full_player_prev);
    fullPlayer_album = (ImageView)findViewById(R.id.imageView_full_player_album_art);
    fullPlayer_song = (TextView)findViewById(R.id.textView_full_player_song);
    fullPlayer_artist = (TextView)findViewById(R.id.textView_full_player_artist);
    fullPlayer_currentTime = (TextView)findViewById(R.id.textView_current_time);
    fullPlayer_maxTime = (TextView)findViewById(R.id.textView_total_length);

    fullPlayer_maxTime.setText(MusicPlayback.getTime(MusicPlayback.mediaPlayer.getDuration()));

    seekBar = (SeekBar)findViewById(R.id.seekBar);

    song = MusicPlayback.allTracks.get(MusicPlayback.songPosition);
    fullPlayer_song.setSelected(true);
    fullPlayer_artist.setSelected(true);
    fullPlayer_song.setText(song.getSongName());
    fullPlayer_artist.setText(song.getArtist());

    if(MusicPlayback.getPlayingStatus()){
        fullPlayer_play.setImageResource(R.drawable.icon_pause_small);
    }
    else
    {
        fullPlayer_play.setImageResource(R.drawable.icon_play_small);
    }
    if(song.getAlbumArt()!= null){

        fullPlayer_album.setImageURI(Uri.parse(song.getAlbumArt()));
        fullPlayer.setBackground(FragmentAllTracks.d);
    }
    else{
        fullPlayer_album.setImageResource(R.drawable.default_album_art);
        fullPlayer.setBackgroundColor(Color.argb(255, 48, 48, 48));

    }
seekBar.setMax(MusicPlayback.mediaPlayer.getDuration());

    progressHandler = new Handler();

    progressRunnable = new Runnable() {
        @Override
        public void run() {
            seekBar.setProgress(MusicPlayback.mediaPlayer.getCurrentPosition());
            fullPlayer_currentTime.setText(MusicPlayback.getTime(MusicPlayback.mediaPlayer.getCurrentPosition()));

            progressHandler.postDelayed(progressRunnable,100);
        }
    };
    progressHandler.postDelayed(progressRunnable,100);
}

@Override
public void onBackPressed() {
    super.onBackPressed();
  this.overridePendingTransition(R.anim.left_exit_translate,R.anim.right_exit_translate);

}
}
</code>```

Here is the result:

答:
I think its because of focus. Please set your textview like this

```<code><TextView
    android:id="@+id/textView_full_player_song"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/imageView_full_player_album_art"
    android:layout_alignStart="@+id/imageView_full_player_album_art"
    android:layout_below="@+id/imageView_full_player_album_art"
    android:layout_marginTop="12dp"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:marqueeRepeatLimit ="marquee_forever"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:scrollHorizontally="true"
    android:text="Song Name"
    android:textAlignment="center"
    android:textColor="@color/defaultTextColor"
    android:textSize="18sp" />
</code>```

add this your TextView,

```<code>android:focusable="true"
android:focusableInTouchMode="true"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm making a music player and have implemented a marquee for the song and artist name. But as soon as the seek bar gets updated, the text view comes back to the original position. So in this way, a kind of back and forth motion of text is seen.

Here is my XML code:

  <?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      android:id="@+id/mainFullPlayerContainer"
      android:layout_width="match_parent"
      android:layout_height="match_parent"

   tools:context="com.musicplayer.integrated.sanket.music.MainFullPlayer"
    android:background="@color/defaultBackground">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/relativeLayout"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true">

    <ImageView
        android:id="@+id/imageView_full_player_more"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="20dp"
        android:layout_marginRight="15dp"
        app:srcCompat="@drawable/icon_more" />
</RelativeLayout>

<ImageView
    android:id="@+id/imageView_full_player_album_art"
    android:layout_width="300dp"
    android:layout_height="300dp"
    app:srcCompat="@drawable/default_album_art"
    android:layout_marginTop="29dp"
    android:layout_below="@+id/relativeLayout"
    android:layout_centerHorizontal="true" />

<SeekBar
    android:id="@+id/seekBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:progressTint="@color/defaultTextColor"
    android:thumbTint="@color/defaultTextColor"
    android:layout_above="@+id/imageView_full_player_play"

    android:layout_marginBottom="37dp" />

<ImageView
    android:id="@+id/imageView_full_player_play"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="31dp"
    app:srcCompat="@drawable/icon_play_small" />

<ImageView
    android:id="@+id/imageView_full_player_next"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/imageView_full_player_play"
    android:layout_marginStart="39dp"
    android:layout_toEndOf="@+id/imageView_full_player_play"
    app:srcCompat="@drawable/icon_fast_next_small" />

<ImageView
    android:id="@+id/imageView_full_player_prev"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/imageView_full_player_play"
    android:layout_marginEnd="38dp"
    android:layout_toStartOf="@+id/imageView_full_player_play"
    app:srcCompat="@drawable/icon_rewind_prev_small" />

<TextView
    android:id="@+id/textView_full_player_song"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/imageView_full_player_album_art"
    android:layout_alignStart="@+id/imageView_full_player_album_art"
    android:layout_below="@+id/imageView_full_player_album_art"
    android:layout_marginTop="12dp"
    android:ellipsize="marquee"
    android:focusable="true"
    android:marqueeRepeatLimit="marquee_forever"
    android:scrollHorizontally="true"
    android:singleLine="true"
    android:text="Song Name"
    android:textAlignment="center"
    android:textColor="@color/defaultTextColor"
    android:textSize="18sp" />

<TextView
    android:id="@+id/textView_current_time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0:00"
    android:textColor="@color/defaultTextColor"
    android:textSize="12sp"

    android:layout_marginBottom="18dp"
    android:layout_above="@+id/imageView_full_player_prev"
    android:layout_alignStart="@+id/textView_full_player_artist" />

<TextView
    android:id="@+id/textView_total_length"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="5:00"
    android:textSize="12sp"
    android:textColor="@color/defaultTextColor"
    android:layout_alignBaseline="@+id/textView_current_time"
    android:layout_alignBottom="@+id/textView_current_time"
    android:layout_alignEnd="@+id/textView_full_player_artist" />

<TextView
    android:id="@+id/textView_full_player_artist"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/textView_full_player_song"
    android:layout_alignStart="@+id/textView_full_player_song"
    android:layout_below="@+id/textView_full_player_song"
    android:layout_marginTop="12dp"
    android:text="Artist"
    android:textAlignment="center"
    android:textColor="@color/defaultTextColor"
    android:textSize="15sp"
    android:ellipsize="marquee"
    android:singleLine="true"
    android:marqueeRepeatLimit="marquee_forever"
    android:focusable="true"
    android:scrollHorizontally="true"
    />

  </RelativeLayout>

Here is my Java code:

public class MainFullPlayer extends AppCompatActivity {

 private static RelativeLayout  fullPlayer;
 private static ImageView fullPlayer_play , fullPlayer_next ,
 fullPlayer_prev,fullPlayer_album;
 private static TextView fullPlayer_song , fullPlayer_artist ,
 fullPlayer_currentTime , fullPlayer_maxTime;
 private    static SeekBar seekBar;
 private Songs song;
 private static Handler progressHandler;
 private static Runnable   progressRunnable;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_full_player);
    fullPlayer = (RelativeLayout)findViewById(R.id.mainFullPlayerContainer);
    fullPlayer_play = (ImageView)findViewById(R.id.imageView_full_player_play);
    fullPlayer_next = (ImageView)findViewById(R.id.imageView_full_player_next);
    fullPlayer_prev = (ImageView)findViewById(R.id.imageView_full_player_prev);
    fullPlayer_album = (ImageView)findViewById(R.id.imageView_full_player_album_art);
    fullPlayer_song = (TextView)findViewById(R.id.textView_full_player_song);
    fullPlayer_artist = (TextView)findViewById(R.id.textView_full_player_artist);
    fullPlayer_currentTime = (TextView)findViewById(R.id.textView_current_time);
    fullPlayer_maxTime = (TextView)findViewById(R.id.textView_total_length);

    fullPlayer_maxTime.setText(MusicPlayback.getTime(MusicPlayback.mediaPlayer.getDuration()));

    seekBar = (SeekBar)findViewById(R.id.seekBar);

    song = MusicPlayback.allTracks.get(MusicPlayback.songPosition);
    fullPlayer_song.setSelected(true);
    fullPlayer_artist.setSelected(true);
    fullPlayer_song.setText(song.getSongName());
    fullPlayer_artist.setText(song.getArtist());

    if(MusicPlayback.getPlayingStatus()){
        fullPlayer_play.setImageResource(R.drawable.icon_pause_small);
    }
    else
    {
        fullPlayer_play.setImageResource(R.drawable.icon_play_small);
    }
    if(song.getAlbumArt()!= null){

        fullPlayer_album.setImageURI(Uri.parse(song.getAlbumArt()));
        fullPlayer.setBackground(FragmentAllTracks.d);
    }
    else{
        fullPlayer_album.setImageResource(R.drawable.default_album_art);
        fullPlayer.setBackgroundColor(Color.argb(255, 48, 48, 48));

    }
seekBar.setMax(MusicPlayback.mediaPlayer.getDuration());

    progressHandler = new Handler();

    progressRunnable = new Runnable() {
        @Override
        public void run() {
            seekBar.setProgress(MusicPlayback.mediaPlayer.getCurrentPosition());
            fullPlayer_currentTime.setText(MusicPlayback.getTime(MusicPlayback.mediaPlayer.getCurrentPosition()));

            progressHandler.postDelayed(progressRunnable,100);
        }
    };
    progressHandler.postDelayed(progressRunnable,100);
}

@Override
public void onBackPressed() {
    super.onBackPressed();
  this.overridePendingTransition(R.anim.left_exit_translate,R.anim.right_exit_translate);

}
}

Here is the result:

Body:
I think its because of focus. Please set your textview like this

<TextView
    android:id="@+id/textView_full_player_song"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/imageView_full_player_album_art"
    android:layout_alignStart="@+id/imageView_full_player_album_art"
    android:layout_below="@+id/imageView_full_player_album_art"
    android:layout_marginTop="12dp"
    android:singleLine="true"
    android:ellipsize="marquee"
    android:marqueeRepeatLimit ="marquee_forever"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:scrollHorizontally="true"
    android:text="Song Name"
    android:textAlignment="center"
    android:textColor="@color/defaultTextColor"
    android:textSize="18sp" />

add this your TextView,

android:focusable="true"
android:focusableInTouchMode="true"


问:
Selenium java does not open the firefox web page
this is my code

```<code>    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.google.com");
    WebElement searchBox = driver.findElement(By.name("q"));
    searchBox.sendKeys("Packt Publishing");
    searchBox.submit();
</code>```

these are my imports:

```<code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
</code>```

(i don't know why here it puts them in the same line)

What it does is that it opens a new firefox page with an empty tab ... what's wrong?
I looked for other people in this site with the same problem and I did not find an answer.

答:
While you work with Selenium 3.4.0 and geckodriver v0.17.0 and Mozilla Firefox 53.0, you have to download and save geckodriver in your system and provide the absolute path of the geckodriver in your code. You can consider to use the following code block to initiate  Google Search by calling submit() method:

```<code>    System.setProperty("webdriver.gecko.driver", "C:\\your_directory\\geckodriver.exe");
    WebDriver driver = new FirefoxDriver();
    driver.get("https://google.com");
    driver.findElement(By.name("q")).clear();
    driver.findElement(By.name("q")).sendKeys("Packt Publishing");
    // CASE C : Submitting the Search String through submit()
    driver.findElement(By.xpath("//input[@value='Google Search']")).submit();
</code>```

Let me know if this Answers your Question.

Body:
this is my code

    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.google.com");
    WebElement searchBox = driver.findElement(By.name("q"));
    searchBox.sendKeys("Packt Publishing");
    searchBox.submit();

these are my imports:

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

(i don't know why here it puts them in the same line)

What it does is that it opens a new firefox page with an empty tab ... what's wrong?
I looked for other people in this site with the same problem and I did not find an answer.

Body:
While you work with Selenium 3.4.0 and geckodriver v0.17.0 and Mozilla Firefox 53.0, you have to download and save geckodriver in your system and provide the absolute path of the geckodriver in your code. You can consider to use the following code block to initiate  Google Search by calling submit() method:

    System.setProperty("webdriver.gecko.driver", "C:\\your_directory\\geckodriver.exe");
    WebDriver driver = new FirefoxDriver();
    driver.get("https://google.com");
    driver.findElement(By.name("q")).clear();
    driver.findElement(By.name("q")).sendKeys("Packt Publishing");
    // CASE C : Submitting the Search String through submit()
    driver.findElement(By.xpath("//input[@value='Google Search']")).submit();

Let me know if this Answers your Question.


问:
Table is goin outta div
I have div with table

Here is code

```<code><div id="container" style="width: 100%; height: 700px;margin-top: 85px; white-space: nowrap;">
<div style="float: left;width: 80%; table-layout: fixed;">
    <table class="table" style="width: 80%;border-style: solid;border-color: #1d69b4;border-radius: 10px;border-collapse: separate">
        <tr>
            <th style="font-size: 18px; text-align: center;">
                <b>Hours</b><b style="padding-left: 30px;"> Monday</b>
            </th>
            <th style="font-size: 20px; text-align: center;">
                <b>Hours</b><b style="padding-left: 30px;"> Tuesday</b>
            </th>
            <th style="font-size: 20px; text-align: center;">
                <b>Hours</b><b style="padding-left: 30px;"> Wednesday</b>
            </th>
            <th style="font-size: 20px; text-align: center;">
                <b>Hours</b><b style="padding-left: 30px;">  Thursday</b>
            </th>
            <th style="font-size: 20px; text-align: center;">
                <b>Hours</b><b style="padding-left: 30px;">  Friday</b>
            </th>
            <th style="font-size: 20px; text-align: center;">
                <b>Hours</b><b style="padding-left: 30px;"> Saturday</b>
            </th>
            <th style="font-size: 20px; text-align: center;">
                <b>Hours</b><b style="padding-left: 30px;"> Sunday</b>
            </th>
         </tr>
        <tr>

          </tr>
    </table>
 </div>
</code>```

My problem is table getting outta div

I try to use table-layout: fixed; but it seems not works.

Where is my mistake?

Thank's for help.

答:
The content of your table cells is pushing the width of the table, which is why it cannot obey the width you set. You can easily see this by playing with the th font size in this example:

#container {
  border: 1px solid red;
  width: 100%;
  height: 700px;
  margin-top: 85px;
}

#container div {
  border: 1px solid blue;
  float: left;
  width: 80%;
}

table {
  border: 3px solid #1d69b4;
  border-radius: 10px;
  border-collapse: separate;
  display: block;
}

th {
  font-size: 12px;
  text-align: center;
  border: 1px solid green;
}

.pad-left {
  padding-left: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div>
    <table>
       <tr>
         <th>Hours Monday</th>
         <th>Hours Tuesday</th>
         <th>Hours Wednesday</th>
         <th>Hours Thursday</th>
         <th>Hours Friday</th>
         <th>Hours Saturday</th>
         <th>Hours Sunday</th>
       </tr>
     </table>
   </div>
 </div></code>```

Solution: adjust your content or your styling so it will fit your table.

Title: Table is goin outta div

Body:
I have div with table

Here is code

                Hours Monday

                Hours Tuesday

                Hours Wednesday

                Hours  Thursday

                Hours  Friday

                Hours Saturday

                Hours Sunday

My problem is table getting outta div

I try to use table-layout: fixed; but it seems not works.

Where is my mistake?

Thank's for help.

Body:
The content of your table cells is pushing the width of the table, which is why it cannot obey the width you set. You can easily see this by playing with the th font size in this example:

#container {
  border: 1px solid red;
  width: 100%;
  height: 700px;
  margin-top: 85px;
}

#container div {
  border: 1px solid blue;
  float: left;
  width: 80%;
}

table {
  border: 3px solid #1d69b4;
  border-radius: 10px;
  border-collapse: separate;
  display: block;
}

th {
  font-size: 12px;
  text-align: center;
  border: 1px solid green;
}

.pad-left {
  padding-left: 30px;
}

<div id="container">
  <div>
    <table>
       <tr>
         <th>Hours Monday</th>
         <th>Hours Tuesday</th>
         <th>Hours Wednesday</th>
         <th>Hours Thursday</th>
         <th>Hours Friday</th>
         <th>Hours Saturday</th>
         <th>Hours Sunday</th>
       </tr>
     </table>
   </div>
 </div>

Solution: adjust your content or your styling so it will fit your table.


问:
recursive return type
I just browsed through Mark Probst's diploma thesis and stumpled over the following code:

```<code>typedef void* cont(void);

for (;;)
{
    cp = (cont*)(*cp)();
}
</code>```

I'm pretty sure the cast should read (cont), not (cont*), because he explains:

The function wishing to do a proper tail call returns the address of the function to be called

And cont is already a pointer-to-function type. So let's change that line to:

```<code>    cp = (cont)(*cp)();
</code>```

Now I was wondering, how can we get rid of the cast? Can cont be defined so it returns a cont? How would the typedef for cont look like? Do we need a helper type to achieve this? Is it impossible?

答:
No, typedef void* cont(void); cont defines a function type returning a void *. I think you are confusing it with typedef void (*cont)(void); or typedef void *(*cont)(void);.

I don't believe that it's possible to eliminate the need for a cast in this scenario but I'm open to be convinced otherwise.

Title: recursive return type

Body:
I just browsed through Mark Probst's diploma thesis and stumpled over the following code:

typedef void* cont(void);

for (;;)
{
    cp = (cont*)(*cp)();
}

I'm pretty sure the cast should read (cont), not (cont*), because he explains:

The function wishing to do a proper tail call returns the address of the function to be called

And cont is already a pointer-to-function type. So let's change that line to:

    cp = (cont)(*cp)();

Now I was wondering, how can we get rid of the cast? Can cont be defined so it returns a cont? How would the typedef for cont look like? Do we need a helper type to achieve this? Is it impossible?


问:
PHP - Add leading zeros to number but keep maximum length
I have an Auto-Increment field in a database.

I want these numbers to be prepended by zeros, to a maximum length of seven.

Example:

Original number: 1  Desired result: 0000001

or

Original number 768 Desired result 0000768

How would I achieve this in PHP?

答:
sprintf has this build in:</p>

```<code>$number = sprintf("%07d", $input)
</code>```

Body:
sprintf has this build in:

$number = sprintf("%07d", $input)


问:
creating view models for models with one to many relationship in asp.net mvc
I Created two models name as Company and Agent and There should be a one to many relationship between them because each company could have many Agents but each agent is related to one company. These Models are as follow:

```<code>    Public class Company
    {
    Public int ComapnyId {get;set;}
    Public String CompanyName{get;set;}
    Public String tell{get;set;}
    Public String Address{get;set;}
    Public virtual ICollection<Agent> Agents {get;set;}
    }

    Public Class Agent
    {
    Public int AgentId{get;set;}
    public string FName{get;set;}
    public string LName{get;set;}
    public string Mobile{get;set;}
    public int? CompanyId{get;set;}
    [ForeignKey("CompanyId")]
    public virtual Company company{get;set;}
    }
</code>```

then I create View Models as follow, but I am not sure I defined them correctly to satisfy my goal.

```<code>     public Class CompanyViewModel
     {
     Public int ComapnyId {get;set;}
     Public String CompanyName{get;set;}
     Public String tell{get;set;}
     Public String Address{get;set;}
     Public List<AgentViewModel> AgentsName {get;set;}
     }

     Public AgentViewModel
     {
     Public int AgentId{get;set;}
     public string FName{get;set;}
     public string LName{get;set;}
     public string Mobile{get;set;}
     public int? CompanyId{get;set;}
     [ForeignKey("CompanyId")]
     public string CompanyName{get;set;}
     }
</code>```

Indeed I want when user wants to create an agent display him all companies in a drop down list. I have so many question about it but the first one is two properties of

```<code>      Public List<AgentViewModel> AgentsName {get;set;} and
      public string CompanyName{get;set;}
</code>```

defined correctly in viewmodels for my goal?

答:
No, unfortunately you are not doing this correctly. So what you have successfully done is create two new classes that are basically duplicates of your model classes, and just changed the names to include the word viewmodel

In this instance what you should be doing is just passing the view a new Agent model and setting a distinct list of companies (cast into selectListItems) in the viewBag to use as the select drop down to set the value of the CompanyId on your Agent model.

With your exact need as you described, there isn't justification for creating the view models.

Body:
I Created two models name as Company and Agent and There should be a one to many relationship between them because each company could have many Agents but each agent is related to one company. These Models are as follow:

    Public class Company
    {
    Public int ComapnyId {get;set;}
    Public String CompanyName{get;set;}
    Public String tell{get;set;}
    Public String Address{get;set;}
    Public virtual ICollection<Agent> Agents {get;set;}
    }

    Public Class Agent
    {
    Public int AgentId{get;set;}
    public string FName{get;set;}
    public string LName{get;set;}
    public string Mobile{get;set;}
    public int? CompanyId{get;set;}
    [ForeignKey("CompanyId")]
    public virtual Company company{get;set;}
    }

then I create View Models as follow, but I am not sure I defined them correctly to satisfy my goal.

     public Class CompanyViewModel
     {
     Public int ComapnyId {get;set;}
     Public String CompanyName{get;set;}
     Public String tell{get;set;}
     Public String Address{get;set;}
     Public List<AgentViewModel> AgentsName {get;set;}
     }

     Public AgentViewModel
     {
     Public int AgentId{get;set;}
     public string FName{get;set;}
     public string LName{get;set;}
     public string Mobile{get;set;}
     public int? CompanyId{get;set;}
     [ForeignKey("CompanyId")]
     public string CompanyName{get;set;}
     }

Indeed I want when user wants to create an agent display him all companies in a drop down list. I have so many question about it but the first one is two properties of

      Public List<AgentViewModel> AgentsName {get;set;} and
      public string CompanyName{get;set;}

defined correctly in viewmodels for my goal?


问:
Topological search and Breadth first search
Is it possible to use Breadth first search logic to do a topological sort of a DAG?
The solution in Cormen makes use of Depth first search but wouldn't be easier to use BFS?

Reason:
BFS visits all the nodes in a particular depth before visiting nodes with the next depth value. It naturally means that the parents will be listed before the children if we do a BFS. Isn't this exactly what we need for a topological sort?

答:
Yes, you can do topological sorting using BFS. Actually I remembered once my teacher told me that if the problem can be solved by BFS, never choose to solve it by DFS. Because the logic for BFS is simpler than DFS, most of the time you will always want a straightforward solution to a problem.

As YvesgereY and IVlad has mentioned, you need to start with nodes of which the indegree is 0, meaning no other nodes direct to them. Be sure to add these nodes to your result first.You can use a HashMap to map every node with its indegree, and a queue which is very commonly seen in BFS to assist your traversal. When you poll a node from the queue, the indegree of its neighbors need to be decreased by 1, this is like delete the node from the graph and delete the edge between the node and its neighbors. Every time you come across nodes with 0 indegree, offer them to the queue for checking their neighbors later and add them to the result.

```<code>public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {

    ArrayList<DirectedGraphNode> result = new ArrayList<>();
    if (graph == null || graph.size() == 0) {
        return result;
    }
    Map<DirectedGraphNode, Integer> indegree = new HashMap<DirectedGraphNode, Integer>();
    Queue<DirectedGraphNode> queue = new LinkedList<DirectedGraphNode>();

    //mapping node to its indegree to the HashMap, however these nodes
    //have to be directed to by one other node, nodes whose indegree == 0
    //would not be mapped.
    for (DirectedGraphNode DAGNode : graph){
        for (DirectedGraphNode nei : DAGNode.neighbors){
            if(indegree.containsKey(nei)){
                indegree.put(nei, indegree.get(nei) + 1);
            } else {
                indegree.put(nei, 1);
            }
        }
    }

    //find all nodes with indegree == 0. They should be at starting positon in the result
    for (DirectedGraphNode GraphNode : graph) {
        if (!indegree.containsKey(GraphNode)){
            queue.offer(GraphNode);
            result.add(GraphNode);
        }
    }

    //everytime we poll out a node from the queue, it means we delete it from the
    //graph, we will minus its neighbors indegree by one, this is the same meaning
    //as we delete the edge from the node to its neighbors.
    while (!queue.isEmpty()) {
        DirectedGraphNode temp = queue.poll();
        for (DirectedGraphNode neighbor : temp.neighbors){
            indegree.put(neighbor, indegree.get(neighbor) - 1);
            if (indegree.get(neighbor) == 0){
                result.add(neighbor);
                queue.offer(neighbor);
            }
        }
    }
    return result;
}
</code>```

Body:
Yes, you can do topological sorting using BFS. Actually I remembered once my teacher told me that if the problem can be solved by BFS, never choose to solve it by DFS. Because the logic for BFS is simpler than DFS, most of the time you will always want a straightforward solution to a problem.

As YvesgereY and IVlad has mentioned, you need to start with nodes of which the indegree is 0, meaning no other nodes direct to them. Be sure to add these nodes to your result first.You can use a HashMap to map every node with its indegree, and a queue which is very commonly seen in BFS to assist your traversal. When you poll a node from the queue, the indegree of its neighbors need to be decreased by 1, this is like delete the node from the graph and delete the edge between the node and its neighbors. Every time you come across nodes with 0 indegree, offer them to the queue for checking their neighbors later and add them to the result.

public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {

    ArrayList<DirectedGraphNode> result = new ArrayList<>();
    if (graph == null || graph.size() == 0) {
        return result;
    }
    Map<DirectedGraphNode, Integer> indegree = new HashMap<DirectedGraphNode, Integer>();
    Queue<DirectedGraphNode> queue = new LinkedList<DirectedGraphNode>();

    //mapping node to its indegree to the HashMap, however these nodes
    //have to be directed to by one other node, nodes whose indegree == 0
    //would not be mapped.
    for (DirectedGraphNode DAGNode : graph){
        for (DirectedGraphNode nei : DAGNode.neighbors){
            if(indegree.containsKey(nei)){
                indegree.put(nei, indegree.get(nei) + 1);
            } else {
                indegree.put(nei, 1);
            }
        }
    }

    //find all nodes with indegree == 0. They should be at starting positon in the result
    for (DirectedGraphNode GraphNode : graph) {
        if (!indegree.containsKey(GraphNode)){
            queue.offer(GraphNode);
            result.add(GraphNode);
        }
    }

    //everytime we poll out a node from the queue, it means we delete it from the
    //graph, we will minus its neighbors indegree by one, this is the same meaning
    //as we delete the edge from the node to its neighbors.
    while (!queue.isEmpty()) {
        DirectedGraphNode temp = queue.poll();
        for (DirectedGraphNode neighbor : temp.neighbors){
            indegree.put(neighbor, indegree.get(neighbor) - 1);
            if (indegree.get(neighbor) == 0){
                result.add(neighbor);
                queue.offer(neighbor);
            }
        }
    }
    return result;
}


答: The type cont is a function returning a void pointer. Therefore cont * is a pointer to such a function, and the * cannot be removed from the cast.

Title: recursive return type


问:
Where is the executable `b2` for installing boost from sources?
I am using Ubuntu 14.04 as my OS, and I have followed every tutorial out there that claims to teach me how to install boost from sources, but all these tutorials magically use b2 to finally install everything after calling ./bootstrap.sh. There are no binaries named b2 generated after running bootstrap.sh nor there seems any packages I can separately install using apt-get. I tried searching everywhere, but the only piece of information I can get is that b2 is supposed to be a building system only for boost. So how do I acquire this binary? Why aren't there any tutorials telling me how to get it? I might be getting a little crazy here...

答:
```<code>./bootstrap
./b2
./b2 install
</code>```

Please you look this :http://www.boost.org/doc/libs/1_64_0/more/getting_started/unix-variants.html#easy-build-and-install

Body:
./bootstrap
./b2
./b2 install

Please you look this :http://www.boost.org/doc/libs/1_64_0/more/getting_started/unix-variants.html#easy-build-and-install


问:
Make Angular UI accordion fully clickable instead of only Heading Label
I am using an Angular ui-bootstrap accordion. With my current code, I am not able to click and open the entire heading panel, only heading label(Title) is clickable and opening the accordion. Any help is appreciated. Thanks in advance ! Here is my HTML: </p>

```<code> <uib-accordion close-others="oneAtATime">
    <div uib-accordion-group is-open="sv.isOpen" class="panel-default" id="{{ sv.domId }}" heading="{{(sv.type == 'Check Call') && sv.type || sv.type + ': '+ sv.city +', '+sv.state}}"
    ng-repeat="sv in segment.stopVos" tab-group={{$index+1}}>
       <div class="app-wrapper content">
</code>```

答:
Instead of...

```<code><uib-accordion-heading>
    Click me
</uib-accordion-heading>
</code>```

Setup you uib-accordion-heading to contain a full width element such as p, p will also provide some default margin so make sure to remove it (or tweak it enough) so it won't mess your style.

```<code><uib-accordion-heading>
    <p style="margin-bottom: 0;"> Click me </p>
</uib-accordion-heading>
</code>```

Body:
I am using an Angular ui-bootstrap accordion. With my current code, I am not able to click and open the entire heading panel, only heading label(Title) is clickable and opening the accordion. Any help is appreciated. Thanks in advance ! Here is my HTML:

 <uib-accordion close-others="oneAtATime">

Body:
Instead of...

<uib-accordion-heading>
    Click me
</uib-accordion-heading>

Setup you uib-accordion-heading to contain a full width element such as p, p will also provide some default margin so make sure to remove it (or tweak it enough) so it won't mess your style.

<uib-accordion-heading>
    <p style="margin-bottom: 0;"> Click me </p>
</uib-accordion-heading>


问:
Implicitly unwrapped optional from init!() in Swift 3.1
I'm trying to understand how init!() works in Swift. Here's my test:

```<code>struct InitTest {
    var text: String
    init!(text: String) {
        self.text = text
    }
}

let testResult = InitTest(text: "Hello!")
</code>```

For my understanding, testResult should be of type InitTest (unwrapped), but it's actually still InitTest?.

How is init!() different from init?() then?

答:
InitTest(text: "Hello!") returns an implicitly unwrapped optional,
which is an optional  that is unwrapped if necessary. For example
you can access its properties without explicit unwrapping

```<code>let string = InitTest(text: "Hello!").text
</code>```

or pass it to functions taking a (non-optional) InitTest argument:

```<code>func foo(_ x: InitTest) { }
foo(InitTest(text: "Hello"))
</code>```

But the assignment

```<code>let testResult = InitTest(text: "Hello!")
</code>```

makes testResult a regular ("strong") optional, see
 SE-0054 Abolish ImplicitlyUnwrappedOptional type and  Implicitly unwrapped optional assign in Xcode 8:

If the expression can be explicitly type checked with a strong optional type, it will be.

Actually I cannot think of a good reason to define an init!() method.

Body:
I'm trying to understand how init!() works in Swift. Here's my test:

struct InitTest {
    var text: String
    init!(text: String) {
        self.text = text
    }
}

let testResult = InitTest(text: "Hello!")

For my understanding, testResult should be of type InitTest (unwrapped), but it's actually still InitTest?.

How is init!() different from init?() then?

Body:
InitTest(text: "Hello!") returns an implicitly unwrapped optional,
which is an optional  that is unwrapped if necessary. For example
you can access its properties without explicit unwrapping

let string = InitTest(text: "Hello!").text

or pass it to functions taking a (non-optional) InitTest argument:

func foo(_ x: InitTest) { }
foo(InitTest(text: "Hello"))

But the assignment

let testResult = InitTest(text: "Hello!")

makes testResult a regular ("strong") optional, see
 SE-0054 Abolish ImplicitlyUnwrappedOptional type and  Implicitly unwrapped optional assign in Xcode 8:

If the expression can be explicitly type checked with a strong optional type, it will be.

Actually I cannot think of a good reason to define an init!() method.


问:
Convert to float and pad left with zero on SQL Server
I need to convert to float and pad left with zero in SQL Server.

I need in this format ####.##.

For example:

```<code>2.23   ->  0002.23
123.3  ->  0123.30
12.65  ->  0012.65
34     ->  0034.00
</code>```

I tried this:

```<code>cast(Weight as decimal(6, 2))
</code>```

and also this:

```<code>REPLACE(STR(Weight, 6), SPACE(1), '0')
</code>```

and this:

```<code>REPLACE(STR(cast(Weight as decimal(6,2)), 6), SPACE(1), '0')
</code>```

But they do not work - I got 5.00 or 000005 and I need 0005.00.

Thanks

答:
I am not sure about how to achieve this mathematically but here is one way by string manipulation </p>

```<code>DECLARE @num  NUMERIC(22, 2) = '2.23',
        @temp VARCHAR(100)

SET @temp = Cast(@num AS VARCHAR(100))

SELECT RIGHT('000'+LEFT(@temp, Charindex('.', @temp)-1), 4)
       + LEFT(Substring(@temp, Charindex('.', @temp), Len(@temp))+'0', 3)
</code>```

Body:
I need to convert to float and pad left with zero in SQL Server.

I need in this format ####.##.

For example:

2.23   ->  0002.23
123.3  ->  0123.30
12.65  ->  0012.65
34     ->  0034.00

I tried this:

cast(Weight as decimal(6, 2))

and also this:

REPLACE(STR(Weight, 6), SPACE(1), '0')

and this:

REPLACE(STR(cast(Weight as decimal(6,2)), 6), SPACE(1), '0')

But they do not work - I got 5.00 or 000005 and I need 0005.00.

Thanks

Body:
I am not sure about how to achieve this mathematically but here is one way by string manipulation

DECLARE @num  NUMERIC(22, 2) = '2.23',
        @temp VARCHAR(100)

SET @temp = Cast(@num AS VARCHAR(100))

SELECT RIGHT('000'+LEFT(@temp, Charindex('.', @temp)-1), 4)
       + LEFT(Substring(@temp, Charindex('.', @temp), Len(@temp))+'0', 3)


问:
Embedded Linux Device Driver Error Code 1-001a?
I have compile my camera driver and try to test it from my target board i.MX6Q
I am facing with

probe of 1-001a failed with error -16

Error when I look at the dmesg | grep camera_name , I think the 1-001a is refering to the device driver camera_name@1a .
this  is my device driver

```<code>camera_name: camera_name@1a {
    compatible = "camera,camera_name";
    reg = <0x1a>;
    inck-name = "mclk";
    xvs-output-len = <8>;
    xclr-gpio = <&gpio1 6 1 GPIO_ACTIVE_LOW>;
    pwn-gpios = <&gpio1 6 1>;
    clock-names = "csi_mclk";
    DOVDD = <&reg_1p8v>;
    AVDD = <&reg_2p9v>;
    DVDD = <&reg_1p2v>;
    rst-gpios = <&gpio1 6 1>; /* xclr */
    ipu_id = <0>;
    csi_id = <0>;
    mclk = <37125000>;
    mclk_source = <0>;
    lanes = <4>;
};
</code>```

But I couldnt understand what this error is saying ? Do you have any suggestion ? I couldnt find any information about it .

Thanks so much .

Best Regards.

答:
This error log probe of 1-001a failed with error -16 informs us that :

The .probe function of

a device driver identified as 1-001a

has return the error value -EBUSY

The device-tree node mentioned in the question belongs to the device-driver.

To understand the reason for the above failure,

Start by locating the C file within the Linux kernel

that implements the device driver for the above device.

Next Look for the function registered as the handler for ".probe" within the device driver.

Check under what conditions does it return -EBUSY.

errno-base.h contains the pre-defined convention of various common error numbers defined within the Linux kernel. Most functions in Linux kernel device drivers and the various Linux kernel sub-systems use these error codes as return values to signify error conditions.

Body:
I have compile my camera driver and try to test it from my target board i.MX6Q
I am facing with

probe of 1-001a failed with error -16

Error when I look at the dmesg | grep camera_name , I think the 1-001a is refering to the device driver camera_name@1a .
this  is my device driver

camera_name: camera_name@1a {
    compatible = "camera,camera_name";
    reg = <0x1a>;
    inck-name = "mclk";
    xvs-output-len = <8>;
    xclr-gpio = <&gpio1 6 1 GPIO_ACTIVE_LOW>;
    pwn-gpios = <&gpio1 6 1>;
    clock-names = "csi_mclk";
    DOVDD = <&reg_1p8v>;
    AVDD = <&reg_2p9v>;
    DVDD = <&reg_1p2v>;
    rst-gpios = <&gpio1 6 1>; /* xclr */
    ipu_id = <0>;
    csi_id = <0>;
    mclk = <37125000>;
    mclk_source = <0>;
    lanes = <4>;
};

But I couldnt understand what this error is saying ? Do you have any suggestion ? I couldnt find any information about it .

Thanks so much .

Best Regards.


问:
"Variable might not have been initialized" in java while using timer
Here is my code in a fragment:

```<code>public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view= inflater.inflate(R.layout.fragment_profile, container, false);
    profile();
    textView = (TextView) view.findViewById(R.id.textViewUsername);
    listView = (ListView) view.findViewById(R.id.listView);
    timer_start();
    return view;
}

public void timer_start(){
    final Runnable mTicker = new Runnable() {
        @Override
        public void run() {
            sendRequest();
            handler.postDelayed(mTicker, 5000); // error shows only for this line
        }
    };

    handler.postDelayed(mTicker, 5000);
}
</code>```

I want to execute sendRequest() function in every 5 seconds. But it shows error: "Variable mTicker might not have been initialized" while I am calling timer_start() fragment.

答:
You are referring to mTicker in the same line that it is initialized.  This is not allowed.  That's like saying:

```<code>String s = s;
</code>```

It doesn't make sense.  Try using "this":

```<code>handler.postDelayed(this, 5000);
</code>```

Body:
Here is my code in a fragment:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view= inflater.inflate(R.layout.fragment_profile, container, false);
    profile();
    textView = (TextView) view.findViewById(R.id.textViewUsername);
    listView = (ListView) view.findViewById(R.id.listView);
    timer_start();
    return view;
}

public void timer_start(){
    final Runnable mTicker = new Runnable() {
        @Override
        public void run() {
            sendRequest();
            handler.postDelayed(mTicker, 5000); // error shows only for this line
        }
    };

    handler.postDelayed(mTicker, 5000);
}

I want to execute sendRequest() function in every 5 seconds. But it shows error: "Variable mTicker might not have been initialized" while I am calling timer_start() fragment.

Body:
You are referring to mTicker in the same line that it is initialized.  This is not allowed.  That's like saying:

String s = s;

It doesn't make sense.  Try using "this":

handler.postDelayed(this, 5000);


问:
How to set the alignment of the chart in matplotlib.pyplot?
I have two numpy.ndarray and both have the same number of datas as follow :

```<code>data1 = [1,2,3,4,5,6,7,8,9]
data2 = [Nan, Nan, Nan, 14,15,16,17,18,19]
</code>```

When, I plot these data, the data1 occupies the whole width of the window. But since data2 has NaN, only the non-NaN data will be shown on the window and they are in the middle.

How can I set the matplotlib.pyplot so that they are aligned on the right side/edge of the window?

Hi, the screenshot1 is the actual situation. The screenshot 2 is what I want, i.e. the charts are right aligned.

答:
Adding x values (using x-y pairs) could help you probably to align the data as you want.

```<code>plt.plot(x, data)
plt.plot(x, data2)
plt.show()
</code>```

Where x is an array e.g. [0,1,2,3,4,5,6,7,8]

Body:
I have two numpy.ndarray and both have the same number of datas as follow :

data1 = [1,2,3,4,5,6,7,8,9]
data2 = [Nan, Nan, Nan, 14,15,16,17,18,19]

When, I plot these data, the data1 occupies the whole width of the window. But since data2 has NaN, only the non-NaN data will be shown on the window and they are in the middle.

How can I set the matplotlib.pyplot so that they are aligned on the right side/edge of the window?

Hi, the screenshot1 is the actual situation. The screenshot 2 is what I want, i.e. the charts are right aligned.

Body:
Adding x values (using x-y pairs) could help you probably to align the data as you want.

plt.plot(x, data)
plt.plot(x, data2)
plt.show()

Where x is an array e.g. [0,1,2,3,4,5,6,7,8]


问:
Asyncio, await and infinite loops
```<code>async def start(channel):
    while True:
        m = await client.send_message(channel, "Generating... ")
        generator.makeFile()
        with open('tmp.png', 'rb') as f:
            await client.send_file(channel, f)
        await client.delete_message(m)
        await asyncio.sleep(2)
</code>```

I have a discord bot that runs a task every 2 seconds. I tried using an infinite loop for this, but the script crashes with a Task was destroyed but it is still pending! I have read about asyncio's coroutines, but none of the examples that I found use await in them. Is it possible avoid this error, by running a coroutine with await, for example?

答:
Task was destroyed but it is still pending! is warning that you receive when you call loop.close() when some of tasks in your script aren't finished. Usually you should avoid this situation because unfinished task may not release some resources. You need either to await task done or cancel it before event loop closed.

Since you have infinite loop you probably would need to cancel task, example:

```<code>import asyncio
from contextlib import suppress

async def start():
    # your infinite loop here, for example:
    while True:
        print('echo')
        await asyncio.sleep(1)

async def main():
    task = asyncio.Task(start())

    # let script some thime to work:
    await asyncio.sleep(3)

    # cancel task to avoid warning:
    task.cancel()
    with suppress(asyncio.CancelledError):
        await task  # await for task cancellation

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
    loop.run_until_complete(main())
finally:
    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.close()
</code>```

See also this answer for more information about tasks.

Title: Asyncio, await and infinite loops

Body:
async def start(channel):
    while True:
        m = await client.send_message(channel, "Generating... ")
        generator.makeFile()
        with open('tmp.png', 'rb') as f:
            await client.send_file(channel, f)
        await client.delete_message(m)
        await asyncio.sleep(2)

I have a discord bot that runs a task every 2 seconds. I tried using an infinite loop for this, but the script crashes with a Task was destroyed but it is still pending! I have read about asyncio's coroutines, but none of the examples that I found use await in them. Is it possible avoid this error, by running a coroutine with await, for example?

Body:
Task was destroyed but it is still pending! is warning that you receive when you call loop.close() when some of tasks in your script aren't finished. Usually you should avoid this situation because unfinished task may not release some resources. You need either to await task done or cancel it before event loop closed.

Since you have infinite loop you probably would need to cancel task, example:

import asyncio
from contextlib import suppress

async def start():
    # your infinite loop here, for example:
    while True:
        print('echo')
        await asyncio.sleep(1)

async def main():
    task = asyncio.Task(start())

    # let script some thime to work:
    await asyncio.sleep(3)

    # cancel task to avoid warning:
    task.cancel()
    with suppress(asyncio.CancelledError):
        await task  # await for task cancellation

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
    loop.run_until_complete(main())
finally:
    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.close()

See also this answer for more information about tasks.


问:
Missing Configuration File For Tests - Aqueduct
When implementing OAuth with aqueduct I mistakenly didn't follow the test driven development ideology, and I am paying for it now...

When I run my tests, I get the error:

```<code>"No configuration file found. See README.md."
</code>```

Which is thrown from the initializeApplication method in my AppSink class.
As I understand it, tests make use of the config.src.yaml file so I have configured my test harness accordingly:

```<code>application = new Application<OdexSink>();
application.configuration.port = 0;
application.configuration.configurationFilePath = "config.src.yaml";
</code>```

Since I was able to run the tests before I implemented the AuthServer etc, I suspect it happened along the way.

My test setUp is as follows:

```<code>var app = new Application<OdexSink>();
TestClient client;

setUp(() async {
   await app.start(runOnMainIsolate: true);
   client = new TestClient(app);

   var ctx = ManagedContext.defaultContext;
   var builder = new SchemaBuilder.toSchema(ctx.persistentStore, new Schema.fromDataModel(ctx.dataModel), isTemporary: true);

   for (var cmd in builder.commands) {
     await ctx.persistentStore.execute(cmd);
   }
});
</code>```

And my Test harness start() method is:

```<code>Future start() async {
   RequestController.letUncaughtExceptionsEscape = true;
   application = new Application<OdexSink>();
   application.configuration.port = 0;
   application.configuration.configurationFilePath = "config.src.yaml";

   await application.start(runOnMainIsolate: true);

   await createDatabaseSchema(ManagedContext.defaultContext, sink.logger);
   await addClientRecord();
   await addClientRecord(clientID: DefaultClientID, clientSecret: DefaultClientSecret);

   client = new TestClient(application)
     ..clientID = DefaultClientID
     ..clientSecret = DefaultClientSecret;
}
</code>```

My config.src.yaml file exits, and contains DB information.

答:
Ah, just one small thing - in your setUp method, you are creating and starting an Application instead of that TestApplication harness. It should look like this

```<code>var app = new TestApplication();

setUp(() async {
   await app.start();
});
</code>```

All of the other stuff in setUp is already done in your test harness and you can use the TestClient as app.client:

```<code>expect(await app.client.request("/endpoint"), hasStatus(200));
</code>```

Body:
When implementing OAuth with aqueduct I mistakenly didn't follow the test driven development ideology, and I am paying for it now...

When I run my tests, I get the error:

"No configuration file found. See README.md."

Which is thrown from the initializeApplication method in my AppSink class.
As I understand it, tests make use of the config.src.yaml file so I have configured my test harness accordingly:

application = new Application<OdexSink>();
application.configuration.port = 0;
application.configuration.configurationFilePath = "config.src.yaml";

Since I was able to run the tests before I implemented the AuthServer etc, I suspect it happened along the way.

My test setUp is as follows:

var app = new Application<OdexSink>();
TestClient client;

setUp(() async {
   await app.start(runOnMainIsolate: true);
   client = new TestClient(app);

   var ctx = ManagedContext.defaultContext;
   var builder = new SchemaBuilder.toSchema(ctx.persistentStore, new Schema.fromDataModel(ctx.dataModel), isTemporary: true);

   for (var cmd in builder.commands) {
     await ctx.persistentStore.execute(cmd);
   }
});

And my Test harness start() method is:

Future start() async {
   RequestController.letUncaughtExceptionsEscape = true;
   application = new Application<OdexSink>();
   application.configuration.port = 0;
   application.configuration.configurationFilePath = "config.src.yaml";

   await application.start(runOnMainIsolate: true);

   await createDatabaseSchema(ManagedContext.defaultContext, sink.logger);
   await addClientRecord();
   await addClientRecord(clientID: DefaultClientID, clientSecret: DefaultClientSecret);

   client = new TestClient(application)
     ..clientID = DefaultClientID
     ..clientSecret = DefaultClientSecret;
}

My config.src.yaml file exits, and contains DB information.

Body:
Ah, just one small thing - in your setUp method, you are creating and starting an Application instead of that TestApplication harness. It should look like this

var app = new TestApplication();

setUp(() async {
   await app.start();
});

All of the other stuff in setUp is already done in your test harness and you can use the TestClient as app.client:

expect(await app.client.request("/endpoint"), hasStatus(200));


问:
unexpected Stripe webhook events received, which I can't find on Stripe dashboard
I have setup a Webhook to my development environment. In addition to receiving the event notifications which I would expect, I receive additional notifications (with unique event ID) which do not make sense to me. When I try to look up those events on the Stripe dashboard I cannot find trace of them... Shouldn't all events be logged on the Dashboard?

Has anyone experienced this? I've popped a mail to the support but no answer yet.

EDIT:
I could find one of the "missing" events on the dashboard now. It was buried far down the event list, as it was apparently fired several hours ago for  the first time, but couldn't be handled at that time by my application.

答: All events appear on the dashboard, listed at the time they are fired for the first time. So in case the application receiving the notification can't return a response 2xx for some reason, Stripe will try sending the notification again at a later time. Once the application server handles the event notification properly, the event will in all likelihood be logged by the application, and the timing might look confusing. </p>


问:
Create a Promise from an API (object)
The API I'm using is owapi.net/api/v3/u/Calvin-1337/stats (the name will change). Let's say I wanted the tier, that'd be JSON.us.stats.competitive.overall_stats.tier and I can parse that and get it okay. But now I want to create a promise. Let's make it for the overall_stats so... us.stats.competitive.overall_stats and I only want values from there for the moment. I wan't to be able to do something like:

```<code>const core = require("myNodePackage");

core.getCompOverallStats("Calvin-1337").then(data > {
    console.log(data.tier) // grandmaster
    // etc through to
    console.log(data.prestige) // 5
});
</code>```

This is totally wrong but what I had thought about:

```<code>const fetch = require("node-fetch"); // used to get json data

getCompOverallStats = (playerName) => {
    return new Promise((resolve, reject) => {

        // only want this for us.stats.competitive.overall_stats

        fetch("https://owapi.net/api/v3/u/Calvin-1337/stats")
            .then(function(res) => {
                return res.json();
            }).then(function(json) {
                //console.log(json.us.stats.competitive.overall_stats.tier) => grandmaster
            });
</code>```

答:
```<code>getCompOverallStats = (playerName) =>
  // grab the player stats
  fetch(`https://owapi.net/api/v3/u/${playerName}/stats`)
    // parse json
    .then(res => res.json())
    // pull out the one object you want
    .then(data => data.us.stats.competitive.overall_stats);
</code>```

That should be enough.

You should now be able to call

getCompOverallStats('some-pl4y3r').then(overall => console.log(overall.tier));

Title: Create a Promise from an API (object)

Body:
The API I'm using is owapi.net/api/v3/u/Calvin-1337/stats (the name will change). Let's say I wanted the tier, that'd be JSON.us.stats.competitive.overall_stats.tier and I can parse that and get it okay. But now I want to create a promise. Let's make it for the overall_stats so... us.stats.competitive.overall_stats and I only want values from there for the moment. I wan't to be able to do something like:

const core = require("myNodePackage");

core.getCompOverallStats("Calvin-1337").then(data > {
    console.log(data.tier) // grandmaster
    // etc through to
    console.log(data.prestige) // 5
});

This is totally wrong but what I had thought about:

const fetch = require("node-fetch"); // used to get json data

getCompOverallStats = (playerName) => {
    return new Promise((resolve, reject) => {

        // only want this for us.stats.competitive.overall_stats

        fetch("https://owapi.net/api/v3/u/Calvin-1337/stats")
            .then(function(res) => {
                return res.json();
            }).then(function(json) {
                //console.log(json.us.stats.competitive.overall_stats.tier) => grandmaster
            });

Body:
getCompOverallStats = (playerName) =>
  // grab the player stats
  fetch(`https://owapi.net/api/v3/u/${playerName}/stats`)
    // parse json
    .then(res => res.json())
    // pull out the one object you want
    .then(data => data.us.stats.competitive.overall_stats);

That should be enough.

You should now be able to call

getCompOverallStats('some-pl4y3r').then(overall => console.log(overall.tier));


问:
Using BFS for topological sort
Can Breadth first Search be used for finding topological sorting of vertices and strongly connected components in a graph?

If yes how to do that? and If not why not?

we generally use Depth first search in these problems but What will be the problem if I try to implement using BFS?

Will code like this work?

```<code>def top_bfs(start_node):
    queue = [start_node]
    stack = []
    while not queue.empty():
        node = queue.dequeue()
        if not node.visited:
            node.visited = True
            stack.push(node)
            for c in node.children:
                queue.enqueue(c)
    stack.reverse()
    return stack
</code>```

答:
Yes, you can do topological sorting using BFS. Actually I remembered once my teacher told me that if the problem can be solved by BFS, never choose to solve it by DFS. Because the logic for BFS is simpler than DFS, most of the time you will always want a straightforward solution to a problem.

You need to start with nodes of which the indegree is 0, meaning no other nodes direct to them. Be sure to add these nodes to your result first.You can use a HashMap to map every node with its indegree, and a queue which is very commonly seen in BFS to assist your traversal. When you poll a node from the queue, the indegree of its neighbors need to be decreased by 1, this is like delete the node from the graph and delete the edge between the node and its neighbors. Every time you come across nodes with 0 indegree, offer them to the queue for checking their neighbors later and add them to the result.

```<code>public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {

  ArrayList<DirectedGraphNode> result = new ArrayList<>();
    if (graph == null || graph.size() == 0) {
      return result;
    }
  Map<DirectedGraphNode, Integer> indegree = new HashMap<DirectedGraphNode, Integer>();
  Queue<DirectedGraphNode> queue = new LinkedList<DirectedGraphNode>();

//mapping node to its indegree to the HashMap, however these nodes
//have to be directed to by one other node, nodes whose indegree == 0
//would not be mapped.
  for (DirectedGraphNode DAGNode : graph){
      for (DirectedGraphNode nei : DAGNode.neighbors){
          if(indegree.containsKey(nei)){
              indegree.put(nei, indegree.get(nei) + 1);
          } else {
              indegree.put(nei, 1);
          }
      }
  }

//find all nodes with indegree == 0. They should be at starting positon in the result
  for (DirectedGraphNode GraphNode : graph) {
      if (!indegree.containsKey(GraphNode)){
          queue.offer(GraphNode);
          result.add(GraphNode);
      }
  }

//everytime we poll out a node from the queue, it means we delete it from the
//graph, we will minus its neighbors indegree by one, this is the same meaning
//as we delete the edge from the node to its neighbors.
  while (!queue.isEmpty()) {
      DirectedGraphNode temp = queue.poll();
      for (DirectedGraphNode neighbor : temp.neighbors){
          indegree.put(neighbor, indegree.get(neighbor) - 1);
          if (indegree.get(neighbor) == 0){
              result.add(neighbor);
              queue.offer(neighbor);
          }
      }
  }
  return result;
}
</code>```

Title: Using BFS for topological sort

Body:
Can Breadth first Search be used for finding topological sorting of vertices and strongly connected components in a graph?

If yes how to do that? and If not why not?

we generally use Depth first search in these problems but What will be the problem if I try to implement using BFS?

Will code like this work?

def top_bfs(start_node):
    queue = [start_node]
    stack = []
    while not queue.empty():
        node = queue.dequeue()
        if not node.visited:
            node.visited = True
            stack.push(node)
            for c in node.children:
                queue.enqueue(c)
    stack.reverse()
    return stack

Body:
Yes, you can do topological sorting using BFS. Actually I remembered once my teacher told me that if the problem can be solved by BFS, never choose to solve it by DFS. Because the logic for BFS is simpler than DFS, most of the time you will always want a straightforward solution to a problem.

You need to start with nodes of which the indegree is 0, meaning no other nodes direct to them. Be sure to add these nodes to your result first.You can use a HashMap to map every node with its indegree, and a queue which is very commonly seen in BFS to assist your traversal. When you poll a node from the queue, the indegree of its neighbors need to be decreased by 1, this is like delete the node from the graph and delete the edge between the node and its neighbors. Every time you come across nodes with 0 indegree, offer them to the queue for checking their neighbors later and add them to the result.

public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {

  ArrayList<DirectedGraphNode> result = new ArrayList<>();
    if (graph == null || graph.size() == 0) {
      return result;
    }
  Map<DirectedGraphNode, Integer> indegree = new HashMap<DirectedGraphNode, Integer>();
  Queue<DirectedGraphNode> queue = new LinkedList<DirectedGraphNode>();

//mapping node to its indegree to the HashMap, however these nodes
//have to be directed to by one other node, nodes whose indegree == 0
//would not be mapped.
  for (DirectedGraphNode DAGNode : graph){
      for (DirectedGraphNode nei : DAGNode.neighbors){
          if(indegree.containsKey(nei)){
              indegree.put(nei, indegree.get(nei) + 1);
          } else {
              indegree.put(nei, 1);
          }
      }
  }

//find all nodes with indegree == 0. They should be at starting positon in the result
  for (DirectedGraphNode GraphNode : graph) {
      if (!indegree.containsKey(GraphNode)){
          queue.offer(GraphNode);
          result.add(GraphNode);
      }
  }

//everytime we poll out a node from the queue, it means we delete it from the
//graph, we will minus its neighbors indegree by one, this is the same meaning
//as we delete the edge from the node to its neighbors.
  while (!queue.isEmpty()) {
      DirectedGraphNode temp = queue.poll();
      for (DirectedGraphNode neighbor : temp.neighbors){
          indegree.put(neighbor, indegree.get(neighbor) - 1);
          if (indegree.get(neighbor) == 0){
              result.add(neighbor);
              queue.offer(neighbor);
          }
      }
  }
  return result;
}


问:
typeof() parameter - how does it work?
In the Code below:

```<code>string GetName(Type type)
{
    return ((type)this.obj).Name;
}

void Run()
{
    string name = GetName(typeof(MyClass));
}
</code>```

Im getting a "The type or name space cannot be found (are you missing using a directive or assembly reference?)" error. What should I do to correct this?

答:
You can't do like this, you need Reflection to do something like what you are asking for:</p>

```<code>void Update(Type type)
{
    PropertyInfo info = type.GetProperty("Name");
    string name = info.GetValue(info, null);
}
</code>```

Title: typeof() parameter - how does it work?

Body:
In the Code below:

string GetName(Type type)
{
    return ((type)this.obj).Name;
}

void Run()
{
    string name = GetName(typeof(MyClass));
}

Im getting a "The type or name space cannot be found (are you missing using a directive or assembly reference?)" error. What should I do to correct this?

Body:
You can't do like this, you need Reflection to do something like what you are asking for:

void Update(Type type)
{
    PropertyInfo info = type.GetProperty("Name");
    string name = info.GetValue(info, null);
}


问:
How can I dynamically access a page control in a visual basic asp web page?
I am trying to update the text property of multiple labels on my page that I know exist by the naming convention I have below. However when I try to access them in this way I always get an "Input String was not in correct format" error.</p>

```<code> For i = 1 To 5
        Dim title As Label = CType(Me.Controls("title" & i), Label)
        title.Text = alist(i * section).inDate
        Dim postDate As Label = CType(Me.Controls("postDate" & i), Label)
        postDate.Text = alist(i * section).inDate
        Dim depart As Label = CType(Me.Controls("depart" & i), Label)
        depart.Text = alist(i * section).department
        Dim mess As Label = CType(Me.Controls("mess" & i), Label)
        mess.Text = alist(i * section).message

    Next
</code>```

答:
I guess in your line 3 it should be:

```<code>title.Text = alist(i * section).title
</code>```

I don't know if this causes the problem you described

Body:
I am trying to update the text property of multiple labels on my page that I know exist by the naming convention I have below. However when I try to access them in this way I always get an "Input String was not in correct format" error.

 For i = 1 To 5
        Dim title As Label = CType(Me.Controls("title" & i), Label)
        title.Text = alist(i * section).inDate
        Dim postDate As Label = CType(Me.Controls("postDate" & i), Label)
        postDate.Text = alist(i * section).inDate
        Dim depart As Label = CType(Me.Controls("depart" & i), Label)
        depart.Text = alist(i * section).department
        Dim mess As Label = CType(Me.Controls("mess" & i), Label)
        mess.Text = alist(i * section).message

    Next

Body:
I guess in your line 3 it should be:

title.Text = alist(i * section).title

I don't know if this causes the problem you described


问:
React router 4 "NOT FOUND" when I type in the URL in browser
I am trying to learn react router 4 but meet some problems. I follow the guide from here https://reacttraining.com/react-router/web/example/no-match, and yes this example works fine in my browser. I can click the links and get things shown in the browser.

but, if I type in the url in the browser instead of click the links, the page shows NOT FOUND

NOT FOUND page

What's happening? Does React-router can only use links instead of typing in URL??

答:
Stijn de Witt explain about this "problem" here: https://stackoverflow.com/a/36623117/8272354

When you initialize with the URL in the "inital route" of your route system, all the routes "know" how to deal with Router Links. So, the React Link does't refresh the browser, just change the route internally in javascript and load the specifyc route. This way everything works fine.

But, when you type the route (not the "initial route") directly in the URL, the router system does't understand that route, and the browser will try get this page in the server.


问:
How can I show a div, then hide the other divs when a link is clicked?
I am right now trying to hide six divs while showing only one of the divs.  I've tried JavaScript and in jQuery, but nothing seems to work!  Click here to get to the website.

I would like to know if it has to do with my CSS, jQuery, or the HTML.  Or is there an easier way of doing this?

HTML:

```<code><div id="resourceLinks">
  <a href="#" name="resource" id="resource1">General Information</a><br />
  <a href="#" name="resource" id="resource2">Automatic 401(k)</a><br />
  <a href="#" name="resource" id="resource3">Consumer Fraud</a><br />
  <a href="#" name="resource" id="resource4">Direct Deposit</a><br />
  <a href="#" name="resource" id="resource5">Diversity</a><br />
  <a href="#" name="resource" id="resource6">Women</a><br />
  <a href="#" name="resource" id="resource7">Young Adults (20s - 40s)</a>
  </div>

<div id="resource1></div>
<div id="resource2></div>
<div id="resource3></div>
<div id="resource4></div>
<div id="resource5></div>
<div id="resource6></div>
<div id="resource7></div>
</code>```

CSS:

```<code>#resource1, #resource2, #resource3, #resource4, #resource5, #resource6, #resource7 {
    position: absolute;
    margin-left: 400px;
    margin-top: -10px;
    width: 300px;
    padding-bottom: 120px;
}

#resourceLinks {
    position: fixed;
    margin-left: -450px;
    z-index: 3;
    margin-top: 180px;
    font-size: 16px;
}
</code>```

jQuery:

```<code>$(document).ready(function(){

  $('#resourceLinks a').click(function (selected) {

    var getName = $(this).attr("id");
    var projectImages = $(this).attr("name");

    $(function() {
      $(".resource").hide().removeClass("current");
      $("#" + projectImages ).show("normal").addClass("current");
    });
  });
});
</code>```

答:
I think you are trying to achieve the accordian effect.. Have a look here:

http://jquery.bassistance.de/accordion/demo/

Its and existing jQuery plugin.

Body:
I am right now trying to hide six divs while showing only one of the divs.  I've tried JavaScript and in jQuery, but nothing seems to work!  Click here to get to the website.

I would like to know if it has to do with my CSS, jQuery, or the HTML.  Or is there an easier way of doing this?

HTML:

  General Information

  Automatic 401(k)

  Consumer Fraud

  Direct Deposit

  Diversity

  Women

  Young Adults (20s - 40s)

CSS:

#resource1, #resource2, #resource3, #resource4, #resource5, #resource6, #resource7 {
    position: absolute;
    margin-left: 400px;
    margin-top: -10px;
    width: 300px;
    padding-bottom: 120px;
}

#resourceLinks {
    position: fixed;
    margin-left: -450px;
    z-index: 3;
    margin-top: 180px;
    font-size: 16px;
}

jQuery:

$(document).ready(function(){

  $('#resourceLinks a').click(function (selected) {

    var getName = $(this).attr("id");
    var projectImages = $(this).attr("name");

    $(function() {
      $(".resource").hide().removeClass("current");
      $("#" + projectImages ).show("normal").addClass("current");
    });
  });
});


问:
Moment.js + TypeScript. Cannot find name moment
I develope web application with knockout in VisualStudio. I just installed knockout via bower, included d.ts file in project, included script to html page and now i can get access to ko.

Now i try to use moment.js. Like with knockout: install, include d.ts, include script to page and i get an error cannot find name 'moment'. Adding reference to d.ts does not help, import * as moment from 'moment' get an error can not find module moment.

I know that it's a stupid problem, but i can't fix it. What am i doing wrong?

答:
In my case, finally get this error solved by doing the following:

Adding this option "allowSyntheticDefaultImports": true, in the compilerOptions section of the tsconfig.json file (EDITED: As the moment doc. sais in the Note: If you have trouble importing moment, try add "allowSyntheticDefaultImports": true in compilerOptions in your tsconfig.json file.)

Also add "moduleResolution": "node" in the same compilerOptions section. (Found this option looking around the web)

Importing moment module like this import * as moment from 'moment';


问:
How To print a long string into multiple pages in C#
I'm trying to print a very long string using code below but it prints the whole text only in one page. Is there any easy way to print it correctly?

```<code>string text="the text has like 1000 words";

System.Drawing.Printing.PrintDocument p = new System.Drawing.Printing.PrintDocument();

p.PrintPage += delegate (object sender1, System.Drawing.Printing.PrintPageEventArgs e1)
{
    e1.Graphics.DrawString(text, new System.Drawing.Font("Times New Roman", 12), new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.RectangleF(50, 50, p.DefaultPageSettings.PrintableArea.Width - 50, p.DefaultPageSettings.PrintableArea.Height - 50));

};
try
{
    p.Print();
}
catch (Exception ex)
{
    throw new Exception("Exception Occured While Printing", ex);
}
</code>```

I tried to solve it with this article but the method stuck in some loop that I don't know how to fix.

答:
So thanks to rene I figured it out how to print it correctly. I edit his code and the difference here is that the user chooses the paper size and rectangel drawing happens with choosen paper margin size. This is a ready printing method in case you want to use it...</p>

```<code>private void Print(string thetext){

            try
            {

                System.Drawing.Printing.PrintDocument p = new System.Drawing.Printing.PrintDocument();

                var font = new Font("Times New Roman", 12);
                var brush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);

                // what still needs to be printed
                var remainingText = theText;

                p.PrintPage += delegate (object sender1, System.Drawing.Printing.PrintPageEventArgs e1)
                {
                    int charsFitted, linesFilled;

                // measure how many characters will fit of the remaining text

                var realsize = e1.Graphics.MeasureString(
                        remainingText,
                        font,
                        e1.MarginBounds.Size,
                        System.Drawing.StringFormat.GenericDefault,
                        out charsFitted,  // this will return what we need
                        out linesFilled);

                // take from the remainingText what we're going to print on this page
                var fitsOnPage = remainingText.Substring(0, charsFitted);
                // keep what is not printed on this page
                remainingText = remainingText.Substring(charsFitted).Trim();

                // print what fits on the page
                e1.Graphics.DrawString(
                        fitsOnPage,
                        font,
                        brush,
                        e1.MarginBounds);

                    // if there is still text left, tell the PrintDocument it needs to call
                    // PrintPage again.
                    e1.HasMorePages = remainingText.Length > 0;
                };

                System.Windows.Forms.PrintDialog pd = new System.Windows.Forms.PrintDialog();
                pd.Document = p;
                DialogResult result = pd.ShowDialog();

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    p.Print();
                }

            }catch(Exception e2)
            {
                System.Windows.MessageBox.Show(e2.Message, "Unable to print",MessageBoxButton.OK);
            }

}
</code>```

Body:
I'm trying to print a very long string using code below but it prints the whole text only in one page. Is there any easy way to print it correctly?

string text="the text has like 1000 words";

System.Drawing.Printing.PrintDocument p = new System.Drawing.Printing.PrintDocument();

p.PrintPage += delegate (object sender1, System.Drawing.Printing.PrintPageEventArgs e1)
{
    e1.Graphics.DrawString(text, new System.Drawing.Font("Times New Roman", 12), new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.RectangleF(50, 50, p.DefaultPageSettings.PrintableArea.Width - 50, p.DefaultPageSettings.PrintableArea.Height - 50));

};
try
{
    p.Print();
}
catch (Exception ex)
{
    throw new Exception("Exception Occured While Printing", ex);
}

I tried to solve it with this article but the method stuck in some loop that I don't know how to fix.

Body:
So thanks to rene I figured it out how to print it correctly. I edit his code and the difference here is that the user chooses the paper size and rectangel drawing happens with choosen paper margin size. This is a ready printing method in case you want to use it...

private void Print(string thetext){

            try
            {

                System.Drawing.Printing.PrintDocument p = new System.Drawing.Printing.PrintDocument();

                var font = new Font("Times New Roman", 12);
                var brush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);

                // what still needs to be printed
                var remainingText = theText;

                p.PrintPage += delegate (object sender1, System.Drawing.Printing.PrintPageEventArgs e1)
                {
                    int charsFitted, linesFilled;

                // measure how many characters will fit of the remaining text

                var realsize = e1.Graphics.MeasureString(
                        remainingText,
                        font,
                        e1.MarginBounds.Size,
                        System.Drawing.StringFormat.GenericDefault,
                        out charsFitted,  // this will return what we need
                        out linesFilled);

                // take from the remainingText what we're going to print on this page
                var fitsOnPage = remainingText.Substring(0, charsFitted);
                // keep what is not printed on this page
                remainingText = remainingText.Substring(charsFitted).Trim();

                // print what fits on the page
                e1.Graphics.DrawString(
                        fitsOnPage,
                        font,
                        brush,
                        e1.MarginBounds);

                    // if there is still text left, tell the PrintDocument it needs to call
                    // PrintPage again.
                    e1.HasMorePages = remainingText.Length > 0;
                };

                System.Windows.Forms.PrintDialog pd = new System.Windows.Forms.PrintDialog();
                pd.Document = p;
                DialogResult result = pd.ShowDialog();

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    p.Print();
                }

            }catch(Exception e2)
            {
                System.Windows.MessageBox.Show(e2.Message, "Unable to print",MessageBoxButton.OK);
            }

}


问:
NLTK: No value returned when searching the CMU dictionary based on syllable value
I am practicing the nltk examples from the "Natural language processing in Python" book. While trying to get the words that start with syllable "p" and of syllable length 3 from cmu dictionary (one of the examples provided in chapter 2), I am not getting any values returned. I am using Python 3. Below is the code:

entries = nltk.corpus.cmudict.entries()

p3 = [(pron[0] + '-' + pron[2], word)
            for pron, word in entries if pron[0] == 'P' and len(pron) == 3]

But no value returned:

p3 =
      []

However, I know that the value exist. See below:

[(word, pron[0] + '-' + pron[2]) for word, pron in entries if word == 'perch']

[('perch', 'P-CH')]

答:
My bad, I realized the mistake. I had swapped the position of "pron" with "word" thereby causing this problem. The corrected code is:

p3 = [(pron[0] + '-' + pron[2], word)
            for word, pron in entries if pron[0] == 'P' and len(pron) == 3]
      "