问:
Best practice on git push after rebasing locally
As we know, git denies git push origin BRANCH after BRANCH is rebased with master. If I am the only one who is working on BRANCH, I can use --force while pushing, or simply delete the remote BRANCH and psuh BRANCH again.

So, I know the solutions to the problem but what I don't know is if my solutions have downsides. What is the best practice used by developers?

Also what is the safe/best way to handle the issue if more than one people are working on BRANCH?

答:
Few points I can call from my experience:

You choose to do rebase only in feature branches and never in master/dev so less people have to deal with that.

Perhaps, drop a message in HipChat/Slack that rebase has happened.

Remind them git stash is available to protect their current work.

Your team members should use git pull --rebase in case change is easy to be perceived.

It is still a common practice to rebase for hotfixes on master/dev branches, that is also a good opportunity to let your team members get used to rebasing.


来源: stackexchange

问:
Pre fetching Images using Glide in android
I have an activity which will loads images one by one in same imageview using fadein fadeout animations. In order to provide a good user experience i want to pre fetch the images asynchronously and show them with a constant flow. I want to use glide for achieving the above said behaviour. But i am confused because there are two different approaches I found on internet to pre fetch (Cache) images. First is using Glide's .preload() method:

```<code>Glide.with(this)
.load(url)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.preload()
</code>```

Second is using Glide's .downloadOnly(int , int) method:

```<code>Glide.with(applicationContext)
.load(yourUrl)
.downloadOnly(500, 500);
</code>```

I have two questions:

What is difference between preload and downloadOnly and which one best suites my situation?

How to know that all of my images have been pre fetched and i can continue the process of showing images using one of the above (Best one) approaches?

答:
See the Glide Documentation here :

Glide Documentation

Search for class "DrawableTypeRequest" which has both these methods preload() and downloadOnly().

As the documentation says :

preload()

Preloads the resource into the cache using Target.SIZE_ORIGINAL as the > target width and height. Equivalent to calling preload(int, int) with > > Target.SIZE_ORIGINAL as the width and height.

downloadOnly(int width, int height)

Loads the original unmodified data into the cache and returns a Future > that can be used to retrieve the cache File containing the data.

I would suggest preload() would be fine for you.

ContentLicense: CC BY-SA 3.0

Body:
I have an activity which will loads images one by one in same imageview using fadein fadeout animations. In order to provide a good user experience i want to pre fetch the images asynchronously and show them with a constant flow. I want to use glide for achieving the above said behaviour. But i am confused because there are two different approaches I found on internet to pre fetch (Cache) images. First is using Glide's .preload() method:

Glide.with(this)
.load(url)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.preload()

Second is using Glide's .downloadOnly(int , int) method:

Glide.with(applicationContext)
.load(yourUrl)
.downloadOnly(500, 500);

I have two questions:

What is difference between preload and downloadOnly and which one best suites my situation?

How to know that all of my images have been pre fetched and i can continue the process of showing images using one of the above (Best one) approaches?


问:
How to make an asp dropdown list item unselectable
I have written following code to display drop down list :

```<code><asp:DropDownList AutoPostBack="True" ID="ddlCities" runat="server" class="form-control input-sm" placeholder="" TabIndex="5">
       <asp:ListItem>Select City</asp:ListItem>
       <asp:ListItem value="3">Ahmedabad (All) ---------------</asp:ListItem>
       <asp:ListItem value="3_3004">    Ahmedabad East</asp:ListItem>
       <asp:ListItem value="3_3005">    Ahmedabad West</asp:ListItem>
       <asp:ListItem value="3_3006">    Ahmedabad-Bopal and Surroundings</asp:ListItem>
       <asp:ListItem value="3_3007">    Ahmedabad-Gandhinagar</asp:ListItem>
       <asp:ListItem value="3_3008">    Ahmedabad-Sabarmati and Surroundings</asp:ListItem>
       <asp:ListItem value="3_3009">    Ahmedabad-SG Highway and Surroundings</asp:ListItem>
</asp:DropDownList>
</code>```

I want to make following item inside dropdown unselectable :

```<code><asp:ListItem value="3">Ahmedabad (All) ---------------</asp:ListItem>
</code>```

Note : I CAN'T USE OPTGROUP!!!!

and i don't want to hide it. it will be shown in dropdown, but user can't select this item.

I have tried adding 'disabled' attribute, but it hides that item.

i have also tried :

```<code>ddlCities.Items[1].Attributes.Add("Style", "cursor:not-allowed");
</code>```

It doesn't allow cursor, but still user can select this item, is there any other way to make this particular item unselectable??

答:
Even though you said that disabled attribute hides the element, you are wrong.
Disabled attribute is exactly what you should use for this:

```<code>    <asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem Value="1">First</asp:ListItem>
        <asp:ListItem Value="2" disabled="disabled">Second</asp:ListItem>
        <asp:ListItem Value="3">First</asp:ListItem>
    </asp:DropDownList>
</code>```

Result:

Body:
I have written following code to display drop down list :

<asp:DropDownList AutoPostBack="True" ID="ddlCities" runat="server" class="form-control input-sm" placeholder="" TabIndex="5">
       <asp:ListItem>Select City</asp:ListItem>
       <asp:ListItem value="3">Ahmedabad (All) ---------------</asp:ListItem>
       <asp:ListItem value="3_3004">    Ahmedabad East</asp:ListItem>
       <asp:ListItem value="3_3005">    Ahmedabad West</asp:ListItem>
       <asp:ListItem value="3_3006">    Ahmedabad-Bopal and Surroundings</asp:ListItem>
       <asp:ListItem value="3_3007">    Ahmedabad-Gandhinagar</asp:ListItem>
       <asp:ListItem value="3_3008">    Ahmedabad-Sabarmati and Surroundings</asp:ListItem>
       <asp:ListItem value="3_3009">    Ahmedabad-SG Highway and Surroundings</asp:ListItem>
</asp:DropDownList>

I want to make following item inside dropdown unselectable :

<asp:ListItem value="3">Ahmedabad (All) ---------------</asp:ListItem>

Note : I CAN'T USE OPTGROUP!!!!

and i don't want to hide it. it will be shown in dropdown, but user can't select this item.

I have tried adding 'disabled' attribute, but it hides that item.

i have also tried :

ddlCities.Items[1].Attributes.Add("Style", "cursor:not-allowed");

It doesn't allow cursor, but still user can select this item, is there any other way to make this particular item unselectable??

Body:
Even though you said that disabled attribute hides the element, you are wrong.
Disabled attribute is exactly what you should use for this:

    <asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem Value="1">First</asp:ListItem>
        <asp:ListItem Value="2" disabled="disabled">Second</asp:ListItem>
        <asp:ListItem Value="3">First</asp:ListItem>
    </asp:DropDownList>

Result:


问:
Insecure world writable dir /usr/local in PATH when trying to install Rails 3.0.3
I am trying to install rails 3.0.3 and i get the following error every time:

Insecure world writable dir /usr/local in PATH, mode 040777
```

<p>When I check to see if it installed I get this error:</p>

<pre class="lang-none prettyprint-override"><code>/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:827:in `report_activate_error': Could not find RubyGem rails (>= 0) (Gem::LoadError)
 from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:261:in `activate'
 from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:68:in `gem'
 from /usr/bin/rails:18
</code>```

Any idea what I am doing wrong? Sorry, I'm a newb!

答:
You need to secure that directory before the install. Use:

```<code>chmod o-w /usr/local
</code>```

to do this. If that doesn't work, the you probably need to be root (or otherwise suitably empowered) so you can try:

```<code>sudo chmod o-w /usr/local
</code>```

and enter your password.

I've seen this sort of thing before on some software which really wants things set up in a certain way to ensure that its assumptions are met. In any case, it's actually a bad idea to have world writable directories except when you know security on them is not a big deal.

/usr/local is important enough that you shouldn't allow anyone to write to it.

Body:
I am trying to install rails 3.0.3 and i get the following error every time:

Insecure world writable dir /usr/local in PATH, mode 040777

When I check to see if it installed I get this error:

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:827:in `report_activate_error': Could not find RubyGem rails (>= 0) (Gem::LoadError)
 from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:261:in `activate'
 from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/rubygems.rb:68:in `gem'
 from /usr/bin/rails:18

Any idea what I am doing wrong? Sorry, I'm a newb!

Body:
You need to secure that directory before the install. Use:

chmod o-w /usr/local

to do this. If that doesn't work, the you probably need to be root (or otherwise suitably empowered) so you can try:

sudo chmod o-w /usr/local

and enter your password.

I've seen this sort of thing before on some software which really wants things set up in a certain way to ensure that its assumptions are met. In any case, it's actually a bad idea to have world writable directories except when you know security on them is not a big deal.

/usr/local is important enough that you shouldn't allow anyone to write to it.


问:
How to Get time 2 Hours from current time in IONIC
I need to book a vehicle.So i get date.BUt i didnt got the time.Actually i want to book at least 2 hours after current time.also i need to get full time from next day onwards please help me.Iam doing in Ionic framework and AngularJS

Thanks in Advance

答:
```<code>this.myActualDate = new Date(new Date().getTime() + (3 * 24 * 60 * 60 * 1000)).toISOString().toString().substring(0, 10);

this.myMaxDate = new Date(new Date().getTime() + (368 * 24 * 60 * 60 * 1000)).toISOString();

 <ion-datetime displayFormat="YYYY/MM/DD" pickerFormat="YYYY MMMM DDDD" min={{myActualDate}} max={{myMaxDate}} [(ngModel)]="myActualDate"
          formControlName="booking_date" class="flex-date" required></ion-datetime>
</code>```

You can modify this code to perform yours.

If you want to extend three days in actual date then you can edit 365 digit into 368.
It will add three days in your date.

I think it will also work for time.
If you edit hours , minutes and seconds.

Body:
this.myActualDate = new Date(new Date().getTime() + (3 * 24 * 60 * 60 * 1000)).toISOString().toString().substring(0, 10);

this.myMaxDate = new Date(new Date().getTime() + (368 * 24 * 60 * 60 * 1000)).toISOString();

 <ion-datetime displayFormat="YYYY/MM/DD" pickerFormat="YYYY MMMM DDDD" min={{myActualDate}} max={{myMaxDate}} [(ngModel)]="myActualDate"
          formControlName="booking_date" class="flex-date" required></ion-datetime>

You can modify this code to perform yours.

If you want to extend three days in actual date then you can edit 365 digit into 368.
It will add three days in your date.

I think it will also work for time.
If you edit hours , minutes and seconds.


问:
Calling __host__ functions in PyCUDA
Is it possible to call __host__ functions in pyCUDA like you can __global__ functions? I noticed in the documentation that pycuda.driver.Function creates a handle to a __global__ function. __device__ functions can be called from a __global__ function, but __host__ code cannot. I'm aware that using a __host__ function pretty much defeats the purpose of pyCUDA, but there are some already made functions that I'd like to import and call as a proof of concept.

