问:
Java Android download video in parts and Play combined
I don't know how to do. Please suggest how to download a large video file in parts and play all parts one by one.
Actually I have to stream FTP large file in Android VideoView. I have searched a lot and found that android do not support FTP streaming.

So, I tried to download the file in multiple parts and play them one by one. But the problem is that only first part of file plays, others don't. Please suggest.

Code to download file in parts.

```<code>URL url = new URL(fileUrl);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
FileOutputStream outStream = new FileOutputStream(fileName);
byte[] buff = new byte[5 * 1024];
int len;

int maxLenth = 10000;      //Some random value
int counter = 0;

//Read bytes (and store them) until there is nothing more to read(-1)
 while ((len = inStream.read(buff)) != -1) {
      outStream.write(buff, 0, len);
      counter ++;
      Log.d(TAG, "Counter: " + counter);

      if(counter == maxLenth) {
          counter = 0;
          outStream.flush();
          outStream.close();

          fileName = new File(directory.getAbsolutePath() + "/"
                        + context.getResources().getString(R.string.app_name) + "_"
                        + System.currentTimeMillis() + "." + format);
          fileName.createNewFile();
          outStream = new FileOutputStream(fileName);
      }
  }
</code>```

And when the files are downloaded, I tried to update the list to play videos when at least 1 file is downloaded. listFiles contains list of all the dowloaded files.

```<code>    Uri uri = Uri.parse(listFiles.get(0));
    videoView.setVideoURI(uri);
    videoView.start();

    videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            counter ++;
            if(counter < listFiles.size()) {
                Uri uri = Uri.parse(listFiles.get(counter));
                videoView.setVideoURI(uri);
                videoView.start();
            }
        }
    });
</code>```

I don't know why the downloaded files after file 1 don't play. They don't play even in the PC. I don't know what wrong am I doing.

答: Decoding file this way will not play all the files. Because they are just binary files and you are trying to change the extensions of them. There is no way in android to decode files this way. But there are many libraries which you can use to decode the file into parts and then play each part separately. One of the library is ffmpeg.</p>

Body:
I don't know how to do. Please suggest how to download a large video file in parts and play all parts one by one.
Actually I have to stream FTP large file in Android VideoView. I have searched a lot and found that android do not support FTP streaming.

So, I tried to download the file in multiple parts and play them one by one. But the problem is that only first part of file plays, others don't. Please suggest.

Code to download file in parts.

URL url = new URL(fileUrl);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
FileOutputStream outStream = new FileOutputStream(fileName);
byte[] buff = new byte[5 * 1024];
int len;

int maxLenth = 10000;      //Some random value
int counter = 0;

//Read bytes (and store them) until there is nothing more to read(-1)
 while ((len = inStream.read(buff)) != -1) {
      outStream.write(buff, 0, len);
      counter ++;
      Log.d(TAG, "Counter: " + counter);

      if(counter == maxLenth) {
          counter = 0;
          outStream.flush();
          outStream.close();

          fileName = new File(directory.getAbsolutePath() + "/"
                        + context.getResources().getString(R.string.app_name) + "_"
                        + System.currentTimeMillis() + "." + format);
          fileName.createNewFile();
          outStream = new FileOutputStream(fileName);
      }
  }

And when the files are downloaded, I tried to update the list to play videos when at least 1 file is downloaded. listFiles contains list of all the dowloaded files.

    Uri uri = Uri.parse(listFiles.get(0));
    videoView.setVideoURI(uri);
    videoView.start();

    videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            counter ++;
            if(counter < listFiles.size()) {
                Uri uri = Uri.parse(listFiles.get(counter));
                videoView.setVideoURI(uri);
                videoView.start();
            }
        }
    });

I don't know why the downloaded files after file 1 don't play. They don't play even in the PC. I don't know what wrong am I doing.


来源: stackexchange

问:
Which programming language Google app engine is most likely to work with next and why?
Their roadmap says their next release will be in March 2009, and that they'll be adding a new 'runtime language'. I'm hoping its either Java or PHP but realy not sure, and would like to know which language is the most probable so i can plan accordingly for a project I plan on hosting with google app engine.

Any ideas?

答: I`ve heard once that Google likes Python the most! </p>

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Click Upvote


问:
How to do when selecting select option toggleClass not force close
I made a button that works to select the number of passengers with the select option. but there was a problem when I selected the number of passengers force close.

How to do when selecting passenger numbers is not force close.

Thanks in advance

I've put his code on > https://jsfiddle.net/devefrontend/vaqdsmjk/1/

$(document).ready(function() {
  $(".btn-passenger").on('click', function(e) {
    $(".passenger-box").toggleClass("s");
    e.stopPropagation();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn-passenger {
  background-color: #eee;
  display: inline-block;
  height: 45px;
  cursor: pointer;
}

.passenger-box.s {
  visibility: visible;
  opacity: 1;
  transition: all .3s ease;
}

.passenger-box {
  padding: 10px 20px;
  background-color: #fff;
  border: 1px solid #eee;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  margin-top: 7px;
  position: relative;
  z-index: 99;
  opacity: 0;
  visibility: hidden;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  0 click button

    Dewasa 12+ Thn
    <select name="adult" id="adult" class="form-control passenger">
      <option selected="selected">1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Anak 2-12 Thn
    <select name="child" id="child" class="form-control passenger">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Bayi
      < 2 Thn
        <select name="infant" id="infant" class="form-control passenger">
          <option>0</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
          <option>6</option>
        </select>

```

答:
Issues:

You should use < or use a text node when you want to insert < into a document.  It fixes syntax highlighting, produces more secure and robust code. (Less likely to run into errors).  You should especially do this when you are using < (use > instead).

You can fix it by checking if the target's parent or the target itself is a select tag.  Thanks to charlietfl for pointing this out.  I just tested this in Internet Explorer and Firefox.  It works in both.  If it isn't a select tag, then you update the visibility of s.

You could choose to restructure your code.  If you want only the button to modify visibility. You can simply stop the button from containing the drop down.  Or you could change the closest to check for .passenger-box.

Comment if you have issues