As a note, whenever I try to import the __host__ function, I get:

```<code>pycuda._driver.LogicError: cuModuleGetFunction failed: named symbol not found
</code>```

答:
No it is not possible.

This isn't a limitation of PyCUDA, per se, but of CUDA itself. The __host__ decorator just decays away to plain host code, and the CUDA APIs don't and cannot handle them in the same way that device code can be handled (note the the APIs also don't handle __device__ either, which is the true equivalent of __host__).

If you want to call/use __host__ functions from Python, you will need to use one of the standard C++/Python interoperability mechanisms, like ctypes or SWIG or boost python, etc.

EDIT:

Since this answer was written five years ago, CUDA has added the ability to run host functions in CUDA streams via cuLaunchHostFunc (driver API) or cudaLaunchHostFunc. Unfortunately, at the time of this edit (June 2022), PyCUDA doesn't expose this functionality, so it still isn't possible in PyCUDA and the core message of the original answer is unchanged.

ContentLicense: CC BY-SA 4.0

Title: Calling __host__ functions in PyCUDA

Body:
Is it possible to call __host__ functions in pyCUDA like you can __global__ functions? I noticed in the documentation that pycuda.driver.Function creates a handle to a __global__ function. __device__ functions can be called from a __global__ function, but __host__ code cannot. I'm aware that using a __host__ function pretty much defeats the purpose of pyCUDA, but there are some already made functions that I'd like to import and call as a proof of concept.

As a note, whenever I try to import the __host__ function, I get:

pycuda._driver.LogicError: cuModuleGetFunction failed: named symbol not found


问:
Find files in created between a date range
I use AIX via telnet here at work, and I'd like to know how to find files in a specific folder between a date range. For example: I want to find all files in folder X that were created between 01-Aug-13 and 31-Aug-13.

Observations:

The touch trick (where you create two empty files to use the -newer option) does not work for me, once the user roles that I have on the server does not allow me to create files.

I need to find between specific dates, not days (like: files that were created more than 30 days ago, etc...)

答:
Script oldfiles

I've tried to answer this question in a more complete way, and I ended up creating a complete script with options to help you understand the find command.

The script oldfiles is in this repository

To "create" a new find command you run it with the option -n (dry-run), and it will print to you the correct find command you need to use.

Of course, if you omit the -n it will just run, no need to retype the find command.

Usage:

```<code>oldfiles [-v...] ([-h|-V|-n] | {[(-a|-u) | (-m|-t) | -c] (-i | -d | -o| -y | -g) N (-\> | -\< | -\=) [-p "pat"]})
</code>```

Where the options are classified in the following groups:

Help & Info:

-h, --help     :  Show this help.

-V, --version  :  Show version.

-v, --verbose  :  Turn verbose mode on (cumulative).

-n, --dry-run  :  Do not run, just explain how to create a "find" command

Time type (access/use, modification time or changed status):

-a or -u       : access (use) time

-m or -t       : modification time (default)

-c             : inode status change

Time range (where N is a positive integer):

-i N           : minutes (default, with N equal 1 min)

-d N           : days

-o N           : months

-y N           : years

-g N           : N is a DATE (example: "2017-07-06 22:17:15")

Tests:

-p "pat"       : optional pattern to match (example: -p "*.c" to find c files) (default -p "*")

-\>            : file is newer than given range, ie, time modified after it.

-<            : file is older than given range, ie, time is from before it. (default)

-=            : file that is exactly N (min, day, month, year) old.

Example:

Find C source files newer than 10 minutes (access time) (with verbosity 3):

```<code>oldfiles -a -i 10 -p"*.c" -\> -nvvv
Starting oldfiles script, by beco, version 20170706.202054...
oldfiles -vvv -a -i 10 -p "*.c" -\> -n
Looking for "*.c" files with (a)ccess time newer than 10 minute(s)
find . -name "*.c" -type f -amin -10 -exec ls -ltu --time-style=long-iso {} +
Dry-run
</code>```

Find H header files older than a month (modification time) (verbosity 2):

```<code>oldfiles -m -o 1 -p"*.h" -\< -nvv
Starting oldfiles script, by beco, version 20170706.202054...
oldfiles -vv -m -o 1 -p "*.h" -\< -n
find . -name "*.h" -type f -mtime +30 -exec ls -lt --time-style=long-iso {} +
Dry-run
</code>```

Find all (*) files within a single day (Dec, 1, 2016; no verbosity, dry-run):

```<code>oldfiles -mng "2016-12-01" -\=
find . -name "*" -type f -newermt "2016-11-30 23:59:59" ! -newermt "2016-12-01 23:59:59" -exec ls -lt --time-style=long-iso {} +
</code>```

Of course, removing the -n the program will run the find command itself and save you the trouble.

I hope this helps everyone finally learn this {a,c,t}{time,min} options.

The LS output:

You will also notice that the ls option ls OPT changes to match the type of time you choose.

Link to clone/download of the oldfiles script:

https://github.com/drbeco/oldfiles

Body:
Script oldfiles

I've tried to answer this question in a more complete way, and I ended up creating a complete script with options to help you understand the find command.

The script oldfiles is in this repository

To "create" a new find command you run it with the option -n (dry-run), and it will print to you the correct find command you need to use.

Of course, if you omit the -n it will just run, no need to retype the find command.

Usage:

oldfiles [-v...] ([-h|-V|-n] | {[(-a|-u) | (-m|-t) | -c] (-i | -d | -o| -y | -g) N (-\> | -\< | -\=) [-p "pat"]})

Where the options are classified in the following groups:

Help & Info:

-h, --help     :  Show this help.

-V, --version  :  Show version.

-v, --verbose  :  Turn verbose mode on (cumulative).

-n, --dry-run  :  Do not run, just explain how to create a "find" command

Time type (access/use, modification time or changed status):

-a or -u       : access (use) time

-m or -t       : modification time (default)

-c             : inode status change

Time range (where N is a positive integer):

-i N           : minutes (default, with N equal 1 min)

-d N           : days

-o N           : months

-y N           : years

-g N           : N is a DATE (example: "2017-07-06 22:17:15")

Tests:

-p "pat"       : optional pattern to match (example: -p "*.c" to find c files) (default -p "*")

-\>            : file is newer than given range, ie, time modified after it.

-<            : file is older than given range, ie, time is from before it. (default)

-=            : file that is exactly N (min, day, month, year) old.

Example:

Find C source files newer than 10 minutes (access time) (with verbosity 3):

oldfiles -a -i 10 -p"*.c" -\> -nvvv
Starting oldfiles script, by beco, version 20170706.202054...
oldfiles -vvv -a -i 10 -p "*.c" -\> -n
Looking for "*.c" files with (a)ccess time newer than 10 minute(s)
find . -name "*.c" -type f -amin -10 -exec ls -ltu --time-style=long-iso {} +
Dry-run

Find H header files older than a month (modification time) (verbosity 2):

oldfiles -m -o 1 -p"*.h" -\< -nvv
Starting oldfiles script, by beco, version 20170706.202054...
oldfiles -vv -m -o 1 -p "*.h" -\< -n
find . -name "*.h" -type f -mtime +30 -exec ls -lt --time-style=long-iso {} +
Dry-run

Find all (*) files within a single day (Dec, 1, 2016; no verbosity, dry-run):

oldfiles -mng "2016-12-01" -\=
find . -name "*" -type f -newermt "2016-11-30 23:59:59" ! -newermt "2016-12-01 23:59:59" -exec ls -lt --time-style=long-iso {} +

Of course, removing the -n the program will run the find command itself and save you the trouble.

I hope this helps everyone finally learn this {a,c,t}{time,min} options.

The LS output:

You will also notice that the ls option ls OPT changes to match the type of time you choose.

Link to clone/download of the oldfiles script:

https://github.com/drbeco/oldfiles


问:
Recyclerview dataset update proper method
to update data of recyclerview i have tried three method

notifydatasetchanged()

swapadapter()

updating List<> and assigning same Adapter.

but when i update data in each method memory allocation (to app) keep increasing by range of(0.25 to 0.50)MB how to solve it?

My adapter

```<code>public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
public static int Sub;

public static class PersonViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    TextView personName;
    ImageView personPhoto;

    PersonViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);
        personName = (TextView)itemView.findViewById(R.id.person_name);
        personPhoto = (ImageView)itemView.findViewById(R.id.person_photo);
    }

    @Override
    public void onClick(View view) {
        Sub = getLayoutPosition();
        Toast.makeText(view.getContext(), "position = " + getLayoutPosition(), Toast.LENGTH_SHORT).show();

    }}

List<Person> persons;
RVAdapter(List<Person> persons){
    this.persons = persons;
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
}

@Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.raw, viewGroup, false);
    PersonViewHolder pvh = new PersonViewHolder(v);
    return pvh;
}

@Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
    personViewHolder.personName.setText(persons.get(i).name);
    personViewHolder.personPhoto.setImageResource(persons.get(i).photoId);
}

@Override
public int getItemCount() {
    return persons.size();
}
public void swap(List<Person>persons){
    persons.clear();
    persons.add(new Person("htfg", R.mipmap.ic_launcher));//0
    persons.add(new Person("fhe", R.mipmap.ic_launcher));//0
notifyDataSetChanged();
</code>```

}
}

答: Use adapter.notifyItemChanged (itemPosition) or any other .notifyItem...() native adapter methods.

Body:
to update data of recyclerview i have tried three method

notifydatasetchanged()

swapadapter()

updating List<> and assigning same Adapter.

but when i update data in each method memory allocation (to app) keep increasing by range of(0.25 to 0.50)MB how to solve it?

My adapter

public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
public static int Sub;

public static class PersonViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    TextView personName;
    ImageView personPhoto;

    PersonViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);
        personName = (TextView)itemView.findViewById(R.id.person_name);
        personPhoto = (ImageView)itemView.findViewById(R.id.person_photo);
    }

    @Override
    public void onClick(View view) {
        Sub = getLayoutPosition();
        Toast.makeText(view.getContext(), "position = " + getLayoutPosition(), Toast.LENGTH_SHORT).show();

    }}

List<Person> persons;
RVAdapter(List<Person> persons){
    this.persons = persons;
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
}

@Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.raw, viewGroup, false);
    PersonViewHolder pvh = new PersonViewHolder(v);
    return pvh;
}

@Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
    personViewHolder.personName.setText(persons.get(i).name);
    personViewHolder.personPhoto.setImageResource(persons.get(i).photoId);
}

@Override
public int getItemCount() {
    return persons.size();
}
public void swap(List<Person>persons){
    persons.clear();
    persons.add(new Person("htfg", R.mipmap.ic_launcher));//0
    persons.add(new Person("fhe", R.mipmap.ic_launcher));//0
notifyDataSetChanged();

}
}