$(document).ready(function(e) {
  $(".btn-passenger").on('click', function(e) {
    if (!$(e.target).closest("select").length) { //ADDED IF STATEMENT
      $(".passenger-box").toggleClass("s");
    }
    e.stopPropagation();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn-passenger {
  background-color: #eee;
  display: inline-block;
  height: 45px;
  cursor: pointer;
}

.passenger-box.s {
  visibility: visible;
  opacity: 1;
  transition: all .3s ease;
}

.passenger-box {
  padding: 10px 20px;
  background-color: #fff;
  border: 1px solid #eee;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  margin-top: 7px;
  position: relative;
  z-index: 99;
  opacity: 0;
  visibility: hidden;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  0 click button

    Dewasa 12+ Thn
    <select name="adult" id="adult" class="form-control passenger">
      <option selected="selected">1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Anak 2-12 Thn
    <select name="child" id="child" class="form-control passenger">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Bayi
      < 2 Thn
        <select name="infant" id="infant" class="form-control passenger">
          <option>0</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
          <option>6</option>
        </select>

```

ContentLicense: CC BY-SA 3.0

Body:
I made a button that works to select the number of passengers with the select option. but there was a problem when I selected the number of passengers force close.

How to do when selecting passenger numbers is not force close.

Thanks in advance

I've put his code on > https://jsfiddle.net/devefrontend/vaqdsmjk/1/

$(document).ready(function() {
  $(".btn-passenger").on('click', function(e) {
    $(".passenger-box").toggleClass("s");
    e.stopPropagation();
  });
});

.btn-passenger {
  background-color: #eee;
  display: inline-block;
  height: 45px;
  cursor: pointer;
}

.passenger-box.s {
  visibility: visible;
  opacity: 1;
  transition: all .3s ease;
}

.passenger-box {
  padding: 10px 20px;
  background-color: #fff;
  border: 1px solid #eee;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  margin-top: 7px;
  position: relative;
  z-index: 99;
  opacity: 0;
  visibility: hidden;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  0 click button

    Dewasa 12+ Thn
    <select name="adult" id="adult" class="form-control passenger">
      <option selected="selected">1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Anak 2-12 Thn
    <select name="child" id="child" class="form-control passenger">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Bayi
      < 2 Thn
        <select name="infant" id="infant" class="form-control passenger">
          <option>0</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
          <option>6</option>
        </select>

Body:
Issues:

You should use &lt; or use a text node when you want to insert < into a document.  It fixes syntax highlighting, produces more secure and robust code. (Less likely to run into errors).  You should especially do this when you are using < (use &gt; instead).

You can fix it by checking if the target's parent or the target itself is a select tag.  Thanks to charlietfl for pointing this out.  I just tested this in Internet Explorer and Firefox.  It works in both.  If it isn't a select tag, then you update the visibility of s.

You could choose to restructure your code.  If you want only the button to modify visibility. You can simply stop the button from containing the drop down.  Or you could change the closest to check for .passenger-box.

Comment if you have issues

$(document).ready(function(e) {
  $(".btn-passenger").on('click', function(e) {
    if (!$(e.target).closest("select").length) { //ADDED IF STATEMENT
      $(".passenger-box").toggleClass("s");
    }
    e.stopPropagation();
  });
});

.btn-passenger {
  background-color: #eee;
  display: inline-block;
  height: 45px;
  cursor: pointer;
}

.passenger-box.s {
  visibility: visible;
  opacity: 1;
  transition: all .3s ease;
}

.passenger-box {
  padding: 10px 20px;
  background-color: #fff;
  border: 1px solid #eee;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  margin-top: 7px;
  position: relative;
  z-index: 99;
  opacity: 0;
  visibility: hidden;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="btn-passenger">
  <i class="fa fa-user" aria-hidden="true"></i>
  <span id="count">0 click button</span>
  <i class="fa fa-angle-down" aria-hidden="true"></i>
  <div class="passenger-box">
    <label>Dewasa 12+ Thn</label>
    <select name="adult" id="adult" class="form-control passenger">
      <option selected="selected">1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    <label>Anak 2-12 Thn</label>
    <select name="child" id="child" class="form-control passenger">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    <label>Bayi
      &lt; 2 Thn</label>
        <select name="infant" id="infant" class="form-control passenger">
          <option>0</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
          <option>6</option>
        </select>
  </div>
</div>


问:
Weighted mean of duplicated columns
I have df:

```<code>x <- c(1,1,2,2,3,3,4,5)
y <- c(1,1,2,3,3,3,4,4)
freq <- c(4,6,7,2,2,6,5,1)
distmean <-c(2,4,5,7,3,5,2,7)
df <- data.frame(x,y,freq,distmean)

x      y   freq   distmean
1      1      4          2
1      1      6          4
2      2      7          5
2      3      2          7
3      3      2          3
3      3      6          5
4      4      5          2
5      4      1          7
</code>```

I want to aggregate the rows based on x and y, with the sum of freq and a mean of distmean weighted by freq.

So in the end I want:

```<code>x      y   freq    distmean
1      1     10         3.2
2      2      7         5.0
2      3      2         7.0
3      3      8         4.5
4      4      5         2.0
5      4      1         7.0
</code>```

I tried using aggregate() which I can combine the duplicated rows with, but can't figure out a weighted mean.

答:
This may not be a short method to do this. But can be done this way if you want to avoid complex functions.

df2=a=aggregate(freq ~ x+y, data=df, sum, na.rm=TRUE)
df$dist=df$distmean*df$freq
b=aggregate(dist ~ x+y, data=df, sum, na.rm=TRUE)
df2$distmean=(b/a)[3]

Title: Weighted mean of duplicated columns

Body:
I have df:

x <- c(1,1,2,2,3,3,4,5)
y <- c(1,1,2,3,3,3,4,4)
freq <- c(4,6,7,2,2,6,5,1)
distmean <-c(2,4,5,7,3,5,2,7)
df <- data.frame(x,y,freq,distmean)

x      y   freq   distmean
1      1      4          2
1      1      6          4
2      2      7          5
2      3      2          7
3      3      2          3
3      3      6          5
4      4      5          2
5      4      1          7

I want to aggregate the rows based on x and y, with the sum of freq and a mean of distmean weighted by freq.

So in the end I want:

x      y   freq    distmean
1      1     10         3.2
2      2      7         5.0
2      3      2         7.0
3      3      8         4.5
4      4      5         2.0
5      4      1         7.0

I tried using aggregate() which I can combine the duplicated rows with, but can't figure out a weighted mean.


问:
Efficient algorithm for comparing elements in the same list
I have a list of BaseBallGame objects with start and end time. I need to make sure that each game are happening at a separate time so that a user can watch the live stream of all the game.

I have an algorithm of O(n^2). I need to at least make it nlog(n).
Can someone give me a pointer on how we can improve the performance of my implementation?

```<code>public class GameTime {

    public static Boolean canViewAll(Collection<BaseBallGame> baseBallGames) {

        List<BaseBallGame> games_list = (List<BaseBallGame>) baseBallGames;
        boolean isOverlap = false;

        for (int i = 0; i < games_list(); i++) {

            for (int j = i + 1; j < games_list(); j++) {

                Date startA = games_list(i).getStart();
                Date endA = games_list(i).getEnd();
                Date startB = games_list(j).getStart();
                Date endB = games_list(j).getEnd();

                boolean isStartABeforeEndB = (startA.compareTo(endB)) < 0;
                boolean isEndAAfterStartB = (endA.compareTo(startB)) > 0;

                boolean isCurrentPairOverlap = false;

                isCurrentPairOverlap = isStartABeforeEndB && isEndAAfterStartB;

                if (isCurrentPairOverlap) {
                    isOverlap = true;
                }
            }
        }
        return !isOverlap;
    }

    boolean overlap(Date start1, Date end1, Date start2, Date end2){
        return start1.getTime() <= end2.getTime() && start2.getTime() <= end1.getTime();
    }

    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("y-M-d H:m");

        ArrayList<BaseBallGame> baseBallGames = new ArrayList<BaseBallGame>();
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 20:00"), sdf.parse("2015-01-01 21:30")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 21:30"), sdf.parse("2015-01-01 23:00")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 23:10"), sdf.parse("2015-01-01 23:30")));

        System.out.println(GameTime.canViewAll(baseBallGames));
    }
}

class BaseBallGame {
    private Date start, end;

    public BaseBallGame(Date start, Date end) {
        this.start = start;
        this.end = end;
    }

    public Date getStart() {
        return this.start;
    }

    public Date getEnd() {
        return this.end;
    }

}
</code>```

答:
There are a bunch of sorting algorithms, you can implement them in your code. The below sorting algorithms on the websites have been implemented and also show the time complexity.

https://www.toptal.com/developers/sorting-algorithms

The Quicksort and Quicksort 3 way partition are nlogn algorithms.

Body:
I have a list of BaseBallGame objects with start and end time. I need to make sure that each game are happening at a separate time so that a user can watch the live stream of all the game.

I have an algorithm of O(n^2). I need to at least make it nlog(n).
Can someone give me a pointer on how we can improve the performance of my implementation?

public class GameTime {

    public static Boolean canViewAll(Collection<BaseBallGame> baseBallGames) {

        List<BaseBallGame> games_list = (List<BaseBallGame>) baseBallGames;
        boolean isOverlap = false;

        for (int i = 0; i < games_list(); i++) {

            for (int j = i + 1; j < games_list(); j++) {

                Date startA = games_list(i).getStart();
                Date endA = games_list(i).getEnd();
                Date startB = games_list(j).getStart();
                Date endB = games_list(j).getEnd();

                boolean isStartABeforeEndB = (startA.compareTo(endB)) < 0;
                boolean isEndAAfterStartB = (endA.compareTo(startB)) > 0;

                boolean isCurrentPairOverlap = false;

                isCurrentPairOverlap = isStartABeforeEndB && isEndAAfterStartB;

                if (isCurrentPairOverlap) {
                    isOverlap = true;
                }
            }
        }
        return !isOverlap;
    }

    boolean overlap(Date start1, Date end1, Date start2, Date end2){
        return start1.getTime() <= end2.getTime() && start2.getTime() <= end1.getTime();
    }

    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("y-M-d H:m");

        ArrayList<BaseBallGame> baseBallGames = new ArrayList<BaseBallGame>();
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 20:00"), sdf.parse("2015-01-01 21:30")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 21:30"), sdf.parse("2015-01-01 23:00")));
        baseBallGames.add(new BaseBallGame(sdf.parse("2015-01-01 23:10"), sdf.parse("2015-01-01 23:30")));

        System.out.println(GameTime.canViewAll(baseBallGames));
    }
}

class BaseBallGame {
    private Date start, end;

    public BaseBallGame(Date start, Date end) {
        this.start = start;
        this.end = end;
    }

    public Date getStart() {
        return this.start;
    }

    public Date getEnd() {
        return this.end;
    }

}


答:
You are describing the Activity Selection Problem

Sort the list based on the finish time.

Iterate the list and check if the start time of A[i+1] is greater than the end time of A[i].

And since it involves sorting it has a O(n log n)

Title: Efficient algorithm for comparing elements in the same list


问:
Fragment's content above Tab's text in TabLayout
I'm using TabLayout and I attach two tabs.

```<code>    tabLayout.addTab(tabLayout.newTab().setText("Featured"));
    tabLayout.addTab(tabLayout.newTab().setText("Filter"));
</code>```

Then onTabSelected() I display the fragment I want according to which tab user selected.

The layout of my Activity is :

```<code><LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:id="@+id/ll_container"
     android:orientation="vertical"
     android:layout_width="match_parent"
     android:layout_height="match_parent">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill"/>

    <FrameLayout
        android:id="@+id/fl_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>
</code>```

and the layout of the fragments is just a TextView in a LinearLayout :

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="Projects List Fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>
</code>```

But the result I get is the following :

as you can see the content of the fragment overlaps Tab's text when it should appear underneath.
Thanks

答:
Finally, I found alternative solution for this problem.

You can give top padding on your each Tab fragment's layout.

Eg,

android:paddingTop="?attr/actionBarSize"

For instance, my first tab xml looks like below:

```<code><android.support.design.widget.CoordinatorLayout 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:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="?attr/actionBarSize"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.upgautam.uddhav.productassignment.uicontrollers.ProductListFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/product_list_string" />

</android.support.design.widget.CoordinatorLayout>
</code>```

Now, the screen looks like below:

Body:
I'm using TabLayout and I attach two tabs.

    tabLayout.addTab(tabLayout.newTab().setText("Featured"));
    tabLayout.addTab(tabLayout.newTab().setText("Filter"));

Then onTabSelected() I display the fragment I want according to which tab user selected.

The layout of my Activity is :

<LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:id="@+id/ll_container"
     android:orientation="vertical"
     android:layout_width="match_parent"
     android:layout_height="match_parent">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill"/>

    <FrameLayout
        android:id="@+id/fl_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

and the layout of the fragments is just a TextView in a LinearLayout :

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="Projects List Fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

But the result I get is the following :

as you can see the content of the fragment overlaps Tab's text when it should appear underneath.
Thanks

Body:
Finally, I found alternative solution for this problem.

You can give top padding on your each Tab fragment's layout.

Eg,

android:paddingTop="?attr/actionBarSize"

For instance, my first tab xml looks like below:

<android.support.design.widget.CoordinatorLayout 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:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="?attr/actionBarSize"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.upgautam.uddhav.productassignment.uicontrollers.ProductListFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/product_list_string" />

</android.support.design.widget.CoordinatorLayout>

Now, the screen looks like below:


问:
Ansible error: /bin/sh: -c: line 0: unexpected EOF while looking for matching "
I am trying to use Ansible with several CoreOS virtual machines. I've installed ActivePython, and the binaries are recognized by the system. When I try to use a builtin Ansible module (ping) to test, it throws the following error:

```<code>deploy@kube-bh:~$ ansible dhcp-coreos155 -m ping
dhcp-coreos155 | FAILED! => {
    "changed": false,
    "failed": true,
    "module_stderr": "Shared connection to dhcp-coreos155 closed.\r\n",
    "module_stdout": "/bin/sh: -c: line 0: unexpected EOF while looking for matching `\"'\r\n/bin/sh: -c: line 1: syntax error: unexpected end of file\r\n",
    "msg": "MODULE FAILURE",
    "rc": 1
}
</code>```

Interestingly enough, if I run an Ansible command with -m raw, it succeeds:

```<code>deploy@kube-bh:~$ ansible dhcp-coreos155 -m raw -a 'uptime'
dhcp-coreos155 | SUCCESS | rc=0 >>
 20:02:21 up 1 day, 22:11,  2 users,  load average: 0.00, 0.00, 0.00
Shared connection to dhcp-coreos155 closed.
</code>```

I used the -vvvv flag on the failing command to see the connection state, and it appears SSH is connecting properly to the CoreOS node. I do glean a bit more information, but why the error is occurring is not clear.

```<code><dhcp-coreos155> ESTABLISH SSH CONNECTION FOR USER: deploy
<dhcp-coreos155> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o 'IdentityFile="/home/deploy/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=deploy -o ConnectTimeout=10 -o ControlPath=/home/deploy/.ansible/cp/6852b73873 -tt dhcp-coreos155 '/bin/sh -c '"'"'sudo -H -S -n -u root /bin/sh -c '"'"'"'"'"'"'"'"'echo BECOME-SUCCESS-fisdfsesqopuqybnmnfhfdijsvkmxvoh; /home/deploy/bin/python" /home/deploy/.ansible/tmp/ansible-tmp-1510602904.61-255211842882017/ping.py; rm -rf "/home/deploy/.ansible/tmp/ansible-tmp-1510602904.61-255211842882017/" > /dev/null 2>&1'"'"'"'"'"'"'"'"' && sleep 0'"'"''
<dhcp-coreos155> (1, '/bin/sh: -c: line 0: unexpected EOF while looking for matching `"\'\r\n/bin/sh: -c: line 1: syntax error: unexpected end of file\r\n', 'Shared connection to dhcp-coreos155 closed.\r\n')
</code>```

答:
To me it looks like you have messed with Python executable definition somewhere (you don't show the config, it's likely the Ansible inventory or ansible.cfg) -- there is an unbalanced quotation mark in the command Ansible executes:

```<code> /home/deploy/bin/python"
</code>```

Shell opens a quote, but before it finds matching closing quotation mark, the whole command ends, so  it throws an unexpected EOF-found exception.

raw module doesn't call Python, so there is no error.

Body:
I am trying to use Ansible with several CoreOS virtual machines. I've installed ActivePython, and the binaries are recognized by the system. When I try to use a builtin Ansible module (ping) to test, it throws the following error:

deploy@kube-bh:~$ ansible dhcp-coreos155 -m ping
dhcp-coreos155 | FAILED! => {
    "changed": false,
    "failed": true,
    "module_stderr": "Shared connection to dhcp-coreos155 closed.\r\n",
    "module_stdout": "/bin/sh: -c: line 0: unexpected EOF while looking for matching `\"'\r\n/bin/sh: -c: line 1: syntax error: unexpected end of file\r\n",
    "msg": "MODULE FAILURE",
    "rc": 1
}

Interestingly enough, if I run an Ansible command with -m raw, it succeeds:

deploy@kube-bh:~$ ansible dhcp-coreos155 -m raw -a 'uptime'
dhcp-coreos155 | SUCCESS | rc=0 >>
 20:02:21 up 1 day, 22:11,  2 users,  load average: 0.00, 0.00, 0.00
Shared connection to dhcp-coreos155 closed.

I used the -vvvv flag on the failing command to see the connection state, and it appears SSH is connecting properly to the CoreOS node. I do glean a bit more information, but why the error is occurring is not clear.

<dhcp-coreos155> ESTABLISH SSH CONNECTION FOR USER: deploy
<dhcp-coreos155> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o 'IdentityFile="/home/deploy/.ssh/id_rsa"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=deploy -o ConnectTimeout=10 -o ControlPath=/home/deploy/.ansible/cp/6852b73873 -tt dhcp-coreos155 '/bin/sh -c '"'"'sudo -H -S -n -u root /bin/sh -c '"'"'"'"'"'"'"'"'echo BECOME-SUCCESS-fisdfsesqopuqybnmnfhfdijsvkmxvoh; /home/deploy/bin/python" /home/deploy/.ansible/tmp/ansible-tmp-1510602904.61-255211842882017/ping.py; rm -rf "/home/deploy/.ansible/tmp/ansible-tmp-1510602904.61-255211842882017/" > /dev/null 2>&1'"'"'"'"'"'"'"'"' && sleep 0'"'"''
<dhcp-coreos155> (1, '/bin/sh: -c: line 0: unexpected EOF while looking for matching `"\'\r\n/bin/sh: -c: line 1: syntax error: unexpected end of file\r\n', 'Shared connection to dhcp-coreos155 closed.\r\n')

Body:
To me it looks like you have messed with Python executable definition somewhere (you don't show the config, it's likely the Ansible inventory or ansible.cfg) -- there is an unbalanced quotation mark in the command Ansible executes:

 /home/deploy/bin/python"

Shell opens a quote, but before it finds matching closing quotation mark, the whole command ends, so  it throws an unexpected EOF-found exception.

raw module doesn't call Python, so there is no error.


问:
Implementing ngOnChange to capture old and current value in Angular2
I was trying to implement ngOnChanges() to capture previous and current value. The function I have implemented works fine. I am able to see previous and current value in the console but I am getting this error even though my code is compiling successfully. I am getting the same error for "propertyName", "change", "current" and "previous". If I use 'const' instead of 'let' then my function doesn't work. Please help!!

Code:

```<code>import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
selector: 'app-simple',
templateUrl: './simple.component.html'
})
export class SimpleComponent implements OnChanges {
  @Input() simpleInput: string;

  ngOnChanges(changes: SimpleChanges) {
    for (let propertyName in changes) {
    let change = changes[propertyName];
    let current = JSON.stringify(change.currentValue);
    let previous = JSON.stringify(change.previousValue);
    console.log(propertyName + ' : currentvalue ' + current + ', previousvalue ' + previous);
    }
  }
}
</code>```

答:
This is an ESlint error: https://eslint.org/docs/rules/prefer-const

Your code will work fine, because there is nothing wrong with it programatically, it is just not good for readability as noted in the link I have provided. If you don't want to see the error, you can disable it in your tslint.json file. You can do this manually OR use the third option from the error dialog i.e. 'Remove rule prefer-const from tslint.json'.

Body:
I was trying to implement ngOnChanges() to capture previous and current value. The function I have implemented works fine. I am able to see previous and current value in the console but I am getting this error even though my code is compiling successfully. I am getting the same error for "propertyName", "change", "current" and "previous". If I use 'const' instead of 'let' then my function doesn't work. Please help!!

Code:

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
selector: 'app-simple',
templateUrl: './simple.component.html'
})
export class SimpleComponent implements OnChanges {
  @Input() simpleInput: string;