问:
How to Align a div in Center When Contents added Dynamically
Please have a look at this Image.

Here I was use the Bootstrap for aligning the divs. And created only one div. The Contents are added in this div dynamically from the admin side. then it will loop the div. That's Working fine.

But here you can see only 6 Contents are available. So 2 Divs are aligned in the left. I need these div should align in the middle of the Page. If the Contents are 7 or 5 the Second row Contents should be in the Middle. How to align these Divs Middle. Please Help me to Solve this Problem.

Here Is My Code..

{{ service['name'] }}

{{ str_limit(service['description'], 100) }}

                Read More

Thank you in Advance.

答:
Add display: inline to child div and text-align: center to the parent div. Don't use col-md of bootstrap because it have float: left propertive

.parent {
  text-align: center;
}

.child {
  display: inline-block;
  width: 24%;
  border: solid 1px #123;
  height: 50px;
  margin: 0 auto !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent" id="parent">
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
</div></code>```

Body:
Add display: inline to child div and text-align: center to the parent div. Don't use col-md of bootstrap because it have float: left propertive

.parent {
  text-align: center;
}

.child {
  display: inline-block;
  width: 24%;
  border: solid 1px #123;
  height: 50px;
  margin: 0 auto !important;
}

<div class="parent" id="parent">
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
  <div class='child'></div>
</div>


问:
Play video from local file using Adobe AIR
I'd like to play videos, as well as display images and possibly other flash content using adobe air, and reading from the local file system. I've been searching APIs and I have not yet been able to connect the dots.

I know of flash.filesystem.File and flash.filesystem.FileStream and have experimented with loading and reading files. I believe I can load images this way but haven't tried.

As for video:

mx.controls.VideoDisplay
- seems to accept a file:// URI for source, but I can't get it to work.

flash.media.Video
- accepts a NetStream or can load video directly from a video input, can't seem to find a way to reference a local file

Can anyone help me out here? I specifically want to load and play video directly off the local disk, not from a web server or a streaming file server... assume no network connectivity.

Slightly related question: Loading a video from the local file system… (but my question does not involve a web browser)

答:
The use I have in mind is required to be programmatic in usage. I was looking for a way to do this directly with ActionScript.

I finally stumbled onto the solution I was hoping for... using a NetStream object, but (non-intuitively) you can use this to access local files as well:

```<code>private function playVideo():void {
  var nc:NetConnection = new NetConnection();
  nc.connect(null);

  var ns:NetStream = new NetStream(nc);

  # onMetaData listener is required otherwise you get a ReferenceError
  var client:Object = new Object();
  client.onMetaData = function(metadata:Object):void {
    trace(metadata.duration);
  }
  ns.client = client;

  var v:Video = new Video();
  v.attachNetStream(ns);
  stage.addChild(v);

  var f:File = new File("/tmp/test.flv");
  ns.play(f.url);
}
</code>```

OwnerDisplayName: tweakt

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: tweakt

Body:
The use I have in mind is required to be programmatic in usage. I was looking for a way to do this directly with ActionScript.

I finally stumbled onto the solution I was hoping for... using a NetStream object, but (non-intuitively) you can use this to access local files as well:

private function playVideo():void {
  var nc:NetConnection = new NetConnection();
  nc.connect(null);

  var ns:NetStream = new NetStream(nc);

  # onMetaData listener is required otherwise you get a ReferenceError
  var client:Object = new Object();
  client.onMetaData = function(metadata:Object):void {
    trace(metadata.duration);
  }
  ns.client = client;

  var v:Video = new Video();
  v.attachNetStream(ns);
  stage.addChild(v);

  var f:File = new File("/tmp/test.flv");
  ns.play(f.url);
}


问:
How to import the type-definition in typescript?
I tried use the type-definition for hammerjs. As:

```<code>import Hammer from 'hammerjs';
</code>```

But i get this error:

Error TS2307: Cannot find module 'hammerjs'

I have two question. First, is necessary get all files of tile definition in github, our i can get the simples definition for hammerjs?

My package.json contains:

```<code>"dependencies": {
   "git+https://git@github.com/DefinitelyTyped/DefinitelyTyped.git"
}
</code>```

The second question, whats my error about import module?

答:
Hammerjs may not be the same as chrome extention typings I was dealing with but issue sounds very much like what I was experiencing when you are missing an import or export in the module file you will need to give a reference:

Step 1: npm install --save @types/chrome

Step 2: Add ///  to code needing to use modules

Step 3: that file can access all the declared modules.[do not import chrome or '@types/chrome']
https://typescript.codeplex.com/wikipage?title=Modules%20in%20TypeScript

Body:
I tried use the type-definition for hammerjs. As:

import Hammer from 'hammerjs';

But i get this error:

Error TS2307: Cannot find module 'hammerjs'

I have two question. First, is necessary get all files of tile definition in github, our i can get the simples definition for hammerjs?

My package.json contains:

"dependencies": {
   "git+https://git@github.com/DefinitelyTyped/DefinitelyTyped.git"
}

The second question, whats my error about import module?


问:
Gstreamer streaming multiple cameras over RTP while saving each stream
I am currently working on a project that utilizes a Nvidia Jetson. We need to stream 3 cameras over UDP RTP to a single source (unicast), while saving the contents of all three cameras.

I am having issues with my pipeline, It is probably a simple mistake somewhere that I simply am not seeing.

```<code>gst-launch-1.0 -e v4l2src device=/dev/video0 ! 'video/x-raw, width=(int)640, height=(int)480' ! tee name=c c. ! queue ! omxvp8enc bitrate=1500000 ! rtpvp8pay ! udpsink bind-port=8574 host=129.21.57.204 port=8574 loop=false c. ! queue ! omxh264enc bitrate=1500000 ! mp4mux ! queue ! filesink location=test-RightFacingCamera.mp4 v4l2src device=/dev/video1 ! 'video/x-raw, width=(int)640, height=(int)480' ! tee name=b b. ! queue ! omxvp8enc bitrate=1500000 ! rtpvp8pay ! udpsink bind-port=8564 host=129.21.57.204 port=8564 loop=false b. ! queue ! omxh264enc bitrate=1500000 ! mp4mux ! queue ! filesink location=test-LeftFacingCamera.mp4 v4l2src device=/dev/video2 ! 'video/x-raw, width=(int)640, height=(int)480' ! tee name=a a. ! queue ! omxvp8enc bitrate=1500000 ! rtpvp8pay ! udpsink bind-port=8554 host=129.21.57.204 port=8554 loop=false a. ! queue ! omxh264enc bitrate=1500000 ! mp4mux ! queue ! filesink location=test-FrontFacingCamera.mp4
</code>```

Now the issue here is that 2 of the 3 streams will simply stop without cause, there is no debug information at all, they will simply cease to stream and write to the file after about 2 minutes of up time.

Additionally, I have considered converting this into C/C++ w/Gstreamer, I would not know where to begin if someone would like to point me in a direction. Currently I have a javascript code written up that detects each camera by serial number and assigns a port to the given camera. Then runs this command.

Thanks for any help.

答: This is usb bandwidth limitation of Jetson. We can support 3 camera at a time with compromising the frame-rate. The Logitech camera is compared and that camera is H.264 camera (It gives compressed frames) so it afford to give 60fps bandwidth.

Body:
I am currently working on a project that utilizes a Nvidia Jetson. We need to stream 3 cameras over UDP RTP to a single source (unicast), while saving the contents of all three cameras.

I am having issues with my pipeline, It is probably a simple mistake somewhere that I simply am not seeing.

gst-launch-1.0 -e v4l2src device=/dev/video0 ! 'video/x-raw, width=(int)640, height=(int)480' ! tee name=c c. ! queue ! omxvp8enc bitrate=1500000 ! rtpvp8pay ! udpsink bind-port=8574 host=129.21.57.204 port=8574 loop=false c. ! queue ! omxh264enc bitrate=1500000 ! mp4mux ! queue ! filesink location=test-RightFacingCamera.mp4 v4l2src device=/dev/video1 ! 'video/x-raw, width=(int)640, height=(int)480' ! tee name=b b. ! queue ! omxvp8enc bitrate=1500000 ! rtpvp8pay ! udpsink bind-port=8564 host=129.21.57.204 port=8564 loop=false b. ! queue ! omxh264enc bitrate=1500000 ! mp4mux ! queue ! filesink location=test-LeftFacingCamera.mp4 v4l2src device=/dev/video2 ! 'video/x-raw, width=(int)640, height=(int)480' ! tee name=a a. ! queue ! omxvp8enc bitrate=1500000 ! rtpvp8pay ! udpsink bind-port=8554 host=129.21.57.204 port=8554 loop=false a. ! queue ! omxh264enc bitrate=1500000 ! mp4mux ! queue ! filesink location=test-FrontFacingCamera.mp4

Now the issue here is that 2 of the 3 streams will simply stop without cause, there is no debug information at all, they will simply cease to stream and write to the file after about 2 minutes of up time.

Additionally, I have considered converting this into C/C++ w/Gstreamer, I would not know where to begin if someone would like to point me in a direction. Currently I have a javascript code written up that detects each camera by serial number and assigns a port to the given camera. Then runs this command.

Thanks for any help.


问:
Spark Streaming - StreamingContext sc not defined error

I am getting above error when trying to run Spark-Streaming from Jupyter. Does anyone know how to solve it?

答:
If not, you need to initialize SparkContext before using it

```<code>from pyspark import SparkContext
sc = SparkContext("local", "App Name")
</code>```

Hope this helps!

Body:
If not, you need to initialize SparkContext before using it

from pyspark import SparkContext
sc = SparkContext("local", "App Name")

Hope this helps!


问:
How make validation of Date with datetime work with jquery(date picker) for php?
Script(jquery) use to make input[date] accessible to multiple browser(datepicker)

```<code><script>
   $(function(){
      if (!Modernizr.inputtypes.date) { //if browser doesn't support input type="date", initialize date picker widget:
    // If not native HTML5 support, fallback to jQuery datePicker <script src="js/realtime_validityScript.js">
           $('input[type=date]').datepicker({
            // Consistent format with the HTML5 picker
                **dateFormat: 'dd-mm-yy',**
                maxDate: 0

            },
            // Localization
            $.datepicker.regional['it']
        );
    }
});
</script>
</code>```

2- PHP code for validating date format by user in case jquery is disabled (not working) - also not sure how to use DateTime::getLastErrors()

```<code>// specify your date's original format, in this example d/m/Y (e.g. 25/07/2014)

 **$format = "d-m-Y";**
 $date = DateTime::createFromFormat($format, $_POST['DateField']);
 $date_errors = DateTime::getLastErrors();
  if(? $date_errors[also dunno what to put here?] ) {

   // createFromFormat returns false if the format is invalid;

   echo 'Your date format is incorrect';
 } else {
   //change it to any format you want with format() (e.g. 2013-08-31)

    $date->format('Y-m-d');
 }
</code>```

Original PHP code for getting my date: (my db access currently this format "Y-m-d")

```<code>if (empty($_POST["DateField"]) ) {

   $errors['DateField'] = "Age is required";

} else {
    $date = date("Y-m-d", strtotime( $_POST['DateField']));

}
</code>```

I also want the input date to be able to convert formats like those ('d-m-Y', 'Y/m/d', 'Y.m.d', 'd.m-Y', 'd/m/Y') to 'Y-m-d' maybe with an array of some sort?

Note: if i remove the 2- part my code work fine

Thanks you for your support...still new to PHP would really help if someone could expl to me what wrong and what the correct code

答:
Date type will not allow your required formats. so instead of using type="date" use type="text" and add a class date to the input field to initialise datepicker like,

```<code>....
$('input.date').datepicker({
   // Consistent format with the HTML5 picker
   dateFormat: 'dd-mm-yy',
   maxDate: 0
},
....
</code>```

And change HTML like,

```<code><input type="text" class="date" ..../>
</code>```

Body:
Script(jquery) use to make input[date] accessible to multiple browser(datepicker)

2- PHP code for validating date format by user in case jquery is disabled (not working) - also not sure how to use DateTime::getLastErrors()

// specify your date's original format, in this example d/m/Y (e.g. 25/07/2014)

 **$format = "d-m-Y";**
 $date = DateTime::createFromFormat($format, $_POST['DateField']);
 $date_errors = DateTime::getLastErrors();
  if(? $date_errors[also dunno what to put here?] ) {

   // createFromFormat returns false if the format is invalid;

   echo 'Your date format is incorrect';
 } else {
   //change it to any format you want with format() (e.g. 2013-08-31)

    $date->format('Y-m-d');
 }

Original PHP code for getting my date: (my db access currently this format "Y-m-d")

if (empty($_POST["DateField"]) ) {

   $errors['DateField'] = "Age is required";

} else {
    $date = date("Y-m-d", strtotime( $_POST['DateField']));

}

I also want the input date to be able to convert formats like those ('d-m-Y', 'Y/m/d', 'Y.m.d', 'd.m-Y', 'd/m/Y') to 'Y-m-d' maybe with an array of some sort?

Note: if i remove the 2- part my code work fine

Thanks you for your support...still new to PHP would really help if someone could expl to me what wrong and what the correct code

Body:
Date type will not allow your required formats. so instead of using type="date" use type="text" and add a class date to the input field to initialise datepicker like,

....
$('input.date').datepicker({
   // Consistent format with the HTML5 picker
   dateFormat: 'dd-mm-yy',
   maxDate: 0
},
....

And change HTML like,

<input type="text" class="date" ..../>


问:
How do I order subgraph clusters when using dot?
I have a dot file in which I create subgraph clusters which I want to appear in a specific order, let's say I have this:

```<code>digraph G {
    splines=true;
    sep="+25,25";
    overlap=scalexy;
    nodesep=0.6;
    subgraph cluster_2 {
        label="ADD_MORE_PROBLEMS";
        subgraph cluster_3 {
            label="pattern";
            N1 [label="problem"];
        }
        subgraph cluster_4 {
            label="replacement";
            N2 [label="problem"];
            N3 [label="problem"];
        }
    }
}
</code>```

Which creates:

How do I ensure that "pattern" appears to the left of "replacement" (I may have an arbitrary number of subgraphs).

答:
I can't give and answer, but can provide some clarification. The usual approach to force layout is to introduce hidden edges. In this case, it does not work.

Without the nested clusters, you can use rank=same to force connected edges onto the same level. Then, an invisible edge N1 -> N2 [style = invis] would force the nodes into the correct ordering.

However, constraining nodes with rank breaks the cluster membership and prevents the scheme from working.

The modified graph shows the result. There may not be a general solution.

```<code>digraph G {
    splines=true;
    sep="+25,25";
    overlap=scalexy;
    nodesep=0.6;
    subgraph cluster_2 {
        label="ADD_MORE_PROBLEMS";
        subgraph cluster_3 {
            label="pattern";
            N1 [label="problem 1"];
        }
        subgraph cluster_4 {
            label="replacement";
            N2 [label="problem 2"];
            N3 [label="problem 3"];
        }
        // Introduce hidden edge (shown dashed)
        N1 -> N2 [style = dashed];
        // Force nodes to remain at same rank
        { rank = same; N1; N2; }
    }
}
</code>```

Body:
I have a dot file in which I create subgraph clusters which I want to appear in a specific order, let's say I have this:

digraph G {
    splines=true;
    sep="+25,25";
    overlap=scalexy;
    nodesep=0.6;
    subgraph cluster_2 {
        label="ADD_MORE_PROBLEMS";
        subgraph cluster_3 {
            label="pattern";
            N1 [label="problem"];
        }
        subgraph cluster_4 {
            label="replacement";
            N2 [label="problem"];
            N3 [label="problem"];
        }
    }
}

Which creates:

How do I ensure that "pattern" appears to the left of "replacement" (I may have an arbitrary number of subgraphs).

Body:
I can't give and answer, but can provide some clarification. The usual approach to force layout is to introduce hidden edges. In this case, it does not work.

Without the nested clusters, you can use rank=same to force connected edges onto the same level. Then, an invisible edge N1 -> N2 [style = invis] would force the nodes into the correct ordering.

However, constraining nodes with rank breaks the cluster membership and prevents the scheme from working.

The modified graph shows the result. There may not be a general solution.

digraph G {
    splines=true;
    sep="+25,25";
    overlap=scalexy;
    nodesep=0.6;
    subgraph cluster_2 {
        label="ADD_MORE_PROBLEMS";
        subgraph cluster_3 {
            label="pattern";
            N1 [label="problem 1"];
        }
        subgraph cluster_4 {
            label="replacement";
            N2 [label="problem 2"];
            N3 [label="problem 3"];
        }
        // Introduce hidden edge (shown dashed)
        N1 -> N2 [style = dashed];
        // Force nodes to remain at same rank
        { rank = same; N1; N2; }
    }
}


问:
Settimeout not returning instantly
I was practicing with callback functions and this question is one I can't seem to figure out.

```<code>function foo () {
  var data = 10;
  bar(function (players) {
    data = players;
  });
  return data;
}

function bar (callback) {
  setTimeout(callback, 0);
}

var result = foo();
</code>```

I expected result to be undefined since data = players and there is nothing passed in as players. Since the setTimeout function uses 0 as the delay, shouldn't it run first, and then return data? I looked at the MDN page and there seems to be information on throttling for nested timeouts to >=4ms. Does this also apply in this case?

答:
Since the setTimeout function uses 0 as the delay, shouldn't it run first, and then return data?

No, even with a delay of 0, the callback passed to setTimeout is scheduled to run in the next tick of the event loop.

In other words, the callback is guaranteed to be executed after the current execution ran to completion.

Title: Settimeout not returning instantly

Body:
I was practicing with callback functions and this question is one I can't seem to figure out.

function foo () {
  var data = 10;
  bar(function (players) {
    data = players;
  });
  return data;
}

function bar (callback) {
  setTimeout(callback, 0);
}

var result = foo();

I expected result to be undefined since data = players and there is nothing passed in as players. Since the setTimeout function uses 0 as the delay, shouldn't it run first, and then return data? I looked at the MDN page and there seems to be information on throttling for nested timeouts to >=4ms. Does this also apply in this case?


问:
UIBlurEffect on StatusBar only (not on UINavigationBar)
Similar to this:
How to make a Navigation Bar and Status Bar blurred (UIBlurEffect)? iOS, Swift 3

but we'd like to apply the UIBlurEffect on the StatusBar only, not the navigationbar. Is this possible?

答:
```<code>let statWindow = UIApplication.shared.value(forKey:"statusBarWindow") as! UIView
    let statusBar = statWindow.subviews[0] as UIView
    statusBar.backgroundColor = UIColor.clear
    let blur = UIBlurEffect(style:.dark)
    let visualeffect = UIVisualEffectView(effect: blur)
    visualeffect.frame = statusBar.frame
    //statusBar.addSubview(visualeffect)
    visualeffect.alpha = 0.5
    self.view.addSubview(visualeffect)
</code>```

<p>try this </p>

Body:
let statWindow = UIApplication.shared.value(forKey:"statusBarWindow") as! UIView
    let statusBar = statWindow.subviews[0] as UIView
    statusBar.backgroundColor = UIColor.clear
    let blur = UIBlurEffect(style:.dark)
    let visualeffect = UIVisualEffectView(effect: blur)
    visualeffect.frame = statusBar.frame
    //statusBar.addSubview(visualeffect)
    visualeffect.alpha = 0.5
    self.view.addSubview(visualeffect)

try this


问:
Python Pandas rolling window apply multiple lambda functions
Is it possible to apply more than one function to a pandas rolling window in a tuple like fashion?

I'm currently creating returning the count, lower bound and upper bound of the largest bin by count of a price series over a rolling window.

```<code>def qcut_data(x):
    data_out = pd.qcut(x, q = 10, duplicates = 'drop').value_counts().nlargest(1)
    return data_out

df_m['hist_count'] = df_m['mid'].rolling(window = rolling_window).apply(lambda x: qcut_data(x).item())
df_m['hist_bottom'] = df_m['mid'].rolling(window = rolling_window).apply(lambda x: qcut_data(x).index[0].left)
df_m['hist_top'] = df_m['mid'].rolling(window = rolling_window).apply(lambda x: qcut_data(x).index[0].right)
</code>```

This strikes me as horribly inefficient as i'm just returning different values (item and index) of the same function (qcut_data), over the same rolling window of the same Series (df_m['mid']).

Is there a way to combine these so all three values can be returned?

I can't call a list, tuple or set in the .apply() method, is there another way?

答:
You can probably do what you want with aggregate which is more flexible...

```<code>df_m['mid'].rolling(window=rolling_window).agg([lambda x: qcut_data(x).item(),
                                                lambda x: qcut_data(x).index[0].left,
                                                lambda x: qcut_data(x).index[0].right])
</code>```

But you need to massage the resulting frame to join it. You could also name the lambdas or make them proper funcs.

Body:
Is it possible to apply more than one function to a pandas rolling window in a tuple like fashion?

I'm currently creating returning the count, lower bound and upper bound of the largest bin by count of a price series over a rolling window.

def qcut_data(x):
    data_out = pd.qcut(x, q = 10, duplicates = 'drop').value_counts().nlargest(1)
    return data_out

df_m['hist_count'] = df_m['mid'].rolling(window = rolling_window).apply(lambda x: qcut_data(x).item())
df_m['hist_bottom'] = df_m['mid'].rolling(window = rolling_window).apply(lambda x: qcut_data(x).index[0].left)
df_m['hist_top'] = df_m['mid'].rolling(window = rolling_window).apply(lambda x: qcut_data(x).index[0].right)

This strikes me as horribly inefficient as i'm just returning different values (item and index) of the same function (qcut_data), over the same rolling window of the same Series (df_m['mid']).

Is there a way to combine these so all three values can be returned?

I can't call a list, tuple or set in the .apply() method, is there another way?

Body:
You can probably do what you want with aggregate which is more flexible...

df_m['mid'].rolling(window=rolling_window).agg([lambda x: qcut_data(x).item(),
                                                lambda x: qcut_data(x).index[0].left,
                                                lambda x: qcut_data(x).index[0].right])

But you need to massage the resulting frame to join it. You could also name the lambdas or make them proper funcs.


问:
TFS get build agent working folder programmatically
Is there any way to programmatically retrieve the working folder of a build agent (through TFS REST API)?

I'd like to clean this folder during the reboot of the build agent.

答:
There isn't the REST API to retrieve the working folder of a build agent.

The working folder is defined when your deploy the build agent. Commonly it should be like this D:\VSOAgent_work (the location which you deployed the agent to).

To clean the folder during the reboot of the build agent, you just need to create a .cmd/.bat file to delete the _work directory, and copy it into the start up folder in Windows Explorer.

Please note that you need to run the cmd/bat with administrator.

Delete command sample:  (Just change the dir accordingly, the command will delete all the files and sub-folders, but not delete the directory _work)

```<code>@ECHO OFF

Set dir=D:\VSOAgent\_work\

Echo Deleting all files from %dir%
del %dir%\* /F /Q

Echo Deleting all folders from %dir%
for /d %%p in (%dir%\*) Do rd /Q /S "%%p"
@echo Folder deleted.

exit
</code>```

To find the Startup folder:

For your user account : Win + R run shell:startup

For all users Win + R run  shell:common startup

For how to auto start Programs as Administrator, you can reference this article:
http://www.thewindowsclub.com/autostart-programs-windows-10-make

Body:
There isn't the REST API to retrieve the working folder of a build agent.

The working folder is defined when your deploy the build agent. Commonly it should be like this D:\VSOAgent_work (the location which you deployed the agent to).

To clean the folder during the reboot of the build agent, you just need to create a .cmd/.bat file to delete the _work directory, and copy it into the start up folder in Windows Explorer.

Please note that you need to run the cmd/bat with administrator.

Delete command sample:  (Just change the dir accordingly, the command will delete all the files and sub-folders, but not delete the directory _work)

@ECHO OFF

Set dir=D:\VSOAgent\_work\

Echo Deleting all files from %dir%
del %dir%\* /F /Q

Echo Deleting all folders from %dir%
for /d %%p in (%dir%\*) Do rd /Q /S "%%p"
@echo Folder deleted.

exit

To find the Startup folder:

For your user account : Win + R run shell:startup

For all users Win + R run  shell:common startup

For how to auto start Programs as Administrator, you can reference this article:
http://www.thewindowsclub.com/autostart-programs-windows-10-make


问:
OnclickListener on RecylerView and getting the Id of clicked Item
I need to set onClickListener on RecyclerView which gets the Json Id of an Item Clicked and redirects to the fragment which displays the details of the product based on that Json ID.  How Can I implement this in adapter? I am stuck here. I was able to set onClickListener but I couldn't get the Json ID.

This is my Adapter.

```<code>import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.dell.retroexample.MainActivity;
import com.example.dell.retroexample.R;
import com.example.dell.retroexample.apiHandlers.model.Ad;

import java.util.List;

/**
 * Created by dell on 7/3/2017.
 */

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{

    private List<Ad> ads;
    private Context context;

    public RecyclerAdapter(List<Ad> ads, Context context){
        this.ads=ads;
        this.context=context;

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_ads, parent,false);
        return  new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.name.setText(ads.get(position).getTitle());
        holder.details.setText("Rs. " +ads.get(position).getPrice().toString()+ "/-");
//        Glide.with(context).load(ads.get(position).getPhoto1()).into(holder.thumbnail);

    }

    @Override
    public int getItemCount() {
        return ads.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        ImageView thumbnail;
        TextView name, details;
        public MyViewHolder(View itemView) {
            super(itemView);
//            thumbnail=(ImageView)itemView.findViewById(R.id.thumbnail);
            name=(TextView)itemView.findViewById(R.id.title);
            details=(TextView)itemView.findViewById(R.id.price);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            Toast.makeText(view.getContext(), "Clicked on Recycler View" , Toast.LENGTH_SHORT).show();
        }

    }
}
</code>```

This is my MainActivity

```<code>package com.example.dell.retroexample;

import android.content.res.Resources;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;

import com.example.dell.retroexample.apiHandlers.adapter.RecyclerAdapter;
import com.example.dell.retroexample.apiHandlers.model.Ad;
import com.example.dell.retroexample.apiHandlers.rest.ApiInterface;
import com.example.dell.retroexample.apiHandlers.rest.ApiClient;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerAdapter adapter=null;
    private List<Ad> ads;
    private ApiInterface apiInterface;

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

        recyclerView=(RecyclerView)findViewById(R.id.ads_recycler_view);
                // calculating the number of columns
        int columns=2;
        DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
        double widthPixels = lDisplayMetrics.widthPixels;
        Log.e("Width", String.valueOf(widthPixels));
        columns=(int)widthPixels/dpToPx(170);

        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this,  columns);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        apiInterface=ApiClient.getClient().create(ApiInterface.class);

        Call <List<Ad>> call=apiInterface.getads();

        call.enqueue(new Callback<List<Ad>>() {
            @Override
            public void onResponse(Call<List<Ad>> call, Response<List<Ad>> response) {
                ads=response.body();
                adapter=new RecyclerAdapter(ads, MainActivity.this);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onFailure(Call<List<Ad>> call, Throwable t) {

                Log.e(TAG, t.toString());
            }
        });

    }

    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }

}
</code>```

答:
```<code>@Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.name.setText(ads.get(position).getTitle());
        holder.details.setText("Rs. " +ads.get(position).getPrice().toString()+ "/-");        Glide.with(context).load(ads.get(position).getPhoto1()).into(holder.thumbnail);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String id=ads.get(position).getId();
                //You can call detail fragment here
            }
        });
    }