  ngOnChanges(changes: SimpleChanges) {
    for (let propertyName in changes) {
    let change = changes[propertyName];
    let current = JSON.stringify(change.currentValue);
    let previous = JSON.stringify(change.previousValue);
    console.log(propertyName + ' : currentvalue ' + current + ', previousvalue ' + previous);
    }
  }
}


问:
How to call web API under specific user permission?
I have a function that allows the end user to execute a Workflow (containing many APIs) or schedule it to run as a background job.

Example: User1 creates Workflow1, which contains 3 APIs (Api1, Api2, Api3), and configures it to run at 9AM every day.

I use HttpClient to call each API like this:

var client = new HttpClient { BaseAddress = new Uri("http://localhost/") };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync("/api/services/myApp/workflow/Api1?input=something", "").Result;
```

<p>How do I add the credentials of <code>User1</code> to the request while the user is not logged in to the application (because it will run automatically as a scheduled job)?</p>

<h1>Update 1</h1>

<p>I decided to use reflection to call an API by string name.</p>

<p>In the case of executing an API directly, how do I run it under a specific permission?</p>

<h1>Update 2</h1>

<p>I have put my code inside a <code>using</code> block, but all APIs were fired successfully:</p>

<pre class="lang-cs prettyprint-override"><code>using (_session.Use(1, 3)) // 3 is the Id of User1, who has no permissions
{
    // Execute operator
    switch (input.Operator.Type)
    {
        case "api":
            executeApiResult = await ExecuteApi(input);
            break;
        case "procedure":
            executeApiResult = await ExecuteProcedure(input);
            break;
        default:
            return new ExecuteOperatorOutput
            {
                Result = new ExecuteOperatorResult { Status = false, Message = $"Wrong operator type: {input.Operator.Type}" },
                WorkflowStatus = false
            };
    }
}
</code>```

答:
In the case of executing an API directly, how do I run it under a specific permission?

You can override current session values and call your method inside the using block.

I have put my code inside a using block, but all APIs were fired successfully

Declare your API methods as public virtual as there are some restrictions for AbpAuthorize.

Body:
I have a function that allows the end user to execute a Workflow (containing many APIs) or schedule it to run as a background job.

Example: User1 creates Workflow1, which contains 3 APIs (Api1, Api2, Api3), and configures it to run at 9AM every day.

I use HttpClient to call each API like this:

var client = new HttpClient { BaseAddress = new Uri("http://localhost/") };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync("/api/services/myApp/workflow/Api1?input=something", "").Result;

How do I add the credentials of User1 to the request while the user is not logged in to the application (because it will run automatically as a scheduled job)?

Update 1

I decided to use reflection to call an API by string name.

In the case of executing an API directly, how do I run it under a specific permission?

Update 2

I have put my code inside a using block, but all APIs were fired successfully:

using (_session.Use(1, 3)) // 3 is the Id of User1, who has no permissions
{
    // Execute operator
    switch (input.Operator.Type)
    {
        case "api":
            executeApiResult = await ExecuteApi(input);
            break;
        case "procedure":
            executeApiResult = await ExecuteProcedure(input);
            break;
        default:
            return new ExecuteOperatorOutput
            {
                Result = new ExecuteOperatorResult { Status = false, Message = $"Wrong operator type: {input.Operator.Type}" },
                WorkflowStatus = false
            };
    }
}


问:
Suppress Warning on Console when using Tess4j for OCRing
Help in Suppress Warning- "Warning. Invalid resolution 1 dpi. Using 70 instead." when using Tess4j for OCRing

Hi All, I would like to suppress the warning  thrown out in Console when using Tess4j for OCRing. Please help.

Tesseract uses Leptonica for some image processing internally and Leptonica thows this on console.

TIA

答:
A Workaround: Not from Leptonica(lept4j) but from Tesseract(tess4j) way. Setting the Resolution if the resolution of the image if it is less than 70.</p>

```<code>    TessAPI1.TessBaseAPISetImage2(handle, pix);
    //To remove the warning message "Warning. Invalid resolution 1 dpi. Using 70 instead." Setting the resolution
    int  res = TessAPI1.TessBaseAPIGetSourceYResolution(handle);
    if (res < 70)
        TessAPI1.TessBaseAPISetSourceResolution(handle, 70);
</code>```

Body:
A Workaround: Not from Leptonica(lept4j) but from Tesseract(tess4j) way. Setting the Resolution if the resolution of the image if it is less than 70.

    TessAPI1.TessBaseAPISetImage2(handle, pix);
    //To remove the warning message "Warning. Invalid resolution 1 dpi. Using 70 instead." Setting the resolution
    int  res = TessAPI1.TessBaseAPIGetSourceYResolution(handle);
    if (res < 70)
        TessAPI1.TessBaseAPISetSourceResolution(handle, 70);


答:
This is really a layout design flaw but if you must use this layout check if target is inside the passenger box.

You wouldn't have this problem if you wrapped the actual button elements into their own container