</code>```

Note: Remove onclick listener from ViewHolder

Body:
I need to set onClickListener on RecyclerView which gets the Json Id of an Item Clicked and redirects to the fragment which displays the details of the product based on that Json ID.  How Can I implement this in adapter? I am stuck here. I was able to set onClickListener but I couldn't get the Json ID.

This is my Adapter.

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.dell.retroexample.MainActivity;
import com.example.dell.retroexample.R;
import com.example.dell.retroexample.apiHandlers.model.Ad;

import java.util.List;

/**
 * Created by dell on 7/3/2017.
 */

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{

    private List<Ad> ads;
    private Context context;

    public RecyclerAdapter(List<Ad> ads, Context context){
        this.ads=ads;
        this.context=context;

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_ads, parent,false);
        return  new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.name.setText(ads.get(position).getTitle());
        holder.details.setText("Rs. " +ads.get(position).getPrice().toString()+ "/-");
//        Glide.with(context).load(ads.get(position).getPhoto1()).into(holder.thumbnail);

    }

    @Override
    public int getItemCount() {
        return ads.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        ImageView thumbnail;
        TextView name, details;
        public MyViewHolder(View itemView) {
            super(itemView);
//            thumbnail=(ImageView)itemView.findViewById(R.id.thumbnail);
            name=(TextView)itemView.findViewById(R.id.title);
            details=(TextView)itemView.findViewById(R.id.price);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            Toast.makeText(view.getContext(), "Clicked on Recycler View" , Toast.LENGTH_SHORT).show();
        }

    }
}

This is my MainActivity

package com.example.dell.retroexample;

import android.content.res.Resources;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;

import com.example.dell.retroexample.apiHandlers.adapter.RecyclerAdapter;
import com.example.dell.retroexample.apiHandlers.model.Ad;
import com.example.dell.retroexample.apiHandlers.rest.ApiInterface;
import com.example.dell.retroexample.apiHandlers.rest.ApiClient;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerAdapter adapter=null;
    private List<Ad> ads;
    private ApiInterface apiInterface;

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

        recyclerView=(RecyclerView)findViewById(R.id.ads_recycler_view);
                // calculating the number of columns
        int columns=2;
        DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
        double widthPixels = lDisplayMetrics.widthPixels;
        Log.e("Width", String.valueOf(widthPixels));
        columns=(int)widthPixels/dpToPx(170);

        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this,  columns);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        apiInterface=ApiClient.getClient().create(ApiInterface.class);

        Call <List<Ad>> call=apiInterface.getads();

        call.enqueue(new Callback<List<Ad>>() {
            @Override
            public void onResponse(Call<List<Ad>> call, Response<List<Ad>> response) {
                ads=response.body();
                adapter=new RecyclerAdapter(ads, MainActivity.this);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onFailure(Call<List<Ad>> call, Throwable t) {

                Log.e(TAG, t.toString());
            }
        });

    }

    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }

}

Body:
@Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.name.setText(ads.get(position).getTitle());
        holder.details.setText("Rs. " +ads.get(position).getPrice().toString()+ "/-");        Glide.with(context).load(ads.get(position).getPhoto1()).into(holder.thumbnail);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String id=ads.get(position).getId();
                //You can call detail fragment here
            }
        });
    }

Note: Remove onclick listener from ViewHolder


问:
How to insert arrays into a main array in PHP to make it 2d array?
I have these 3 arrays:

```<code>$date = array('2017-06-10',
              '2017-06-11',
              '2017-06-12');
$time_start = array('02:00 PM',
                    '03:00 PM',
                    '04:00 PM');
$time_end = array('05:00 PM',
                  '06:00 PM',
                  '07:00 PM');
</code>```

I want to put these arrays into one array that will produce this form:

```<code>$frequency = array(array('2017-06-10','02:00 PM','05:00 PM'),
                   array('2017-06-11','03:00 PM','06:00 PM'),
                   array('2017-06-12','04:00 PM','07:00 PM'));
</code>```

I tried array_combine and array_merge but they showed different results as what I wanted to produce. Please help.

答:
You can also map them:</p>

```<code>$result = array_map(function ($value1,$value2,$value3) {
        return [$value1,$value2,$value3];
}, $date,$time_start,$time_end);
</code>```

Body:
I have these 3 arrays:

$date = array('2017-06-10',
              '2017-06-11',
              '2017-06-12');
$time_start = array('02:00 PM',
                    '03:00 PM',
                    '04:00 PM');
$time_end = array('05:00 PM',
                  '06:00 PM',
                  '07:00 PM');

I want to put these arrays into one array that will produce this form:

$frequency = array(array('2017-06-10','02:00 PM','05:00 PM'),
                   array('2017-06-11','03:00 PM','06:00 PM'),
                   array('2017-06-12','04:00 PM','07:00 PM'));

I tried array_combine and array_merge but they showed different results as what I wanted to produce. Please help.

Body:
You can also map them:

$result = array_map(function ($value1,$value2,$value3) {
        return [$value1,$value2,$value3];
}, $date,$time_start,$time_end);


问:
To get the tagname of clicked element via ng-click using angularjs
I am facing a problem with ng-click event. Below is my code. When I click on the element, it retrieves the span tag and if I call currentTarget, it gives the li element. I want to get the  element on ng-click.And after getting  element i have to check whether it has a class named 'havesub', How can I achieve it?

```<code><li>
  <a class="havesub" ui-sref="" ng-click="openmenu($event)">
    <img src="images/icon-03.png" alt="menu" />
    <span>Menu item1</span>
  </a>