$(document).ready(function() {
  $(".btn-passenger").on('click', function(e) {
    if (!$(e.target).closest('.passenger-box').length) {
      $(".passenger-box").toggleClass("s");
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn-passenger {
  background-color: #eee;
  display: inline-block;
  height: 45px;
  cursor: pointer;
}

.passenger-box.s {
  visibility: visible;
  opacity: 1;
  transition: all .3s ease;
}

.passenger-box {
  padding: 10px 20px;
  background-color: #fff;
  border: 1px solid #eee;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  margin-top: 7px;
  position: relative;
  z-index: 99;
  opacity: 0;
  visibility: hidden;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

  0 click button

    Dewasa 12+ Thn
    <select name="adult" id="adult" class="form-control passenger">
      <option selected="selected">1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Anak 2-12 Thn
    <select name="child" id="child" class="form-control passenger">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Bayi
      < 2 Thn
    <select name="infant" id="infant" class="form-control passenger">
          <option>0</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
          <option>6</option>
        </select>

```

Title: How to do when selecting select option toggleClass not force close

Body:
This is really a layout design flaw but if you must use this layout check if target is inside the passenger box.

You wouldn't have this problem if you wrapped the actual button elements into their own container

$(document).ready(function() {
  $(".btn-passenger").on('click', function(e) {
    if (!$(e.target).closest('.passenger-box').length) {
      $(".passenger-box").toggleClass("s");
    }
  });
});

.btn-passenger {
  background-color: #eee;
  display: inline-block;
  height: 45px;
  cursor: pointer;
}

.passenger-box.s {
  visibility: visible;
  opacity: 1;
  transition: all .3s ease;
}

.passenger-box {
  padding: 10px 20px;
  background-color: #fff;
  border: 1px solid #eee;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  margin-top: 7px;
  position: relative;
  z-index: 99;
  opacity: 0;
  visibility: hidden;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="btn-passenger">
  <i class="fa fa-user" aria-hidden="true"></i>
  <span id="count">0 click button</span>
  <i class="fa fa-angle-down" aria-hidden="true"></i>
  <div class="passenger-box">
    <label>Dewasa 12+ Thn</label>
    <select name="adult" id="adult" class="form-control passenger">
      <option selected="selected">1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    <label>Anak 2-12 Thn</label>
    <select name="child" id="child" class="form-control passenger">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    <label>Bayi
      < 2 Thn</label>
    <select name="infant" id="infant" class="form-control passenger">
          <option>0</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
          <option>6</option>
        </select>
  </div>
</div>


问:
CodeIgniter join table
This is my output // As you can see the Name is not the exact name

And I found a code to solve this problem but I'm not really sure about which coding should I have to use. Can you please help?

This is a set of function coding:

```<code><?php

$rn= "0001123456";
$rn2= "A123456";
$dob = "1986-10-25";
$dreg = "1986-10-26";

echo "<br/>".$rn;
echo "<br/>".numberToAlpha($rn);
echo "<br/>".alphaToNumber($rn2);
echo "<br/>cur_age : ".calculateCurrentAge($dob);
echo "<br/>reg_age : ".calculateRegisterAge($dob, $dreg);
/*** End Contoh Penggunaan ***/

function numberToAlpha($rn)
{
  if (strcmp('0000', substr($rn,0,4)) == 0) {
    $rn = 'A'.substr($rn, 4, 6);
  }else{
    $rn = 'B'.substr($rn, 4, 6);
  }

  return $rn;

}

function alphaToNumber($rn)
{
  if (strcmp('A', substr($rn,0,1)) == 0) {
    $rn = '0000'.substr($rn, 1, 6);
  }else{
    $rn = '0001'.substr($rn, 1, 6);
  }

  return $rn;
}

function calculateCurrentAge($dob)
{
    $from = DateTime::createFromFormat('Y-m-d', $dob);

    $to = new DateTime('today +1 day');

    $age = $from->diff($to);

    return $age->format('%y years, %m months, %d days');
}

function calculateRegisterAge($dob, $dreg)
{
    $from = DateTime::createFromFormat('Y-m-d', $dob);
    $to = DateTime::createFromFormat('Y-m-d', $dreg);
    $to = $to->modify('+1 day');

    $age = $from->diff($to);

    return $age->format('%y years, %m months, %d days');
}
</code>```

Can you tell me if I want to change the Name to a proper Name which coding should I use and where to add these coding?

This is my controllers 'Search.php'：

```<code><?php

class Search extends CI_Controller {

    public function __construct()
    {
        parent::__construct();

        $this->load->helper('form');

        $this->load->model('Search_model');
    }

    public function index()
    {
        $this->load->view('search_form');
    }

    public function execute_search()
    {
        // Retrieve the posted search term.
        $search_term = $this->input->post('search');

        // Use a model to retrieve the results.
        $data['results'] = $this->Search_model->get_results($search_term);

        // Pass the results to the view.
        $this->load->view('search_results',$data);
    }
}
</code>```

This is model 'Search_model.php':

```<code><?php

class Search_model extends CI_Model {

    public function get_results($search_term='default')
    {
        // Use the Active Record class for safer queries.
        $this->db->select('rn,nama,tarikhlahir,jantina,agama,bangsa');
        $this->db->from('pesakit');
        $this->db->like('rn',$search_term);
        $this->db->limit(100);

        // Execute the query.
        $query = $this->db->get();

        // Return the results.
        return $query->result_array();
    }
}
</code>```

This is views for search 'search_form.php':

```<code><?php
    echo form_open('search/execute_search');

    echo form_input(array('name'=>'search'));

    echo form_submit('search_submit','Submit');

?>
</code>```

This is results views 'search_results.php'：

```<code><div>
    <?php
        // List up all results.
        foreach ($results as $val)
        {
            echo 'RN : '; echo $val['rn']; echo "<br/>";
            echo 'Name : '; echo $val['nama']; echo "<br/>";
            echo 'Date.of.Birth : '; echo $val['tarikhlahir']; echo "<br/>";
            echo 'Gender : '; echo $val['jantina']; echo "<br/>";
            echo 'Race : '; echo $val['bangsa']; echo "<br/>";
            echo 'Religion : '; echo $val['agama'];
        }
    ?>
</div>
</code>```

答:
I can see an error in your model

Please replace

```<code>$this->db->select('jantina','bangsa','agama');
</code>```

With

```<code>$this->db->select('jantina,bangsa,agama');
</code>```

And in your view

```<code><div>
    <?php
        // List up all results.
        foreach ($results as $val)
        {
            echo $val['jantina'].'<br>';
            echo $val['bangsa'].'<br>';
            echo $val['agama'];
        }
    ?>
</div>
</code>```

ContentLicense: CC BY-SA 4.0

Title: CodeIgniter join table

Body:
This is my output // As you can see the Name is not the exact name

And I found a code to solve this problem but I'm not really sure about which coding should I have to use. Can you please help?

This is a set of function coding:

<?php

$rn= "0001123456";
$rn2= "A123456";
$dob = "1986-10-25";
$dreg = "1986-10-26";

echo "
".$rn;
echo "
".numberToAlpha($rn);
echo "
".alphaToNumber($rn2);
echo "
cur_age : ".calculateCurrentAge($dob);
echo "
reg_age : ".calculateRegisterAge($dob, $dreg);
/*** End Contoh Penggunaan ***/

function numberToAlpha($rn)
{
  if (strcmp('0000', substr($rn,0,4)) == 0) {
    $rn = 'A'.substr($rn, 4, 6);
  }else{
    $rn = 'B'.substr($rn, 4, 6);
  }

  return $rn;

}

function alphaToNumber($rn)
{
  if (strcmp('A', substr($rn,0,1)) == 0) {
    $rn = '0000'.substr($rn, 1, 6);
  }else{
    $rn = '0001'.substr($rn, 1, 6);
  }

  return $rn;
}

function calculateCurrentAge($dob)
{
    $from = DateTime::createFromFormat('Y-m-d', $dob);

    $to = new DateTime('today +1 day');

    $age = $from->diff($to);

    return $age->format('%y years, %m months, %d days');
}

function calculateRegisterAge($dob, $dreg)
{
    $from = DateTime::createFromFormat('Y-m-d', $dob);
    $to = DateTime::createFromFormat('Y-m-d', $dreg);
    $to = $to->modify('+1 day');

    $age = $from->diff($to);

    return $age->format('%y years, %m months, %d days');
}

Can you tell me if I want to change the Name to a proper Name which coding should I use and where to add these coding?

This is my controllers 'Search.php'：

<?php

class Search extends CI_Controller {

    public function __construct()
    {
        parent::__construct();

        $this->load->helper('form');

        $this->load->model('Search_model');
    }

    public function index()
    {
        $this->load->view('search_form');
    }

    public function execute_search()
    {
        // Retrieve the posted search term.
        $search_term = $this->input->post('search');

        // Use a model to retrieve the results.
        $data['results'] = $this->Search_model->get_results($search_term);

        // Pass the results to the view.
        $this->load->view('search_results',$data);
    }
}

This is model 'Search_model.php':

<?php

class Search_model extends CI_Model {

    public function get_results($search_term='default')
    {
        // Use the Active Record class for safer queries.
        $this->db->select('rn,nama,tarikhlahir,jantina,agama,bangsa');
        $this->db->from('pesakit');
        $this->db->like('rn',$search_term);
        $this->db->limit(100);

        // Execute the query.
        $query = $this->db->get();

        // Return the results.
        return $query->result_array();
    }
}

This is views for search 'search_form.php':

<?php
    echo form_open('search/execute_search');

    echo form_input(array('name'=>'search'));

    echo form_submit('search_submit','Submit');

?>

This is results views 'search_results.php'：

    <?php
        // List up all results.
        foreach ($results as $val)
        {
            echo 'RN : '; echo $val['rn']; echo "
";
            echo 'Name : '; echo $val['nama']; echo "
";
            echo 'Date.of.Birth : '; echo $val['tarikhlahir']; echo "
";
            echo 'Gender : '; echo $val['jantina']; echo "
";
            echo 'Race : '; echo $val['bangsa']; echo "
";
            echo 'Religion : '; echo $val['agama'];
        }
    ?>

Body:
I can see an error in your model

Please replace

$this->db->select('jantina','bangsa','agama');

With

$this->db->select('jantina,bangsa,agama');

And in your view

<div>
    <?php
        // List up all results.
        foreach ($results as $val)
        {
            echo $val['jantina'].'<br>';
            echo $val['bangsa'].'<br>';
            echo $val['agama'];
        }
    ?>
</div>


问:
What is the difference between an array with shape (N,1) and one with shape (N)? And how to convert between the two?
Python newbie here coming from a MATLAB background.

I have a 1 column array and I want to move that column into the first column of a 3 column array. With a MATLAB background this is what I would do:

```<code>import numpy as np

A = np.zeros([150,3]) #three column array

B = np.ones([150,1]) #one column array which needs to replace the first column of A

#MATLAB-style solution:

A[:,0] = B
</code>```

However this does not work because the "shape" of A is (150,3) and the "shape" of B is (150,1). And apparently the command A[:,0] results in a "shape" of (150).

Now, what is the difference between (150,1) and (150)? Aren't they the same thing: a column vector? And why isn't Python "smart enough" to figure out that I want to put the column vector, B, into the first column of A?

Is there an easy way to convert a 1-column vector with shape (N,1) to a 1-column vector with shape (N)?

I am new to Python and this seems like a really silly thing that MATLAB does much better...

答:
Several things are different.  In numpy arrays may be 0d or 1d or higher.  In MATLAB 2d is the smallest (and at one time the only dimensions).  MATLAB readily expands dimensions the end because it is Fortran ordered.  numpy, is by default c ordered, and most readily expands dimensions at the front.

```<code>In [1]: A = np.zeros([5,3])
In [2]: A[:,0].shape
Out[2]: (5,)
</code>```

Simple indexing reduces a dimension, regardless whether it's A[0,:] or A[:,0].  Contrast that with happens to a 3d MATLAB matrix, A(1,:,:) v A(:,:,1).

numpy does broadcasting, adjusting dimensions during operations like sum and assignment.  One basic rule is that dimensions may be automatically expanded toward the start if needed:

```<code>In [3]: A[:,0] = np.ones(5)
In [4]: A[:,0] = np.ones([1,5])
In [5]: A[:,0] = np.ones([5,1])
...
ValueError: could not broadcast input array from shape (5,1) into shape (5)
</code>```

It can change (5,) LHS to (1,5), but can't change it to (5,1).

Another broadcasting example, +:

```<code>In [6]: A[:,0] + np.ones(5);
In [7]: A[:,0] + np.ones([1,5]);
In [8]: A[:,0] + np.ones([5,1]);
</code>```

Now the (5,) works with (5,1), but that's because it becomes (1,5), which together with (5,1) produces (5,5) - an outer product broadcasting:

```<code>In [9]: (A[:,0] + np.ones([5,1])).shape
Out[9]: (5, 5)
</code>```

In Octave

```<code>>> x = ones(2,3,4);
>> size(x(1,:,:))
ans =
   1   3   4
>> size(x(:,:,1))
ans =
   2   3
>> size(x(:,1,1) )
ans =
   2   1
>> size(x(1,1,:) )
ans =
   1   1   4
</code>```

To do the assignment that you want you adjust either side

Index in a way that preserves the number of dimensions:

```<code>In [11]: A[:,[0]].shape
Out[11]: (5, 1)
In [12]: A[:,[0]] = np.ones([5,1])
</code>```

transpose the (5,1) to (1,5):

```<code>In [13]: A[:,0] = np.ones([5,1]).T
</code>```

flatten/ravel the (5,1) to (5,):

```<code>In [14]: A[:,0] = np.ones([5,1]).flat
In [15]: A[:,0] = np.ones([5,1])[:,0]
</code>```

squeeze, ravel also work.

Some quick tests in Octave indicate that it is more forgiving when it comes to dimensions mismatch.  But the numpy prioritizes consistency.  Once the broadcasting rules are understood, the behavior makes sense.

Body:
Python newbie here coming from a MATLAB background.

I have a 1 column array and I want to move that column into the first column of a 3 column array. With a MATLAB background this is what I would do:

import numpy as np

A = np.zeros([150,3]) #three column array

B = np.ones([150,1]) #one column array which needs to replace the first column of A

#MATLAB-style solution:

A[:,0] = B

However this does not work because the "shape" of A is (150,3) and the "shape" of B is (150,1). And apparently the command A[:,0] results in a "shape" of (150).

Now, what is the difference between (150,1) and (150)? Aren't they the same thing: a column vector? And why isn't Python "smart enough" to figure out that I want to put the column vector, B, into the first column of A?

Is there an easy way to convert a 1-column vector with shape (N,1) to a 1-column vector with shape (N)?

I am new to Python and this seems like a really silly thing that MATLAB does much better...

Body:
Several things are different.  In numpy arrays may be 0d or 1d or higher.  In MATLAB 2d is the smallest (and at one time the only dimensions).  MATLAB readily expands dimensions the end because it is Fortran ordered.  numpy, is by default c ordered, and most readily expands dimensions at the front.

In [1]: A = np.zeros([5,3])
In [2]: A[:,0].shape
Out[2]: (5,)

Simple indexing reduces a dimension, regardless whether it's A[0,:] or A[:,0].  Contrast that with happens to a 3d MATLAB matrix, A(1,:,:) v A(:,:,1).

numpy does broadcasting, adjusting dimensions during operations like sum and assignment.  One basic rule is that dimensions may be automatically expanded toward the start if needed:

In [3]: A[:,0] = np.ones(5)
In [4]: A[:,0] = np.ones([1,5])
In [5]: A[:,0] = np.ones([5,1])
...
ValueError: could not broadcast input array from shape (5,1) into shape (5)

It can change (5,) LHS to (1,5), but can't change it to (5,1).

Another broadcasting example, +:

In [6]: A[:,0] + np.ones(5);
In [7]: A[:,0] + np.ones([1,5]);
In [8]: A[:,0] + np.ones([5,1]);

Now the (5,) works with (5,1), but that's because it becomes (1,5), which together with (5,1) produces (5,5) - an outer product broadcasting:

In [9]: (A[:,0] + np.ones([5,1])).shape
Out[9]: (5, 5)

In Octave

>> x = ones(2,3,4);
>> size(x(1,:,:))
ans =
   1   3   4
>> size(x(:,:,1))
ans =
   2   3
>> size(x(:,1,1) )
ans =
   2   1
>> size(x(1,1,:) )
ans =
   1   1   4

To do the assignment that you want you adjust either side

Index in a way that preserves the number of dimensions:

In [11]: A[:,[0]].shape
Out[11]: (5, 1)
In [12]: A[:,[0]] = np.ones([5,1])

transpose the (5,1) to (1,5):

In [13]: A[:,0] = np.ones([5,1]).T

flatten/ravel the (5,1) to (5,):

In [14]: A[:,0] = np.ones([5,1]).flat
In [15]: A[:,0] = np.ones([5,1])[:,0]

squeeze, ravel also work.

Some quick tests in Octave indicate that it is more forgiving when it comes to dimensions mismatch.  But the numpy prioritizes consistency.  Once the broadcasting rules are understood, the behavior makes sense.


问:
Validate the user's input of only 0's and 1's
I have to convert an 8-bit binary number to a decimal number. I believe that I have the conversion correct along with validating if the user inputted an 8-bit binary number (no more, no less) but I am stuck on validating the user's input for only 0's and 1's.

Any help would be great. I feel like I am overthinking this but I tried everything.

Here is the code I have:

```<code>while True:
binary = input("Please enter a 8-bit binary number: ")
if len(binary) < 8 or len(binary) > 8:
    print("Must be an 8 bit binary!")

else:
    print(int(binary, 2))
    break
</code>```

答:
Ok, first thing first, you use this line:

```<code>if len(binary) < 8 or len(binary) > 8:
</code>```

it is way more readable to just say:

```<code>if len(binary) != 8
</code>```

Now this is how I would implement your code:

```<code>while True:
    binary = input("Please enter a 8-bit binary number: ")

    for item in binary:
        if item not in {'0','1'}:
            print("Must only contains 0's and 1's !")
            break

    if len(binary) != 8:
        print("Must be an 8 bit binary!")

    else:
        print(int(binary, 2))
        break
</code>```

Note that this will check for both validations you expected while providing a relevant insight to the user depending on his particular mistake.

Body:
I have to convert an 8-bit binary number to a decimal number. I believe that I have the conversion correct along with validating if the user inputted an 8-bit binary number (no more, no less) but I am stuck on validating the user's input for only 0's and 1's.

Any help would be great. I feel like I am overthinking this but I tried everything.

Here is the code I have:

while True:
binary = input("Please enter a 8-bit binary number: ")
if len(binary) < 8 or len(binary) > 8:
    print("Must be an 8 bit binary!")

else:
    print(int(binary, 2))
    break

Body:
Ok, first thing first, you use this line:

if len(binary) < 8 or len(binary) > 8:

it is way more readable to just say:

if len(binary) != 8

Now this is how I would implement your code:

while True:
    binary = input("Please enter a 8-bit binary number: ")

    for item in binary:
        if item not in {'0','1'}:
            print("Must only contains 0's and 1's !")
            break

    if len(binary) != 8:
        print("Must be an 8 bit binary!")

    else:
        print(int(binary, 2))
        break

Note that this will check for both validations you expected while providing a relevant insight to the user depending on his particular mistake.


问:
Select random column where minimum total values are same
I need random column where column values are same. Here d1, d2, d3 column values are same. Least column becomes only the d1 column not d2 or d3.

```<code>id  date                    name    d1  d2  d3  d4  least_val   least_col
1   2017-02-10T09:00:00Z    bimal   1   2   3   4   1           d1
2   2017-02-10T09:00:00Z    amal    8   7   4   5   8           d1
3   2017-02-10T09:00:00Z    kamal   9   9   11  12  9           d1
</code>```

```<code>    select f.*,
       (case ff.least_col
             when 'd1' then d1
             when 'd2' then d2
             when 'd3' then d3
             when 'd4' then d4
        end) as least_val,
        ff.least_col
from formal f cross join
     (select least(sum(d1), sum(d2), sum(d3), sum(d4)) as least_val,
             (case least(sum(d1), sum(d2), sum(d3), sum(d4))
                   when sum(d1) then 'd1'
                   when sum(d2) then 'd2'
                   when sum(d3) then 'd3'
                   when sum(d4) then 'd4'
              end) as least_col
      from formal
     ) ff;
</code>```

See the SQL Fiddle

Is it possible to get least_col randomly it means least column will be either d1 or d2 or d3 not always d1. I want to say, every execution time least_col will be changed where values are same?

答:
Try this answer, Hope this helps you:

```<code>select *,Case When d1 < d2 And d1 < d3 And d1<d4 Then d1
            When d2 < d1 And d2 < d3 And d2<d4 Then d2
            When d3 < d1 And d3 < d2 And d3<d4 Then d3
            Else d4 end Least_Value
         ,Case When d1 < d2 And d1 < d3 And d1<d4 Then 'd1'
            When d2 < d1 And d2 < d3 And d2<d4 Then 'd2'
            When d3 < d1 And d3 < d2 And d3<d4 Then 'd3'
            Else 'd4' end Least_Column
from formal
</code>```

Check the answer in:

SQL Fiddle

Body:
I need random column where column values are same. Here d1, d2, d3 column values are same. Least column becomes only the d1 column not d2 or d3.

id  date                    name    d1  d2  d3  d4  least_val   least_col
1   2017-02-10T09:00:00Z    bimal   1   2   3   4   1           d1
2   2017-02-10T09:00:00Z    amal    8   7   4   5   8           d1
3   2017-02-10T09:00:00Z    kamal   9   9   11  12  9           d1

    select f.*,
       (case ff.least_col
             when 'd1' then d1
             when 'd2' then d2
             when 'd3' then d3
             when 'd4' then d4
        end) as least_val,
        ff.least_col
from formal f cross join
     (select least(sum(d1), sum(d2), sum(d3), sum(d4)) as least_val,
             (case least(sum(d1), sum(d2), sum(d3), sum(d4))
                   when sum(d1) then 'd1'
                   when sum(d2) then 'd2'
                   when sum(d3) then 'd3'
                   when sum(d4) then 'd4'
              end) as least_col
      from formal
     ) ff;

See the SQL Fiddle

Is it possible to get least_col randomly it means least column will be either d1 or d2 or d3 not always d1. I want to say, every execution time least_col will be changed where values are same?

Body:
Try this answer, Hope this helps you:

select *,Case When d1 < d2 And d1 < d3 And d1<d4 Then d1
            When d2 < d1 And d2 < d3 And d2<d4 Then d2
            When d3 < d1 And d3 < d2 And d3<d4 Then d3
            Else d4 end Least_Value
         ,Case When d1 < d2 And d1 < d3 And d1<d4 Then 'd1'
            When d2 < d1 And d2 < d3 And d2<d4 Then 'd2'
            When d3 < d1 And d3 < d2 And d3<d4 Then 'd3'
            Else 'd4' end Least_Column
from formal

Check the answer in:

SQL Fiddle


问:
How to Make NSVisualEffectView That Only Appears When Content is Beneath It
I am working on a macOS application that makes use of NSVisualEffectView to achieve transparency. I want to achieve an effect similar to that of iOS' Cover Sheet widget view. Notice how when you scroll up, content a blur appears around the search bar. I want do this in a macOS app so that when content in a table view is scrolled beneath a certain point an NSVisualEffectView blurs it. How would I do this? Thanks in advance.</p>

答:
Create a instance of Visual Effect View as following and set on window:</p>

```<code>func setVisualEffectToWindow(window: NSWindow) {
        // create the visual effect view
var blurryView = NSVisualEffectView(frame: NSRect(x: 0, y: 0, width: 800, height: 600)) //Create with size you want or you can use window content bound here
    // this is default value but is here for clarity
    blurryView.blendingMode = NSVisualEffectBlendingMode.BehindWindow

    // set the background to always be the dark blur
    blurryView.material = NSVisualEffectMaterial.Dark

    // set it to always be blurry regardless of window state
    blurryView.state = NSVisualEffectState.Active

    window.contentView.addSubview(blurryView)
}
</code>```

Body:
Create a instance of Visual Effect View as following and set on window:

func setVisualEffectToWindow(window: NSWindow) {
        // create the visual effect view
var blurryView = NSVisualEffectView(frame: NSRect(x: 0, y: 0, width: 800, height: 600)) //Create with size you want or you can use window content bound here
    // this is default value but is here for clarity
    blurryView.blendingMode = NSVisualEffectBlendingMode.BehindWindow

    // set the background to always be the dark blur
    blurryView.material = NSVisualEffectMaterial.Dark

    // set it to always be blurry regardless of window state
    blurryView.state = NSVisualEffectState.Active

    window.contentView.addSubview(blurryView)
}


问:
Combine two arrays in specific order
I need to combine these two arrays:

```<code>A = ["Dog", "Cat", "Bird"]
B = ["John", "Doe", "Foo"]
</code>```

I must take the first element of the first array and then the first element of the second array, then the second element of the first array and the second element of the second array and so on. It has to be in this exact order:

```<code>["Dog", "John", "Cat", "Doe", "Bird", "Foo"]
</code>```

答:
You can use Array#zip to get [[A[0], B[0]], [A[1], B[1]], ...]

```<code>A.zip(B)
# => [["Dog", "John"], ["Cat", "Doe"], ["Bird", "Foo"]]
</code>```

Flattening it will give you what you want:

```<code>A.zip(B).flatten
# => ["Dog", "John", "Cat", "Doe", "Bird", "Foo"]
</code>```

UPDATE alternative using Enumerable#flat_map:

```<code>(0...A.size).map { |i| [A[i], B[i]] }
# => [["Dog", "John"], ["Cat", "Doe"], ["Bird", "Foo"]]
(0...A.size).flat_map { |i| [A[i], B[i]] }
# => ["Dog", "John", "Cat", "Doe", "Bird", "Foo"]
</code>```

Title: Combine two arrays in specific order

Body:
I need to combine these two arrays:

A = ["Dog", "Cat", "Bird"]
B = ["John", "Doe", "Foo"]

I must take the first element of the first array and then the first element of the second array, then the second element of the first array and the second element of the second array and so on. It has to be in this exact order:

["Dog", "John", "Cat", "Doe", "Bird", "Foo"]

Body:
You can use Array#zip to get [[A[0], B[0]], [A[1], B[1]], ...]

A.zip(B)
# => [["Dog", "John"], ["Cat", "Doe"], ["Bird", "Foo"]]

Flattening it will give you what you want:

A.zip(B).flatten
# => ["Dog", "John", "Cat", "Doe", "Bird", "Foo"]

UPDATE alternative using Enumerable#flat_map:

(0...A.size).map { |i| [A[i], B[i]] }
# => [["Dog", "John"], ["Cat", "Doe"], ["Bird", "Foo"]]
(0...A.size).flat_map { |i| [A[i], B[i]] }
# => ["Dog", "John", "Cat", "Doe", "Bird", "Foo"]


问:
How to do a LIKE in Entity Framework CORE (not full .net)
There are Q+A's for Entity Framework LIKE's in the Full .net framework:

How to do SQL Like % in Linq?

Like Operator in Entity Framework?

eg:

```<code>from c in dc.Organization
where SqlMethods.Like(c.Boss, "%Jeremy%")
</code>```

This doesn't work in EF Core:

The name SqlMethods does not exist in the current context.

So how do you do a LIKE using Entity Framework CORE?

答:
The LIKE function has moved under EF.Functions in Core:

```<code>from c in dc.Organization
where EF.Functions.Like(c.Boss, "%Jeremy%")
</code>```

Body:
There are Q+A's for Entity Framework LIKE's in the Full .net framework:

How to do SQL Like % in Linq?

Like Operator in Entity Framework?

eg:

from c in dc.Organization
where SqlMethods.Like(c.Boss, "%Jeremy%")

This doesn't work in EF Core:

The name SqlMethods does not exist in the current context.

So how do you do a LIKE using Entity Framework CORE?

Body:
The LIKE function has moved under EF.Functions in Core:

from c in dc.Organization
where EF.Functions.Like(c.Boss, "%Jeremy%")


问:
Object detection from image using vision framework
I am trying to detect objects from a given image. From research I just found that we can detect and track an object for the videos using the following process:

```<code>private lazy var cameraLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)

private func tapGestureAction(recognizer: UITapGestureRecognizer)
 {
   highlightView.frame.size = CGSize(width: 200, height: 200)
   highlightView.center = recognizer.location(in: view)

   let originalRect = highlightView.frame
   var convertedRect = cameraLayer.metadataOutputRectConverted(fromLayerRect: originalRect)
   convertedRect.origin.y = 1 - convertedRect.origin.y

   previousObservation = VNDetectedObjectObservation(boundingBox: convertedRect)
 }
</code>```

Can we have similar method like metadataOutputRectConverted for imageView? I am trying to detect the object rect whenever the user taps on that object. How can this be accomplished?

答: this method to convert the camera output rect ( topleft(0,0) to bottomright(0,1)) to the UI rect. So, I think you do not need to convert it</p>

Body:
I am trying to detect objects from a given image. From research I just found that we can detect and track an object for the videos using the following process:

private lazy var cameraLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)

private func tapGestureAction(recognizer: UITapGestureRecognizer)
 {
   highlightView.frame.size = CGSize(width: 200, height: 200)
   highlightView.center = recognizer.location(in: view)

   let originalRect = highlightView.frame
   var convertedRect = cameraLayer.metadataOutputRectConverted(fromLayerRect: originalRect)
   convertedRect.origin.y = 1 - convertedRect.origin.y

   previousObservation = VNDetectedObjectObservation(boundingBox: convertedRect)
 }

Can we have similar method like metadataOutputRectConverted for imageView? I am trying to detect the object rect whenever the user taps on that object. How can this be accomplished?


问:
Angular4 importing local js file indicates 404 not found
I set up a new project using "ng new xxx",
 just add one line in index.html:

<!doctype html>

  <meta charset="utf-8">
  <title>Bbb</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

```

Then put the JS file in the same dir as index.html

the same dir

But when I run "ng server", the browser always show: 404

the js file not found

Does anyone know why? Thanks in advance.

答:
I was going through same issue with JSON file, so what I done is kept my JSON file in to assets folder. And access it through my code.

Here in Project file review you can also verify it.

Body:
I set up a new project using "ng new xxx",
 just add one line in index.html:

<!doctype html>

  <meta charset="utf-8">
  <title>Bbb</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

Then put the JS file in the same dir as index.html

the same dir

But when I run "ng server", the browser always show: 404

the js file not found

Does anyone know why? Thanks in advance.


问:
Populating 2d array zig zag with consecutive numbers C++
I'm stuck on this. Could you please help me?

Write   a   function    which   initialize  a   two-dimensional array.  The array   is  a square

matrix  (i.e.,  its width   and height  are identical.) The array   should  be  initialized in  the
zig-zag style.  Specifically,   we  start   at  the top-left    corner  and go  downward,   and put a

number  starting from   1.  Once    we  hit the bottom, we  go  to  the next    column  and fill    in

the numbers from    bottom  to  top.    We  fill    the numbers downward    in  the third

column, upward  in  the fourth  column, and so  on. The process ends when   all the
elements    in  the array   are filled.

```<code>However, How do I get my output like this?
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25

#include <iomanip>
#include <iostream>
using namespace std;
const int SIZE = 5; // Note SIZE can be anything between 1 to 9
void initGrid(int grid[SIZE][SIZE]);
void printGrid(int grid[SIZE][SIZE]);
int main() {
    int grid[SIZE][SIZE];
    initGrid(grid);
    printGrid(grid);
}
void initGrid(int grid[SIZE][SIZE]) {
    int inc = 1;
    for (int j = 0; j < SIZE; j++) {
        for (int i = 0; i < SIZE; i++) {
             grid[i][j] = inc;
             inc++;
        }
    }
}
void printGrid(int grid[SIZE][SIZE]) {
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            // setw() function handles the printing format.
            cout << setw(2) << grid[i][j] << " ";
        }
        cout << endl;
    }
}
</code>```

答:
Firstly, if I was writing this program I would represent my data in a different manner. I.e. I would likely use a vector and avoid global size constants. The being said, here is how I would do this. Let's write out the sequence the indexes follow and try to see if we can create some kind of sequence.

```<code>1 4 7
2 5 8
3 6 9
</code>```

Is what is in your array after creating it and we want

```<code>1 6 7
2 5 8
3 4 9
</code>```

Our indexes to the original array looks like this

```<code>(0, 0) (2, 1) (0, 2)
(1, 0) (1, 1) (1, 2)
(2, 0) (0, 1) (2, 2)
</code>```

Well our j component is easy, it's just a simple arithmetic sequence where you add 1, i.e. 1, 2, 3, 4, 5...

```<code>for (int j = 0; j < 3; j++){
  ...
}
</code>```

Now we need a sequence that follows the patten 0, 1, 2, 2, 1, 0, 0, 1, 2, ... repeating. Since we have repeating digits, I am thinking of clock arithmetic or modular arithmetic. Let's start with the sequence 0, 1, 2, 0, 1, 2 ... repeating. I.e the integers mod 3 (Z mod 3). For the first column we want the indicies straight up as they are (Z mod 3). Then for the reversed columns let's say we are given this sequence and we are iterating through it from 0 to 2. We can cleverly use modular arithmetic to get to our reversed sequence. For example if we had (2 mod 3), (4 mod 3), (6 mod 3), we would have 2, 1, 0. How do we get 0, 1, 2 to 2, 4, 6? Like this f(x) : (x + 1) * 2.

```<code>bool reversed = false;
for (int i = 0; i < 3; i++){
    int idx = i;
    if(reversed){
      int offset = (i + 1) * 2;
      idx = (offset) % 3;
    }
}
reversed = !reversed;
</code>```

Now we just have to put it all together. This should be our new init grid as the print function is fine.

```<code>for (int j = 0; j < SIZE; j++){
  bool reversed = false;
  for (int i = 0; i < SIZE; i++){
    int idx = i;
    if(reversed){
      int offset = (i + 1) * (SIZE - 1);
      idx = (offset) % SIZE;
    }
    arr[idx][j] = inc;
    inc++;
  }
  reversed = !reversed;
}
</code>```

That should do it. I got it to work in repl.it, hopefully this helps.

Body:
I'm stuck on this. Could you please help me?

Write   a   function    which   initialize  a   two-dimensional array.  The array   is  a square

matrix  (i.e.,  its width   and height  are identical.) The array   should  be  initialized in  the
zig-zag style.  Specifically,   we  start   at  the top-left    corner  and go  downward,   and put a

number  starting from   1.  Once    we  hit the bottom, we  go  to  the next    column  and fill    in

the numbers from    bottom  to  top.    We  fill    the numbers downward    in  the third

column, upward  in  the fourth  column, and so  on. The process ends when   all the
elements    in  the array   are filled.

However, How do I get my output like this?
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25

#include <iomanip>
#include <iostream>
using namespace std;
const int SIZE = 5; // Note SIZE can be anything between 1 to 9
void initGrid(int grid[SIZE][SIZE]);
void printGrid(int grid[SIZE][SIZE]);
int main() {
    int grid[SIZE][SIZE];
    initGrid(grid);
    printGrid(grid);
}
void initGrid(int grid[SIZE][SIZE]) {
    int inc = 1;
    for (int j = 0; j < SIZE; j++) {
        for (int i = 0; i < SIZE; i++) {
             grid[i][j] = inc;
             inc++;
        }
    }
}
void printGrid(int grid[SIZE][SIZE]) {
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            // setw() function handles the printing format.
            cout << setw(2) << grid[i][j] << " ";
        }
        cout << endl;
    }
}

Body:
Firstly, if I was writing this program I would represent my data in a different manner. I.e. I would likely use a vector and avoid global size constants. The being said, here is how I would do this. Let's write out the sequence the indexes follow and try to see if we can create some kind of sequence.

1 4 7
2 5 8
3 6 9

Is what is in your array after creating it and we want

1 6 7
2 5 8
3 4 9

Our indexes to the original array looks like this

(0, 0) (2, 1) (0, 2)
(1, 0) (1, 1) (1, 2)
(2, 0) (0, 1) (2, 2)

Well our j component is easy, it's just a simple arithmetic sequence where you add 1, i.e. 1, 2, 3, 4, 5...

for (int j = 0; j < 3; j++){
  ...
}

Now we need a sequence that follows the patten 0, 1, 2, 2, 1, 0, 0, 1, 2, ... repeating. Since we have repeating digits, I am thinking of clock arithmetic or modular arithmetic. Let's start with the sequence 0, 1, 2, 0, 1, 2 ... repeating. I.e the integers mod 3 (Z mod 3). For the first column we want the indicies straight up as they are (Z mod 3). Then for the reversed columns let's say we are given this sequence and we are iterating through it from 0 to 2. We can cleverly use modular arithmetic to get to our reversed sequence. For example if we had (2 mod 3), (4 mod 3), (6 mod 3), we would have 2, 1, 0. How do we get 0, 1, 2 to 2, 4, 6? Like this f(x) : (x + 1) * 2.

bool reversed = false;
for (int i = 0; i < 3; i++){
    int idx = i;
    if(reversed){
      int offset = (i + 1) * 2;
      idx = (offset) % 3;
    }
}
reversed = !reversed;

Now we just have to put it all together. This should be our new init grid as the print function is fine.

for (int j = 0; j < SIZE; j++){
  bool reversed = false;
  for (int i = 0; i < SIZE; i++){
    int idx = i;
    if(reversed){
      int offset = (i + 1) * (SIZE - 1);
      idx = (offset) % SIZE;
    }
    arr[idx][j] = inc;
    inc++;
  }
  reversed = !reversed;
}

That should do it. I got it to work in repl.it, hopefully this helps.


问:
XSLT iterate array and apply generic template to sub elements(Xml to Json)
I will be getting no. of xml and I have to convert them to appropriate json format using XSLT. I am able to convert everything except for array. I need to keep templates generic.

Here is gist sample example(XML, XSL and result) having scenario as - account having m departments having n employees.

XSL works fine for all scenarios including complex objects. But it doesn't apply ideal JSON formatting to an array. It appends object name as well to each individual element of the array. In actual I have very complex/nested xml, so I have to keep xslt as generic as possible.

If I add following two templates, it does not add a comma after leaf node.

```<code><xsl:template match="departments">
    <xsl:text>"departments": [{</xsl:text>
    <xsl:for-each select=".//department">
        <xsl:if test="position() > 1">
            <xsl:text>},{</xsl:text>
        </xsl:if>
        <xsl:apply-templates />
    </xsl:for-each>
    <xsl:text>}]</xsl:text>
</xsl:template>

<xsl:template match="employees">
    <xsl:text>"employees": [{</xsl:text>
    <xsl:for-each select=".//employee">
        <xsl:if test="position() > 1">
            <xsl:text>},{</xsl:text>
        </xsl:if>
        <xsl:apply-templates />
    </xsl:for-each>
    <xsl:text>}]</xsl:text>
</xsl:template>
</code>```

I have copied expected-result.json in gist as well. Is there any way to iterate subelement of an array and apply a template to the nested object or any other logic?

答:
Add new template array-obj and call it from template where field employees and departments are matched.

```<code><xsl:template name="array-obj">
    <xsl:text>{
</xsl:text>
    <xsl:for-each select="*">
        <xsl:if test="position() > 1">
            <xsl:text>,
</xsl:text>
        </xsl:if>
        <xsl:apply-templates select="."/>
    </xsl:for-each>
        <xsl:text>
</xsl:text>
    <xsl:text>}</xsl:text>
</xsl:template>
</code>```

employees and departments template needs to be modified as below. Remove curly brackets from the template.

```<code><xsl:template match="employees">
    <xsl:text>"employees": [</xsl:text>
    <xsl:for-each select=".//employee">
        <xsl:if test="position() > 1">
            <xsl:text>,</xsl:text>
        </xsl:if>
        <xsl:call-template name="array-obj"/>
    </xsl:for-each>
    <xsl:text>]</xsl:text>
</xsl:template>
</code>```

Body:
I will be getting no. of xml and I have to convert them to appropriate json format using XSLT. I am able to convert everything except for array. I need to keep templates generic.

Here is gist sample example(XML, XSL and result) having scenario as - account having m departments having n employees.

XSL works fine for all scenarios including complex objects. But it doesn't apply ideal JSON formatting to an array. It appends object name as well to each individual element of the array. In actual I have very complex/nested xml, so I have to keep xslt as generic as possible.

If I add following two templates, it does not add a comma after leaf node.

<xsl:template match="departments">
    <xsl:text>"departments": [{</xsl:text>
    <xsl:for-each select=".//department">
        <xsl:if test="position() > 1">
            <xsl:text>},{</xsl:text>
        </xsl:if>
        <xsl:apply-templates />
    </xsl:for-each>
    <xsl:text>}]</xsl:text>
</xsl:template>

<xsl:template match="employees">
    <xsl:text>"employees": [{</xsl:text>
    <xsl:for-each select=".//employee">
        <xsl:if test="position() > 1">
            <xsl:text>},{</xsl:text>
        </xsl:if>
        <xsl:apply-templates />
    </xsl:for-each>
    <xsl:text>}]</xsl:text>
</xsl:template>

I have copied expected-result.json in gist as well. Is there any way to iterate subelement of an array and apply a template to the nested object or any other logic?

Body:
Add new template array-obj and call it from template where field employees and departments are matched.

<xsl:template name="array-obj">
    <xsl:text>{
</xsl:text>
    <xsl:for-each select="*">
        <xsl:if test="position() > 1">
            <xsl:text>,
</xsl:text>
        </xsl:if>
        <xsl:apply-templates select="."/>
    </xsl:for-each>
        <xsl:text>
</xsl:text>
    <xsl:text>}</xsl:text>
</xsl:template>

employees and departments template needs to be modified as below. Remove curly brackets from the template.

<xsl:template match="employees">
    <xsl:text>"employees": [</xsl:text>
    <xsl:for-each select=".//employee">
        <xsl:if test="position() > 1">
            <xsl:text>,</xsl:text>
        </xsl:if>
        <xsl:call-template name="array-obj"/>
    </xsl:for-each>
    <xsl:text>]</xsl:text>
</xsl:template>


问:
QProcess passing arguments to a python Script
```<code>from PIL import Image
def porcentaje(path):

    im = Image.open(path, "r")
    im.show()
    width, height = im.size
    type = im.mode
    format = im.format
    pixels=im.getdata()
    n = len(pixels)
   im=im.load()
   nblack = 0
   noblack=0

   for pixel in pixels:
       if pixel < 50:
           nblack += 1
       else:
           noblack+=1

porcentajefinal=(nblack*100)/n
print(porcentajefinal)
return(porcentajefinal)

(porcentaje(path))
</code>```

mainwindow.cpp (QT Creator)

```<code>void MainWindow::on_pushButton_2_clicked()
{

    QString path = QFileDialog::getOpenFileName(this,
            tr("All Files (*)"));
     qDebug()<<path;

     QDir dir1("D:/QTCProjects/prueba");
     QFile file1("D:/QTCProjects/prueba/2_1.py");
     QString script1 = "D:/QTCProjects/prueba/2_1.py";
     QFile file2(script1);

     qDebug() << dir1.exists() << file1.exists() << file2.exists();
       //  these all result in true, true true
     QProcess *myProcess = new QProcess();
     myProcess->start("python.exe D:/QTCProjects/prueba/2_1.py" );
     myProcess->waitForFinished(-1);

      qDebug() << "myProcess:" << myProcess->readAll(); }
</code>```

This python requires a variable called path to run and i get this variable in qtcreator with Qstring path, how i can give python this variable with Qprocess.

答:
If you want to pass arguments to a script through the terminal, the following structure is used:

```<code>python.exe /path/of/your_script.py arg1 arg2 ... argn
</code>```

Then to obtain the parameter we must use sys.argv which is a list that stores the following:

```<code>['/path/of/your_script.py', 'arg1', 'arg2', ..., 'argn']
</code>```

So in your case you should get the parameter through sys.argv[1]:

2_1.py

```<code>from PIL import Image
import sys

def porcentaje(path):

    im = Image.open(path, "r")
    im.show()
    width, height = im.size
    type = im.mode
    format = im.format
    pixels=im.getdata()
    n = len(pixels)
    im=im.load()
    nblack = 0
    noblack=0
    for pixel in pixels:
        if pixel < 50:
            nblack += 1
        else:
            noblack+=1

    porcentajefinal=(nblack*100.0)/n
    print(porcentajefinal)
    return(porcentajefinal)

path = sys.argv[1]
porcentaje(path)
</code>```

On the side of Qt, python.exe is the main program, and the other parameters are the arguments, so your code must have the following structure:

```<code>void MainWindow::on_pushButton_2_clicked()
{
    QString path = QFileDialog::getOpenFileName(this, "All Files (*)");
    qDebug()<<path;
    if(!path.isEmpty()){
        QDir dir("D:/QTCProjects/prueba");
        QFileInfo info(dir, "2_1.py");
        qDebug() << dir.exists() << info.exists();
        QProcess process;
        process.start("python.exe", QStringList()<< info.absoluteFilePath() << path);
        process.waitForFinished(-1);
        qDebug() << "myProcess:" << process.readAll();
    }
}
</code>```

Body:
from PIL import Image
def porcentaje(path):

    im = Image.open(path, "r")
    im.show()
    width, height = im.size
    type = im.mode
    format = im.format
    pixels=im.getdata()
    n = len(pixels)
   im=im.load()
   nblack = 0
   noblack=0

   for pixel in pixels:
       if pixel < 50:
           nblack += 1
       else:
           noblack+=1

porcentajefinal=(nblack*100)/n
print(porcentajefinal)
return(porcentajefinal)

(porcentaje(path))

mainwindow.cpp (QT Creator)

void MainWindow::on_pushButton_2_clicked()
{

    QString path = QFileDialog::getOpenFileName(this,
            tr("All Files (*)"));
     qDebug()<<path;

     QDir dir1("D:/QTCProjects/prueba");
     QFile file1("D:/QTCProjects/prueba/2_1.py");
     QString script1 = "D:/QTCProjects/prueba/2_1.py";
     QFile file2(script1);

     qDebug() << dir1.exists() << file1.exists() << file2.exists();
       //  these all result in true, true true
     QProcess *myProcess = new QProcess();
     myProcess->start("python.exe D:/QTCProjects/prueba/2_1.py" );
     myProcess->waitForFinished(-1);

      qDebug() << "myProcess:" << myProcess->readAll(); }

This python requires a variable called path to run and i get this variable in qtcreator with Qstring path, how i can give python this variable with Qprocess.

Body:
If you want to pass arguments to a script through the terminal, the following structure is used:

python.exe /path/of/your_script.py arg1 arg2 ... argn

Then to obtain the parameter we must use sys.argv which is a list that stores the following:

['/path/of/your_script.py', 'arg1', 'arg2', ..., 'argn']

So in your case you should get the parameter through sys.argv[1]:

2_1.py

from PIL import Image
import sys

def porcentaje(path):

    im = Image.open(path, "r")
    im.show()
    width, height = im.size
    type = im.mode
    format = im.format
    pixels=im.getdata()
    n = len(pixels)
    im=im.load()
    nblack = 0
    noblack=0
    for pixel in pixels:
        if pixel < 50:
            nblack += 1
        else:
            noblack+=1

    porcentajefinal=(nblack*100.0)/n
    print(porcentajefinal)
    return(porcentajefinal)

path = sys.argv[1]
porcentaje(path)

On the side of Qt, python.exe is the main program, and the other parameters are the arguments, so your code must have the following structure:

void MainWindow::on_pushButton_2_clicked()
{
    QString path = QFileDialog::getOpenFileName(this, "All Files (*)");
    qDebug()<<path;
    if(!path.isEmpty()){
        QDir dir("D:/QTCProjects/prueba");
        QFileInfo info(dir, "2_1.py");
        qDebug() << dir.exists() << info.exists();
        QProcess process;
        process.start("python.exe", QStringList()<< info.absoluteFilePath() << path);
        process.waitForFinished(-1);
        qDebug() << "myProcess:" << process.readAll();
    }
}


问:
Cloud Foundry : Eureka Server as user provided service and add services
The cloud foundry in our organization does not have Spring Cloud services installed. I have created a Eureka Server and deployed it in the Cloud foundry and able to see the Eureka home page

I have created a user provide service and bound the application using the steps provided here (https://github.com/making/cf-eureka-server)!

I have given the following dependencies since there is no Spring CLoud

```<code><dependency>
        <groupId>io.pivotal.spring.cloud</groupId>
         <artifactId>spring-cloud-services-starter-service-registry</artifactId>
         <version>1.5.0.RELEASE</version>
    </dependency>
</code>```

and

```<code><dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
</code>```

However I get the following error in the CF logs

```<code>2017-11-13T14:39:05.238+05:30 [APP/PROC/WEB/0] [OUT] at com.sun.jersey.client.apache4.ApacheHttpClient4Handler.handle(ApacheHttpClient4Handler.java:173) ~[jersey-apache-client4-1.19.1.jar!/:1.19.1]
2017-11-13T14:39:05.238+05:30 [APP/PROC/WEB/0] [OUT] ... 30 common frames omitted
2017-11-13T14:39:05.238+05:30 [APP/PROC/WEB/0] [OUT] 2017-Nov-13 09:09:05.237 WARN [DiscoveryClient-HeartbeatExecutor-0] c.n.d.s.t.d.RetryableEurekaHttpClient - Request execution failed with message: java.net.ConnectException: Connection refused (Connection refused)
2017-11-13T14:39:05.238+05:30 [APP/PROC/WEB/0] [OUT] 2017-Nov-13 09:09:05.237 WARN [DiscoveryClient-CacheRefreshExecutor-0] c.n.d.s.t.d.RetryableEurekaHttpClient - Request execution failed with message: java.net.ConnectException: Connection refused (Connection refused)
2017-11-13T14:39:05.238+05:30 [APP/PROC/WEB/0] [OUT] 2017-Nov-13 09:09:05.237 ERROR [DiscoveryClient-HeartbeatExecutor-0] c.n.d.DiscoveryClient - DiscoveryClient_C2M-LAUNCH-SERVICE/app-launch-service.apps.np.sdppcf.com:d2c76a2f-f2c4-45f9-7e3b-f807 - was unable to send heartbeat!
2017-11-13T14:39:05.238+05:30 [APP/PROC/WEB/0] [OUT] com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
</code>```

The application is Spring boot application and I have enabled Discovery using @EnableDiscoveryClient. Due to this error I cannot see the services in Eureka.

Is it possible to create a Eureka service without Spring Cloud Services installed in Cloud foundry and use feign Clients etc ? Any direction would be helpful.

答:
The spring-cloud-services-starter-* client libraries were developed to match the way that Spring Cloud Services deploys and secures Spring Cloud applications like Eureka. These Spring Cloud Services libraries aren't likely to work with a Eureka service you write yourself unless you implement the same security and other configuration that SCS does.

Instead of using io.pivotal.spring.cloud:spring-cloud-services-starter-service-registry, you should use org.springframework.cloud:spring-cloud-starter-eureka and configure Eureka using properties in application.properties or application.yml. You can set the appropriate properties to values parsed from the user-provided service instance as shown in making's example from the Github repo:

eureka.client.service-url.defaultZone=${vcap.services.eureka-service.credentials.uri:http://localhost:8761}/eureka/

Body:
The cloud foundry in our organization does not have Spring Cloud services installed. I have created a Eureka Server and deployed it in the Cloud foundry and able to see the Eureka home page

I have created a user provide service and bound the application using the steps provided here (https://github.com/making/cf-eureka-server)!

I have given the following dependencies since there is no Spring CLoud

<dependency>
        <groupId>io.pivotal.spring.cloud</groupId>
         <artifactId>spring-cloud-services-starter-service-registry</artifactId>
         <version>1.5.0.RELEASE</version>
    </dependency>

and

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

However I get the following error in the CF logs

2017-11-13T14:39:05.238+05:30 [APP/PROC/WEB/0] [OUT] at com.sun.jersey.client.apache4.ApacheHttpClient4Handler.handle(ApacheHttpClient4Handler.java:173) ~[jersey-apache-client4-1.19.1.jar!/:1.19.1]
2017-11-13T14:39:05.238+05:30 [APP/PROC/WEB/0] [OUT] ... 30 common frames omitted
2017-11-13T14:39:05.238+05:30 [APP/PROC/WEB/0] [OUT] 2017-Nov-13 09:09:05.237 WARN [DiscoveryClient-HeartbeatExecutor-0] c.n.d.s.t.d.RetryableEurekaHttpClient - Request execution failed with message: java.net.ConnectException: Connection refused (Connection refused)
2017-11-13T14:39:05.238+05:30 [APP/PROC/WEB/0] [OUT] 2017-Nov-13 09:09:05.237 WARN [DiscoveryClient-CacheRefreshExecutor-0] c.n.d.s.t.d.RetryableEurekaHttpClient - Request execution failed with message: java.net.ConnectException: Connection refused (Connection refused)
2017-11-13T14:39:05.238+05:30 [APP/PROC/WEB/0] [OUT] 2017-Nov-13 09:09:05.237 ERROR [DiscoveryClient-HeartbeatExecutor-0] c.n.d.DiscoveryClient - DiscoveryClient_C2M-LAUNCH-SERVICE/app-launch-service.apps.np.sdppcf.com:d2c76a2f-f2c4-45f9-7e3b-f807 - was unable to send heartbeat!
2017-11-13T14:39:05.238+05:30 [APP/PROC/WEB/0] [OUT] com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server

The application is Spring boot application and I have enabled Discovery using @EnableDiscoveryClient. Due to this error I cannot see the services in Eureka.

Is it possible to create a Eureka service without Spring Cloud Services installed in Cloud foundry and use feign Clients etc ? Any direction would be helpful.