</li>
</code>```

Below is my function in controller

```<code>app.controller("con", function($scope) {
  $scope.openmenu = function($event) {
    var targets = $event.currentTarget;
  };
});
</code>```

答:
var app = angular.module("ngClickApp", []);
app.controller('ngClickCtrl', ['$scope', function ($scope) {
$scope.click=function(event){
 alert(angular.element(event.currentTarget).hasClass("havesub"));
}
}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="ngClickApp">
<head>
 <title>Validation messages</title>
</head>
<body ng-controller="ngClickCtrl">
<form name="userForm">

 <li>

    <img src="1.png" alt="menu" />
    <span>Menu item1</span>

</li>

</form>
</body>
</html></code>```

event.currentTarget works fine for me

```<code><html ng-app="ngClickApp">
<head>
    <title>Validation messages</title>
</head>
<body ng-controller="ngClickCtrl">
<form name="userForm">

 <li>
  <a href  class="havesub"  ng-click="click($event)">
    <img src="1.png" alt="menu" />
    <span>Menu item1</span>
  </a>
</li>

</form>
<script type="text/javascript">
var app = angular.module("ngClickApp", []);
app.controller('ngClickCtrl', ['$scope', function ($scope) {
$scope.click=function(event){
    alert(angular.element(event.currentTarget).hasClass("havesub"));
}
}]);
</script>
</body>
</html>
</code>```

Body:
I am facing a problem with ng-click event. Below is my code. When I click on the element, it retrieves the span tag and if I call currentTarget, it gives the li element. I want to get the  element on ng-click.And after getting  element i have to check whether it has a class named 'havesub', How can I achieve it?

    Menu item1

Below is my function in controller

app.controller("con", function($scope) {
  $scope.openmenu = function($event) {
    var targets = $event.currentTarget;
  };
});

Body:
var app = angular.module("ngClickApp", []);
app.controller('ngClickCtrl', ['$scope', function ($scope) {
$scope.click=function(event){
 alert(angular.element(event.currentTarget).hasClass("havesub"));
}
}]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="ngClickApp">
<head>
 <title>Validation messages</title>
</head>
<body ng-controller="ngClickCtrl">
<form name="userForm">

 <li>
  <a href  class="havesub"  ng-click="click($event)">
    <img src="1.png" alt="menu" />
    <span>Menu item1</span>
  </a>
</li>

</form>
</body>
</html>

event.currentTarget works fine for me

<html ng-app="ngClickApp">
<head>
    <title>Validation messages</title>
</head>
<body ng-controller="ngClickCtrl">
<form name="userForm">

 <li>
  <a href  class="havesub"  ng-click="click($event)">
    <img src="1.png" alt="menu" />
    <span>Menu item1</span>
  </a>
</li>

</form>
<script type="text/javascript">
var app = angular.module("ngClickApp", []);
app.controller('ngClickCtrl', ['$scope', function ($scope) {
$scope.click=function(event){
    alert(angular.element(event.currentTarget).hasClass("havesub"));
}
}]);
</script>
</body>
</html>


答:
try this using below class you can get recyclerview onclick listener and longclick listneeers

create a RecyclerItemClickListener class

```<code>public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;

public interface OnItemClickListener {
    public void onItemClick(View view, int position);

    public void onLongItemClick(View view, int position);
}

GestureDetector mGestureDetector;

public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
    mListener = listener;
    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
            if (child != null && mListener != null) {
                mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
            }
        }
    });
}

@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
    View childView = view.findChildViewUnder(e.getX(), e.getY());
    if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
        mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
        return true;
    }
    return false;
}

@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}

@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
</code>```

now add lister to recyclerview like this

```<code>        indexRecyclerView.addOnItemTouchListener(
            new RecyclerItemClickListener(MainActivity.this, indexRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {

                @Override
                public void onItemClick(View view, int position) {
                   /// perform your action here

                }

                @Override
                public void onLongItemClick(View view, int position) {

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

ask me in case of any query

Title: OnclickListener on RecylerView and getting the Id of clicked Item

Body:
try this using below class you can get recyclerview onclick listener and longclick listneeers

create a RecyclerItemClickListener class

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;

public interface OnItemClickListener {
    public void onItemClick(View view, int position);

    public void onLongItemClick(View view, int position);
}

GestureDetector mGestureDetector;

public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
    mListener = listener;
    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
            if (child != null && mListener != null) {
                mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
            }
        }
    });
}

@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
    View childView = view.findChildViewUnder(e.getX(), e.getY());
    if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
        mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
        return true;
    }
    return false;
}

@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}

@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}

now add lister to recyclerview like this

        indexRecyclerView.addOnItemTouchListener(
            new RecyclerItemClickListener(MainActivity.this, indexRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {

                @Override
                public void onItemClick(View view, int position) {
                   /// perform your action here

                }

                @Override
                public void onLongItemClick(View view, int position) {

                }
            })
    );

ask me in case of any query


问:
TSQL - Display the date which exist in all Model
```<code>MODEL     DateCreated
----------------------
MODEL_1   2017-07-20
MODEL_1   2017-07-19
MODEL_1   2017-06-10
MODEL_1   2017-06-02
MODEL_2   2017-07-18
MODEL_2   2017-07-17
MODEL_2   2017-06-10
MODEL_2   2017-06-02
MODEL_3   2017-07-20
MODEL_3   2017-07-12
MODEL_3   2017-06-10
MODEL_3   2017-06-02
MODEL_3   2017-05-16
</code>```

Expected result

```<code>DateCreated_Exist_In_All_Model
------------------------------
2017-06-10
2017-06-02
</code>```

This means, only those DateCreated exist in all model will be displayed

Thanks to everyone who willing to help me.

答:
```<code>DECLARE @Temp table(Model varchar(1000), DateCreated date)

INSERT INTO @Temp

SELECT  'MODEL_1' , '2017-07-20'

UNION ALL

SELECT 'MODEL_1',   '2017-07-19'

UNION ALL

SELECT 'MODEL_1',   '2017-06-10'

UNION ALL

SELECT 'MODEL_1',   '2017-06-02'

UNION ALL

SELECT 'MODEL_2',   '2017-07-17'

UNION ALL

SELECT 'MODEL_2',   '2017-06-10'

UNION ALL

SELECT 'MODEL_2',   '2017-06-02'

UNION ALL

SELECT 'MODEL_3',   '2017-07-12'

UNION ALL

SELECT 'MODEL_3 ',  '2017-06-10'

UNION ALL

SELECT 'MODEL_3 ',  '2017-06-02'

UNION ALL

SELECT 'MODEL_3' ,  '2017-05-16'

DECLARE @ModelCount int

SELECT @ModelCount = COUNT(distinct Model) from @Temp

SELECT DISTINCT DateCreated FROM  (

SELECT

COUNT(MODEL) OVER(PARTITION BY DateCreated) AS Counts, Model,

DateCreated

FROM @Temp) AS D

WHERE D.Counts = @ModelCount

Or

SELECT DateCreated FROM  (

SELECT

ROW_NUMBER() OVER(PARTITION BY DateCreated ORDER BY DateCreated) as Rownum,

COUNT(MODEL) OVER(PARTITION BY DateCreated) AS Counts, Model,

DateCreated

FROM @Temp) AS D

WHERE D.Counts = @ModelCount and D.Rownum = 1
</code>```

Body:
MODEL     DateCreated
----------------------
MODEL_1   2017-07-20
MODEL_1   2017-07-19
MODEL_1   2017-06-10
MODEL_1   2017-06-02
MODEL_2   2017-07-18
MODEL_2   2017-07-17
MODEL_2   2017-06-10
MODEL_2   2017-06-02
MODEL_3   2017-07-20
MODEL_3   2017-07-12
MODEL_3   2017-06-10
MODEL_3   2017-06-02
MODEL_3   2017-05-16

Expected result

DateCreated_Exist_In_All_Model
------------------------------
2017-06-10
2017-06-02

This means, only those DateCreated exist in all model will be displayed

Thanks to everyone who willing to help me.


问:
Why is php str_pad only working every 3rd time for Unicode Character “─”
I am doing a simple str_pad with the Unicode Character “─” https://www.compart.com/en/unicode/U+2500

```<code>for($i=0;$i<50;$i++){
    echo str_pad("", $i,"─");
    echo "\n";
}
</code>```

But the output in PHP CLI is displaying :

```<code>▒
▒
─
─▒
─▒
──
──▒
──▒
───
───▒
───▒
────
────▒
────▒
─────
─────▒
─────▒
──────
...
</code>```

So it appears every 3rd line is correct, but the 1st and 2nd have a different end of line character.

But if I used str_repeat this works fine :

```<code>for($i=0;$i<50;$i++){
    echo str_repeat("─", $i);
    echo "\n";
}
</code>```

Results in :

```<code>─
──
───
────
─────
──────
───────
────────
─────────
──────────
...
</code>```

So str_repeat works fine, but str_pad has a very weird and unexpected result. Any idea why this is happening?

答:
Looks like a multibyte issue.

A quick way to get str_pad to work using Unicode characters

```<code>for($i=0;$i<50;$i++){
    echo str_pad("", $i*strlen("─"),"─");
    echo "\n";
}
</code>```

So this will give the desired output of :

```<code>─
──
───
────
─────
──────
───────
────────
...
</code>```

But this will break when you actually have a string to pad out :

```<code>for($i=0;$i<50;$i++){
    echo str_pad("X", $i*strlen("─"),"─");
    echo "\n";
}
</code>```

Becomes :

```<code>X
X▒
X─▒
X──▒
X───▒
X────▒
X─────▒
....
</code>```

So just need to use the multibyte version example :
http://php.net/manual/en/function.str-pad.php#116244

```<code>for($i=0;$i<50;$i++){
    echo mb_str_pad("X", $i,"─");
    echo "\n";
}

function mb_str_pad($str, $pad_len, $pad_str = ' ', $dir = STR_PAD_RIGHT, $encoding = NULL)
{
    $encoding = $encoding === NULL ? mb_internal_encoding() : $encoding;
    $padBefore = $dir === STR_PAD_BOTH || $dir === STR_PAD_LEFT;
    $padAfter = $dir === STR_PAD_BOTH || $dir === STR_PAD_RIGHT;
    $pad_len -= mb_strlen($str, $encoding);
    $targetLen = $padBefore && $padAfter ? $pad_len / 2 : $pad_len;
    $strToRepeatLen = mb_strlen($pad_str, $encoding);
    $repeatTimes = ceil($targetLen / $strToRepeatLen);
    $repeatedString = str_repeat($pad_str, max(0, $repeatTimes)); // safe if used with valid utf-8 strings
    $before = $padBefore ? mb_substr($repeatedString, 0, floor($targetLen), $encoding) : '';
    $after = $padAfter ? mb_substr($repeatedString, 0, ceil($targetLen), $encoding) : '';
    return $before . $str . $after;
}
</code>```

Body:
I am doing a simple str_pad with the Unicode Character “─” https://www.compart.com/en/unicode/U+2500

for($i=0;$i<50;$i++){
    echo str_pad("", $i,"─");
    echo "\n";
}

But the output in PHP CLI is displaying :

▒
▒
─
─▒
─▒
──
──▒
──▒
───
───▒
───▒
────
────▒
────▒
─────
─────▒
─────▒
──────
...

So it appears every 3rd line is correct, but the 1st and 2nd have a different end of line character.

But if I used str_repeat this works fine :

for($i=0;$i<50;$i++){
    echo str_repeat("─", $i);
    echo "\n";
}

Results in :

─
──
───
────
─────
──────
───────
────────
─────────
──────────
...

So str_repeat works fine, but str_pad has a very weird and unexpected result. Any idea why this is happening?

Body:
Looks like a multibyte issue.

A quick way to get str_pad to work using Unicode characters

for($i=0;$i<50;$i++){
    echo str_pad("", $i*strlen("─"),"─");
    echo "\n";
}

So this will give the desired output of :

─
──
───
────
─────
──────
───────
────────
...

But this will break when you actually have a string to pad out :

for($i=0;$i<50;$i++){
    echo str_pad("X", $i*strlen("─"),"─");
    echo "\n";
}

Becomes :

X
X▒
X─▒
X──▒
X───▒
X────▒
X─────▒
....

So just need to use the multibyte version example :
http://php.net/manual/en/function.str-pad.php#116244

for($i=0;$i<50;$i++){
    echo mb_str_pad("X", $i,"─");
    echo "\n";
}

function mb_str_pad($str, $pad_len, $pad_str = ' ', $dir = STR_PAD_RIGHT, $encoding = NULL)
{
    $encoding = $encoding === NULL ? mb_internal_encoding() : $encoding;
    $padBefore = $dir === STR_PAD_BOTH || $dir === STR_PAD_LEFT;
    $padAfter = $dir === STR_PAD_BOTH || $dir === STR_PAD_RIGHT;
    $pad_len -= mb_strlen($str, $encoding);
    $targetLen = $padBefore && $padAfter ? $pad_len / 2 : $pad_len;
    $strToRepeatLen = mb_strlen($pad_str, $encoding);
    $repeatTimes = ceil($targetLen / $strToRepeatLen);
    $repeatedString = str_repeat($pad_str, max(0, $repeatTimes)); // safe if used with valid utf-8 strings
    $before = $padBefore ? mb_substr($repeatedString, 0, floor($targetLen), $encoding) : '';
    $after = $padAfter ? mb_substr($repeatedString, 0, ceil($targetLen), $encoding) : '';
    return $before . $str . $after;
}


问:
Stop HTML/Javascript page from loading mid initialization
So imagine a piece of Javascript as the first script on a page along the lines of

```<code>var MySuperObject = new (function () {
    this.SuperObjectInit();
})();
</code>```

Now imagine that everything that proceeds this script (or a large portion therein) requires the SuperObject to have met its load conditions and loaded correctly.

Assuming for whatever reason the loading of the object fails I need to abort loading the rest of the page and the scripts in particular.

I know the majority of you are going to scream why not have your function issue a callback onSuccess and onFailed but the problem is this is in a ASP.Net project with masterpages, nestedmasterpages, usercontrols and so forth (each of which have their own dependencies and scripts); rendering such an approach problematic.

The other option (I assume) is to use window.location = "myErrorPage.html"; but I dont like the idea of having to create another page for an error message or the fact that it causes a redirect.

What I am hoping to do is something along the lines of

```<code>StopLoadingPage();
document.write("Error has occurred");
</code>```

But not sure how this might be accomplished.

答:
What you're trying to achieve isn't how web pages are designed, so as far as I know it is not possible. Logically, you can only stop in Javascript what was started in Javascript, so the only workaround I can think of is to load the dependent scripts asynchronously.

I know this isn't the solution you're looking for, but if there's no other alternative (and I don't think there is), have a look at RequireJS, which handles your JS dependencies for you (no need for callbacks etc...): http://requirejs.org/

Body:
So imagine a piece of Javascript as the first script on a page along the lines of

var MySuperObject = new (function () {
    this.SuperObjectInit();
})();

Now imagine that everything that proceeds this script (or a large portion therein) requires the SuperObject to have met its load conditions and loaded correctly.

Assuming for whatever reason the loading of the object fails I need to abort loading the rest of the page and the scripts in particular.

I know the majority of you are going to scream why not have your function issue a callback onSuccess and onFailed but the problem is this is in a ASP.Net project with masterpages, nestedmasterpages, usercontrols and so forth (each of which have their own dependencies and scripts); rendering such an approach problematic.

The other option (I assume) is to use window.location = "myErrorPage.html"; but I dont like the idea of having to create another page for an error message or the fact that it causes a redirect.

What I am hoping to do is something along the lines of

StopLoadingPage();
document.write("Error has occurred");

But not sure how this might be accomplished.


问:
How to implement: Express (ISO 10303-21) TYPE typename = SELECT in C#
At the moment I am writing a really basic Early Binding for IFC, that is mapped following the Express-standard described in ISO 10303-21.
As I've only just started coding two months ago, everything I do is fairly basic still. However, I can already create all the entities and types with all their properties within the given schema. I'm also able to map that to a file, following the ISO.
There are still a problem I'm coming across:

in the schema, there are types that are SELECT types, looking like the follwoing:

```<code>TYPE IfcGridPlacementDirectionSelect = SELECT
(IfcDirection
,IfcVirtualGridIntersection);
END_TYPE;
</code>```

IfcDirection and IfcVirtualGridIntersection are both entities or types themselves ( I create a class for a type and an entity likewise).
My TYPE IfcGridPlacementDirectionSelect - class looks something like this:

```<code>public class IfcGridPlacementDirectionSelect :IfcBase
{
   public IfcBase _value { get; set; }
}
</code>```

Is there any way to implement the select structure into csharp so the property-type of _value is either "IfcDirection" or "IfcVirtualGridIntersection" instead of what I'm making it now "IfcBase". So that the SELECT-structure would be represented?

答:
I've implemented it now by using an Generic Class. This not a very elegant method, but it works. The only problem is, that now the user can select any type. Therfore you gotta rely on the user knowing what he can actually select. For my example that works for now. </p>

```<code>public class IfcGridPlacementDirectionSelect< T > : IfcBase
{
   public T _value { get; set; }
}
</code>```

Body:
At the moment I am writing a really basic Early Binding for IFC, that is mapped following the Express-standard described in ISO 10303-21.
As I've only just started coding two months ago, everything I do is fairly basic still. However, I can already create all the entities and types with all their properties within the given schema. I'm also able to map that to a file, following the ISO.
There are still a problem I'm coming across:

in the schema, there are types that are SELECT types, looking like the follwoing:

TYPE IfcGridPlacementDirectionSelect = SELECT
(IfcDirection
,IfcVirtualGridIntersection);
END_TYPE;

IfcDirection and IfcVirtualGridIntersection are both entities or types themselves ( I create a class for a type and an entity likewise).
My TYPE IfcGridPlacementDirectionSelect - class looks something like this:

public class IfcGridPlacementDirectionSelect :IfcBase
{
   public IfcBase _value { get; set; }
}

Is there any way to implement the select structure into csharp so the property-type of _value is either "IfcDirection" or "IfcVirtualGridIntersection" instead of what I'm making it now "IfcBase". So that the SELECT-structure would be represented?

Body:
I've implemented it now by using an Generic Class. This not a very elegant method, but it works. The only problem is, that now the user can select any type. Therfore you gotta rely on the user knowing what he can actually select. For my example that works for now.

public class IfcGridPlacementDirectionSelect< T > : IfcBase
{
   public T _value { get; set; }
}


问:
Avoiding hardcoded ip addresses in Android
I use the following approach to store the server ip address in my android project so that the server url can be accessed by other classes.

```<code>   interface GlobalConstants{
       String SERVER_URL = "192.168.xx.xx";
   }
</code>```

However, this approach requires recompiling each time the IP address changes and decompiling will expose the server url. Is there a better approach to initialize SERVER_URL ?

I tried System.setProperty() and System.getProperty() but still it is done at runtime. Is there a way to use something like a configuration file to store IP address and make it configurable?

Thanks in advance. :)

答:
You can do this in gradle.build

```<code> buildTypes {
        debug {
            buildConfigField "String", "SERVER_URL", "\"http:TempRequest\""
        }
        release {
            buildConfigField "String", "SERVER_URL", "\"http:TempRequest\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
</code>```

Then you can acess it using BuildConfig class that android studio will generate.

For example

```<code>String url = BuildConfig.SERVER_URL + "endpoint";
</code>```

I hope this will help you.

Body:
I use the following approach to store the server ip address in my android project so that the server url can be accessed by other classes.

   interface GlobalConstants{
       String SERVER_URL = "192.168.xx.xx";
   }

However, this approach requires recompiling each time the IP address changes and decompiling will expose the server url. Is there a better approach to initialize SERVER_URL ?

I tried System.setProperty() and System.getProperty() but still it is done at runtime. Is there a way to use something like a configuration file to store IP address and make it configurable?

Thanks in advance. :)

Body:
You can do this in gradle.build

 buildTypes {
        debug {
            buildConfigField "String", "SERVER_URL", "\"http:TempRequest\""
        }
        release {
            buildConfigField "String", "SERVER_URL", "\"http:TempRequest\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

Then you can acess it using BuildConfig class that android studio will generate.

For example

String url = BuildConfig.SERVER_URL + "endpoint";

I hope this will help you.


问:
Dexie: where clause - cant get it to use a plain object containing criterias
I've been searching trough dexie docs and here on stack but i can't find anything related. I'm new to dexie and it's the end of my work day, probably it's something that I didn't understand correctly (ー_ー)!!

This way it works:

```<code>DB['t_menus_' + langAbrev].where('menu_type', 'menu_group').equals('6', '3').toArray();
</code>```

But this way won't work, why?

```<code>let theWhere = {menu_type: '6'};
theWhere['menu_group'] = '3';

DB['t_menus_' + langAbrev].where({menu_type: '6', menu_group: '3'}).toArray());
DB['t_menus_' + langAbrev].where(theWhere).toArray());
</code>```

The error message: Uncaught TypeError: DB.t_menus_ptg.where(...).toArray is not a function

答:
You need dexie >= 2.0 to use the latter format:

```<code>npm install dexie@^2.0.0-beta.11 --save
</code>```

Or download from:

unpkg.com/dexie@^2.0.0-beta.11/dist/dexie.js

Body:
I've been searching trough dexie docs and here on stack but i can't find anything related. I'm new to dexie and it's the end of my work day, probably it's something that I didn't understand correctly (ー_ー)!!

This way it works:

DB['t_menus_' + langAbrev].where('menu_type', 'menu_group').equals('6', '3').toArray();

But this way won't work, why?

let theWhere = {menu_type: '6'};
theWhere['menu_group'] = '3';

DB['t_menus_' + langAbrev].where({menu_type: '6', menu_group: '3'}).toArray());
DB['t_menus_' + langAbrev].where(theWhere).toArray());

The error message: Uncaught TypeError: DB.t_menus_ptg.where(...).toArray is not a function

Body:
You need dexie >= 2.0 to use the latter format:

npm install dexie@^2.0.0-beta.11 --save

Or download from:

unpkg.com/dexie@^2.0.0-beta.11/dist/dexie.js


问:
Python numpy array manipulations
I need to somehow make that array:

```<code>[[639 190]
 [ 44   1]
 [ 71   4]
 ...,
 [863 347]
 [870 362]
 [831 359]]
</code>```

look like this:

```<code>[[[639 190]]
 [[ 44   1]]
 [[ 71   4]]
 ...,
 [[863 347]]
 [[870 362]]
 [[831 359]]]
</code>```

How would I do that? I'm new to numpy and I need it for my scientific experiment.

答:
In addition to newaxis/None mentioned by @Divakar,

```<code>np.expand_dims(input_array, axis=1)
</code>```

Title: Python numpy array manipulations

Body:
I need to somehow make that array:

[[639 190]
 [ 44   1]
 [ 71   4]
 ...,
 [863 347]
 [870 362]
 [831 359]]

look like this:

[[[639 190]]
 [[ 44   1]]
 [[ 71   4]]
 ...,
 [[863 347]]
 [[870 362]]
 [[831 359]]]

How would I do that? I'm new to numpy and I need it for my scientific experiment.

Body:
In addition to newaxis/None mentioned by @Divakar,

np.expand_dims(input_array, axis=1)


问:
Instantiate type variable in Haskell
EDIT: Solved. I was unware that enabling a language extension in the source file did not enable the language extension in GHCi. The solution was to :set FlexibleContexts in GHCi.

I recently discovered that type declarations in classes and instances in Haskell are Horn clauses. So I encoded the arithmetic operations from The Art of Prolog, Chapter 3, into Haskell. For instance:

```<code>fac(0,s(0)).
fac(s(N),F) :- fac(N,X), mult(s(N),X,F).

class Fac x y | x -> y
instance Fac Z (S Z)
instance (Fac n x, Mult (S n) x f) => Fac (S n) f

pow(s(X),0,0) :- nat(X).
pow(0,s(X),s(0)) :- nat(X).
pow(s(N),X,Y) :- pow(N,X,Z), mult(Z,X,Y).

class Pow x y z | x y -> z
instance (N n) => Pow (S n) Z Z
instance (N n) => Pow Z (S n) (S Z)
instance (Pow n x z, Mult z x y) => Pow (S n) x y
</code>```

In Prolog, values are instantiated for (logic) variable in a proof. However, I don't understand how to instantiate type variables in Haskell. That is, I don't understand what the Haskell equivalent of a Prolog query

```<code>?-f(X1,X2,...,Xn)
</code>```

is. I assume that

```<code>:t undefined :: (f x1 x2 ... xn) => xi
</code>```

would cause Haskell to instantiate xi, but this gives a Non type-variable argument in the constraint error, even with FlexibleContexts enabled.

答:
No sure about Prolog samples, but I would define this in Haskell in the following way:

```<code>{-# LANGUAGE MultiParamTypeClasses, EmptyDataDecls, FlexibleInstances,
FlexibleContexts, UndecidableInstances, TypeFamilies, ScopedTypeVariables #-}

data Z
data S a
type One = S Z
type Two = S One
type Three = S Two
type Four = S Three

class Plus x y r
instance (r ~ a) => Plus Z a r
instance (Plus a b p, r ~ S p) => Plus (S a) b r

p1 = undefined :: (Plus Two Three r) => r

class Mult x y r
instance (r ~ Z) => Mult Z a r
instance (Mult a b m, Plus m b r) => Mult (S a) b r

m1 = undefined :: (Mult Two Four r) => r

class Fac x r
instance (r ~ One) => Fac Z r
instance (Fac n r1, Mult (S n) r1 r) => Fac (S n) r

f1 = undefined :: (Fac Three r) => r

class Pow x y r
instance (r ~ One) => Pow x Z r
instance (r ~ Z) => Pow Z y r
instance (Pow x y z, Mult z x r) => Pow x (S y) r

pw1 = undefined :: (Pow Two Four r) => r

-- Handy output
class (Num n) => ToNum a n where
    toNum :: a -> n
instance (Num n) => ToNum Z n where
    toNum _ = 0
instance (ToNum a n) => ToNum (S a) n where
    toNum _ = 1 + toNum (undefined :: a)

main = print $ (toNum p1, toNum m1, toNum f1, toNum pw1)
</code>```

Update:

As danportin noted in his comment below TypeFamilies "Lazy pattern" (in instance context) is not needed here (his initial code is shorter and much cleaner).

One application of this pattern though, which I can think of in the context of this question is this: Say we want to add Boolean logic to our type-level arithmetic:

```<code>data HTrue
data HFalse

-- Will not compile
class And x y r | x y -> r
instance And HTrue HTrue HTrue
instance And a b HFalse -- we do not what to enumerate all the combination here - they all HFalse
</code>```

But this will not compile due to "Functional dependencies conflict".
And it looks to me that we still can express this overlapping case without fundeps:

```<code>class And x y r
instance (r ~ HTrue) => And HTrue HTrue r
instance (r ~ HFalse) => And a b r

b1 = undefined :: And HTrue HTrue r => r   -- HTrue
b2 = undefined :: And HTrue HFalse r => r  -- HFalse
</code>```

It's definitely not a nicest way (it requires IncoherentInstances). So maybe somebody can suggest another, less 'traumatic' approach.

Title: Instantiate type variable in Haskell

Body:
EDIT: Solved. I was unware that enabling a language extension in the source file did not enable the language extension in GHCi. The solution was to :set FlexibleContexts in GHCi.

I recently discovered that type declarations in classes and instances in Haskell are Horn clauses. So I encoded the arithmetic operations from The Art of Prolog, Chapter 3, into Haskell. For instance:

fac(0,s(0)).
fac(s(N),F) :- fac(N,X), mult(s(N),X,F).

class Fac x y | x -> y
instance Fac Z (S Z)
instance (Fac n x, Mult (S n) x f) => Fac (S n) f

pow(s(X),0,0) :- nat(X).
pow(0,s(X),s(0)) :- nat(X).
pow(s(N),X,Y) :- pow(N,X,Z), mult(Z,X,Y).

class Pow x y z | x y -> z
instance (N n) => Pow (S n) Z Z
instance (N n) => Pow Z (S n) (S Z)
instance (Pow n x z, Mult z x y) => Pow (S n) x y

In Prolog, values are instantiated for (logic) variable in a proof. However, I don't understand how to instantiate type variables in Haskell. That is, I don't understand what the Haskell equivalent of a Prolog query

?-f(X1,X2,...,Xn)

is. I assume that

:t undefined :: (f x1 x2 ... xn) => xi

would cause Haskell to instantiate xi, but this gives a Non type-variable argument in the constraint error, even with FlexibleContexts enabled.

Body:
No sure about Prolog samples, but I would define this in Haskell in the following way:

{-# LANGUAGE MultiParamTypeClasses, EmptyDataDecls, FlexibleInstances,
FlexibleContexts, UndecidableInstances, TypeFamilies, ScopedTypeVariables #-}

data Z
data S a
type One = S Z
type Two = S One
type Three = S Two
type Four = S Three

class Plus x y r
instance (r ~ a) => Plus Z a r
instance (Plus a b p, r ~ S p) => Plus (S a) b r

p1 = undefined :: (Plus Two Three r) => r

class Mult x y r
instance (r ~ Z) => Mult Z a r
instance (Mult a b m, Plus m b r) => Mult (S a) b r

m1 = undefined :: (Mult Two Four r) => r

class Fac x r
instance (r ~ One) => Fac Z r
instance (Fac n r1, Mult (S n) r1 r) => Fac (S n) r

f1 = undefined :: (Fac Three r) => r

class Pow x y r
instance (r ~ One) => Pow x Z r
instance (r ~ Z) => Pow Z y r
instance (Pow x y z, Mult z x r) => Pow x (S y) r

pw1 = undefined :: (Pow Two Four r) => r

-- Handy output
class (Num n) => ToNum a n where
    toNum :: a -> n
instance (Num n) => ToNum Z n where
    toNum _ = 0
instance (ToNum a n) => ToNum (S a) n where
    toNum _ = 1 + toNum (undefined :: a)

main = print $ (toNum p1, toNum m1, toNum f1, toNum pw1)

Update:

As danportin noted in his comment below TypeFamilies "Lazy pattern" (in instance context) is not needed here (his initial code is shorter and much cleaner).

One application of this pattern though, which I can think of in the context of this question is this: Say we want to add Boolean logic to our type-level arithmetic:

data HTrue
data HFalse

-- Will not compile
class And x y r | x y -> r
instance And HTrue HTrue HTrue
instance And a b HFalse -- we do not what to enumerate all the combination here - they all HFalse

But this will not compile due to "Functional dependencies conflict".
And it looks to me that we still can express this overlapping case without fundeps:

class And x y r
instance (r ~ HTrue) => And HTrue HTrue r
instance (r ~ HFalse) => And a b r

b1 = undefined :: And HTrue HTrue r => r   -- HTrue
b2 = undefined :: And HTrue HFalse r => r  -- HFalse

It's definitely not a nicest way (it requires IncoherentInstances). So maybe somebody can suggest another, less 'traumatic' approach.