问:
Convert .NET Windows Service to Azure Web Job
I have a .NET Windows Service and would like to convert to Azure Web Jobs. Please let me know if I can host it as an Azure Web Jobs or a recommendation to convert.</p>

答:
You can't unfortunately directly host Windows Services in Azure PaaS solutions, unless it is built using TopShelf. Your options are:

Use Azure Virtual Machine to host the Windows Service

Convert the Windows Service so that it can be hosted in Azure PaaS

For conversion the simplest plan is usually the following:

Create a new .NET Console application

Move all the logic from your Windows Service into the .NET Console app

Make the console app work so that once you run it, it executes the logic and exits. So no while loop which keeps the console app running forever.

Publish the console app as a Web Job. You can publish it directly from Visual Studio or upload it using Azure Portal.

Schedule the web job to execute when needed.

You can skip the conversion part if your service uses TopShelf.

If your Windows Service is doing something else than just executing simple logic, for example it hosts WCF or Web Api, the easiest option usually is to convert it into a web app.


来源: stackexchange

问:
url pattern matching php
I have a url of the format /?var1 = val1&var2 = val2;

I want to check for the presence of just var2 = val2 in the url using php. How can that be done?

答:
You can use the $_GET superglobal

if(!empty($_GET['var2']) && $_GET['var2'] == 'val2')) // do something

ContentLicense: CC BY-SA 2.5

Title: url pattern matching php


问:
Problems in creating a new column and looping a formula from first column. code i made and error message is displayed below.

str(st1)
  'data.frame':   4 obs. of  1 variable:
   $ st: num  1 2 3 4
  st1$z=" "
  summary(st1)
         st            z

   Min.   :1.00   Length:4

   1st Qu.:1.75   Class :character

   Median :2.50   Mode  :character

   Mean   :2.50

   3rd Qu.:3.25

   Max.   :4.00

for(i in 1:nrow(st1)) { st1$z[i]= (st1$st-mean(st)/sd(st))}
  Warning messages:
  1: In st1$z[i] <- (st1$st - mean(st)/sd(st)) :
    number of items to replace is not a multiple of replacement length
  2: In st1$z[i] <- (st1$st - mean(st)/sd(st)) :
    number of items to replace is not a multiple of replacement length
  3: In st1$z[i] <- (st1$st - mean(st)/sd(st)) :
    number of items to replace is not a multiple of replacement length
  4: In st1$z[i] <- (st1$st - mean(st)/sd(st)) :
    number of items to replace is not a multiple of replacement length

答:
Try this:</p>

```<code>   for(i in 1:nrow(st1)) {
        st1$z[i]= (st1$st[i]-mean(st)/sd(st))
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Try this:

   for(i in 1:nrow(st1)) {
        st1$z[i]= (st1$st[i]-mean(st)/sd(st))
    }


问:
How can I make MySQL automatically delete records of a table when date of deletion is specified in each record?
I have made the following table in MySQL:

```<code>mysql> use test;
Database changed
mysql> desc NeoTec_test;
+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| Product_Key | varchar(10) | NO   | PRI | NULL    |       |
| Validation  | date        | YES  |     | NULL    |       |
| Expiry      | date        | YES  |     | NULL    |       |
+-------------+-------------+------+-----+---------+-------+
3 rows in set (0.03 sec)

mysql> select * from NeoTec_test;
+-------------+------------+------------+
| Product_Key | Validation | Expiry     |
+-------------+------------+------------+
| GF427DHH5   | 2017-11-16 | 2017-11-17 |
| GFHJV75HG   | 2017-11-16 | 2017-11-18 |
| GFJYFRTV5   | 2017-11-16 | 2017-11-20 |
+-------------+------------+------------+
3 rows in set (0.00 sec)
</code>```

Now coming to the point, I need some help with a part of my project. I want MySQL to automatically delete the Product keys that have expired, i.e., I want to get the product keys deleted automatically on their expiry dates given under the "Expiry" Column of the table. How can I do so? I am a total newbie to MySQL events so I would appreciate the full code... Thank you! :-)

Earlier research I did was not fruitful, but I did found this, which was half helpful...:
How to delete a MySQL record after a certain time

答:
You can use event scheduler to perform the task like below:</p>

```<code>DELIMITER //
CREATE EVENT eventName
ON SCHEDULE EVERY 1 WEEK
STARTS 'Some Date to start'
ENDS 'End date If any'

DO
BEGIN
   DELETE FROM NeoTec_test WHERE NOW() > Expiry
END//
DELIMITER ;
</code>```

Body:
I have made the following table in MySQL:

mysql> use test;
Database changed
mysql> desc NeoTec_test;
+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| Product_Key | varchar(10) | NO   | PRI | NULL    |       |
| Validation  | date        | YES  |     | NULL    |       |
| Expiry      | date        | YES  |     | NULL    |       |
+-------------+-------------+------+-----+---------+-------+
3 rows in set (0.03 sec)

mysql> select * from NeoTec_test;
+-------------+------------+------------+
| Product_Key | Validation | Expiry     |
+-------------+------------+------------+
| GF427DHH5   | 2017-11-16 | 2017-11-17 |
| GFHJV75HG   | 2017-11-16 | 2017-11-18 |
| GFJYFRTV5   | 2017-11-16 | 2017-11-20 |
+-------------+------------+------------+
3 rows in set (0.00 sec)

Now coming to the point, I need some help with a part of my project. I want MySQL to automatically delete the Product keys that have expired, i.e., I want to get the product keys deleted automatically on their expiry dates given under the "Expiry" Column of the table. How can I do so? I am a total newbie to MySQL events so I would appreciate the full code... Thank you! :-)

Earlier research I did was not fruitful, but I did found this, which was half helpful...:
How to delete a MySQL record after a certain time

Body:
You can use event scheduler to perform the task like below:

DELIMITER //
CREATE EVENT eventName
ON SCHEDULE EVERY 1 WEEK
STARTS 'Some Date to start'
ENDS 'End date If any'

DO
BEGIN
   DELETE FROM NeoTec_test WHERE NOW() > Expiry
END//
DELIMITER ;


问:
Effective solution to map names with groups
I have some staff names. Each staff can be in different groups. Say staff names are N1, N2, and N3, and group names are G1, and G2.

I need to show in a webpage which staff belongs which group (sorting by groups). E.g. G1 contains N1 and N2.

Also I need to show (when another button is clicked) for each staff what are the groups they belongs to. E.g. N1 belongs to G1 and G2.

What is the effective way to do this in a webpage?

答:
I have create an object with staffname as key and groupsArray as value;

Others must be self-explanatory; Hope this helps

let staffsArray = ["N1","N2","N3"];

staffs = [{
 "N1" : ["G1","G2","G3"]
},{
 "N2" : ["G1"]
},
{
 "N3" : ["G3"]
},
{
 "N4" : ["G2","G3"]
}]

window.onload =  appendStaffsToDropDown();

function appendStaffsToDropDown() {
 staffsArray.map((staffName) => {
  let staffNameDiv = document.createElement("option");
  let x = document.createElement("OPTION");
     x.setAttribute("value", staffName);
     let t = document.createTextNode(staffName);
     x.appendChild(t);
     document.getElementById("staffDropDown").appendChild(x)
 });
 displayStaffDetails();
}

function displayStaffDetails() {
 staffsArray.map((staffName) => {
  staffs.map((staffObject) => {
   if(staffObject[staffName] != undefined) {
    let parentDiv = document.getElementById('staffDetails');

    let staffNameDiv = document.createElement("div");
    let staffNameContent = document.createTextNode("staffName :" + staffName);
    staffNameDiv.appendChild(staffNameContent);
    parentDiv.appendChild(staffNameDiv)

    let staffGroupDiv = document.createElement("div");
    let staffGroupContent = document.createTextNode("StaffGroup :" + staffObject[staffName]);
    staffGroupDiv.appendChild(staffGroupContent);

    parentDiv.appendChild(staffGroupDiv)
   }
  });
 });
}

document.getElementById("staffDropDown").onchange = function () {
 let staffName = document.getElementById("staffDropDown").value;

 var filteredDetails = document.getElementById("filteredDetails");
 while (filteredDetails.firstChild) {
     filteredDetails.removeChild(filteredDetails.firstChild);
 }

 staffs.map((staffObject) => {
  if(staffObject[staffName] != undefined) {
   let parentDiv = document.getElementById('filteredDetails');

   let staffNameDiv = document.createElement("div");
   let staffNameContent = document.createTextNode("staffName :" + staffName);
   staffNameDiv.appendChild(staffNameContent);
   parentDiv.appendChild(staffNameDiv)

   let staffGroupDiv = document.createElement("div");
   let staffGroupContent = document.createTextNode("StaffGroup :" + staffObject[staffName]);
   staffGroupDiv.appendChild(staffGroupContent);

   parentDiv.appendChild(staffGroupDiv)

   document.getElementById("staffDetails").style.display = 'none';
  }
 });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="staffDetails">
</div>

<select id="staffDropDown">
<option>Select Staffs</option>
</select>

<button>
Filter groups
</button>

<div id="filteredDetails">
</div></code>```

Body:
I have create an object with staffname as key and groupsArray as value;

Others must be self-explanatory; Hope this helps

let staffsArray = ["N1","N2","N3"];

staffs = [{
 "N1" : ["G1","G2","G3"]
},{
 "N2" : ["G1"]
},
{
 "N3" : ["G3"]
},
{
 "N4" : ["G2","G3"]
}]

window.onload =  appendStaffsToDropDown();

function appendStaffsToDropDown() {
 staffsArray.map((staffName) => {
  let staffNameDiv = document.createElement("option");
  let x = document.createElement("OPTION");
     x.setAttribute("value", staffName);
     let t = document.createTextNode(staffName);
     x.appendChild(t);
     document.getElementById("staffDropDown").appendChild(x)
 });
 displayStaffDetails();
}

function displayStaffDetails() {
 staffsArray.map((staffName) => {
  staffs.map((staffObject) => {
   if(staffObject[staffName] != undefined) {
    let parentDiv = document.getElementById('staffDetails');

    let staffNameDiv = document.createElement("div");
    let staffNameContent = document.createTextNode("staffName :" + staffName);
    staffNameDiv.appendChild(staffNameContent);
    parentDiv.appendChild(staffNameDiv)

    let staffGroupDiv = document.createElement("div");
    let staffGroupContent = document.createTextNode("StaffGroup :" + staffObject[staffName]);
    staffGroupDiv.appendChild(staffGroupContent);

    parentDiv.appendChild(staffGroupDiv)
   }
  });
 });
}

document.getElementById("staffDropDown").onchange = function () {
 let staffName = document.getElementById("staffDropDown").value;

 var filteredDetails = document.getElementById("filteredDetails");
 while (filteredDetails.firstChild) {
     filteredDetails.removeChild(filteredDetails.firstChild);
 }

 staffs.map((staffObject) => {
  if(staffObject[staffName] != undefined) {
   let parentDiv = document.getElementById('filteredDetails');

   let staffNameDiv = document.createElement("div");
   let staffNameContent = document.createTextNode("staffName :" + staffName);
   staffNameDiv.appendChild(staffNameContent);
   parentDiv.appendChild(staffNameDiv)

   let staffGroupDiv = document.createElement("div");
   let staffGroupContent = document.createTextNode("StaffGroup :" + staffObject[staffName]);
   staffGroupDiv.appendChild(staffGroupContent);

   parentDiv.appendChild(staffGroupDiv)

   document.getElementById("staffDetails").style.display = 'none';
  }
 });
}

<div id="staffDetails">
</div>

<select id="staffDropDown">
<option>Select Staffs</option>
</select>

<button>
Filter groups
</button>

<div id="filteredDetails">
</div>


问:
Vue.js dynamic
```

答:
As you are using Vue.js, use Vue.js to change the background, instead of CSS:

var vm = new Vue({
    el: '#vue-instance',
    data: {
        rows: [
            {value: 'green'},
            {value: 'red'},
            {value: 'blue'},
        ],
        item:""
    },
    methods:{
        onTimeSlotClick: function(item){
            console.log(item);
            document.querySelector(".dynamic").style.background = item;
        }
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>
<div id="vue-instance">
    <select class="form-control" v-model="item" v-on:change="onTimeSlotClick(item)">
        <option value="">Select</option>
        <option v-for="row in rows">
            {{row.value}}
        </option>
    </select>
    <div class='dynamic'>VALUE</div>
    <br/><br/>
    <div :style="{ background: item}">Another</div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Title: Vue.js dynamic <style> with variables

Body:
Is it possible to add the dynamic variable in style?

I mean something like:

Body:
As you are using Vue.js, use Vue.js to change the background, instead of CSS:

var vm = new Vue({
    el: '#vue-instance',
    data: {
        rows: [
            {value: 'green'},
            {value: 'red'},
            {value: 'blue'},
        ],
        item:""
    },
    methods:{
        onTimeSlotClick: function(item){
            console.log(item);
            document.querySelector(".dynamic").style.background = item;
        }
    }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>
<div id="vue-instance">
    <select class="form-control" v-model="item" v-on:change="onTimeSlotClick(item)">
        <option value="">Select</option>
        <option v-for="row in rows">
            {{row.value}}
        </option>
    </select>
    <div class='dynamic'>VALUE</div>
    <br/><br/>
    <div :style="{ background: item}">Another</div>
</div>


问:
How is it possible that the output of the following code is true?
```<code>this.someService.findDevices()
          .subscribe((segments) => {
            this.segments = Array.from(segments.segments);
            this.packs.forEach((pack) => {
              pack.segments = Array.from(segments.segments);
              pack.segments[0].devices[0].selected = true; //if commented, output is FALSE
              console.log(this.segments[0].devices[0]); // shows TRUE
            });
          });
</code>```

I created a method where I'm trying to add the segments array to each pack in this.packs.
I am creating a new array using Array.from() but for some reason when I set the pack.segments[0].devices[0] to TRUE, this.segments[0].devices[0] is changing to true as well.

Any idea how to solve it?

答:
You are making a shallow copy of the segments array, which does not clone the devices array inside it.

To do a deep clone and make your code work as expected try the below.

 pack.segments = JSON.parse(JSON.stringify(segments.segments))```

NOTE: The above will not not work if you have any circular reference within the array

Body:
this.someService.findDevices()
          .subscribe((segments) => {
            this.segments = Array.from(segments.segments);
            this.packs.forEach((pack) => {
              pack.segments = Array.from(segments.segments);
              pack.segments[0].devices[0].selected = true; //if commented, output is FALSE
              console.log(this.segments[0].devices[0]); // shows TRUE
            });
          });

I created a method where I'm trying to add the segments array to each pack in this.packs.
I am creating a new array using Array.from() but for some reason when I set the pack.segments[0].devices[0] to TRUE, this.segments[0].devices[0] is changing to true as well.

Any idea how to solve it?

Body:
You are making a shallow copy of the segments array, which does not clone the devices array inside it.

To do a deep clone and make your code work as expected try the below.

 pack.segments = JSON.parse(JSON.stringify(segments.segments))

NOTE: The above will not not work if you have any circular reference within the array


问:
How do I style Paged media elements
Neither google nor the @Page documentation nor this link has any info on this.

I have the following code to show page numbers in a footer on the right of the page of the pdf I generate from html :

```<code>@page {
  @bottom-right {
    content: "Page " counter(page) " of " counter(pages);
  }
}
</code>```

This happily prints Page A of X. How do I style A and X ?

答:
The short answer is that you can't using CSS alone.  In order to style A and X separately from the rest of the text, you need to insert elements to wrap A and X like:

```<code> Page <span class="a">A</span> of <span class="b">B</span>
</code>```

However, you cannot insert tags using the CSS content tag.  Thus in order to accomplish this, you should create a footer element (as described here) in HTML, and style it accordingly.  For example:

```<code><div class="footer">
    Page <span class="a">A</span> of <span class="b">B</span>
</div>

@media screen {
  div.footer {
    display: none;
  }
}

@media print {
  div.footer {
     position: fixed;
     bottom: 0;
     right: 0;
     padding-right: 30px;
  }

  div.footer a{
     // STYLING FOR A GOES HERE
  }
}
</code>```

Title: How do I style Paged media elements

Body:
Neither google nor the @Page documentation nor this link has any info on this.

I have the following code to show page numbers in a footer on the right of the page of the pdf I generate from html :

@page {
  @bottom-right {
    content: "Page " counter(page) " of " counter(pages);
  }
}

This happily prints Page A of X. How do I style A and X ?

Body:
The short answer is that you can't using CSS alone.  In order to style A and X separately from the rest of the text, you need to insert elements to wrap A and X like:

 Page <span class="a">A</span> of <span class="b">B</span>

However, you cannot insert tags using the CSS content tag.  Thus in order to accomplish this, you should create a footer element (as described here) in HTML, and style it accordingly.  For example:

<div class="footer">
    Page <span class="a">A</span> of <span class="b">B</span>
</div>

@media screen {
  div.footer {
    display: none;
  }
}

@media print {
  div.footer {
     position: fixed;
     bottom: 0;
     right: 0;
     padding-right: 30px;
  }

  div.footer a{
     // STYLING FOR A GOES HERE
  }
}


问:
How to hide and show a layout on scrolling down a scroll view in Android?
I have a particular layout which consist a scroll view and an image which is at bottom of the activity. My question is that when I start scrolling up that image will not visible and when the scroll reach to top it is visible again.

I attached my image link so that you get the idea what I want.

答:
You can achieve this easily with android support widget CoordinatorLayout.
Follow this post to hide/show the image based on scrolling.

You can learn more about coordinator layout here


答:
Thete is no functionality in mysql to automatically delete a record. You need to trigger the deletion either through a scheduler (mysql's as shown in the question you found, or an external scheduler such as cron), or via a database trigger.

The latter one is probably an overkill.

I would use a scheduler set to a convenient interval based on your business requirements to clean up the table.

Title: How can I make MySQL automatically delete records of a table when date of deletion is specified in each record?


问:
(Eclipse SDK update error) An error occur while collecting items to be installed
I just updated ADK and I encountered exactly the same problem (the same version of upgrade) as this guy (Cannot update ADT from 22.3.0. to 22.6.1, no updates were found)

I followed their comments, yet I did not see the dialog mentioned in step 4 (4. You should see a dialog that says "this software is already installed, an update will be performed instead". Clicking ok will lead to 22.6.1 being installed.)

Instead, I have the error message that titled

Problem occurred

It says

Installing Software has encountered a problem. An error occurred while
  collecting items to be installed

And a chunk of details is followed, which I do not understand (See below). Could someone help? Thx so much

An error occurred while collecting items to be installed session
  context was:(profile=profile,
  phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=,
  action=). No repository found containing:
  osgi.bundle,com.android.ide.eclipse.adt,22.6.2.v201403212031-1085508
  No repository found containing:
  osgi.bundle,com.android.ide.eclipse.adt.package,22.6.2.v201403212031-1085508
  No repository found containing:
  osgi.bundle,com.android.ide.eclipse.base,22.6.2.v201403212031-1085508
  No repository found containing:
  osgi.bundle,com.android.ide.eclipse.ddms,22.6.2.v201403212031-1085508
  No repository found containing:
  osgi.bundle,com.android.ide.eclipse.gldebugger,22.6.2.v201403212031-1085508
  No repository found containing:
  osgi.bundle,com.android.ide.eclipse.hierarchyviewer,22.6.2.v201403212031-1085508
  No repository found containing:
  osgi.bundle,com.android.ide.eclipse.traceview,22.6.2.v201403212031-1085508
  No repository found containing:
  osgi.bundle,overlay.com.android.ide.eclipse.adt.overlay,22.6.2.v201403212031-1085508
  No repository found containing:
  org.eclipse.update.feature,com.android.ide.eclipse.adt,22.6.2.v201403212031-1085508
  No repository found containing:
  org.eclipse.update.feature,com.android.ide.eclipse.ddms,22.6.2.v201403212031-1085508
  No repository found containing:
  org.eclipse.update.feature,com.android.ide.eclipse.gldebugger,22.6.2.v201403212031-1085508
  No repository found containing:
  org.eclipse.update.feature,com.android.ide.eclipse.hierarchyviewer,22.6.2.v201403212031-1085508
  No repository found containing:
  org.eclipse.update.feature,com.android.ide.eclipse.traceview,22.6.2.v201403212031-1085508

答: I recently encountered the same problem and marked answer didn't worked for me. I had tried all the possible solutions to fix this error. Finally I found there were 2 workspace of eclipse under C:\Users\Public\Documents ( Neon, Mars). Just delete the folder which you don't want (Suppose you are working on Neon then delete the other folder Mars) and then try installing update.


问:
iOS - print javascript as text in uiwebview not to execute
><svg/onload=alert(document.domain)> i want to print this text in uiwebview. Right now it gives me alert "myapplication.app" and not showing any text.

To load html string i am using [webView loadHTMLString:HtmlString baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]]; this code.

Basically i want to print javascripts as text in UIWebView and don't want them to get execute.
Thanks.

答: Well i could not find any solution for this. The only reason i was using UIWebview is to show html links. But as UITextview also can show links i changes element from UIWebview to UITextview. Which solve the issue of executing javascript text.


问:
Recycleview's onClick and put extra
Please help!  i have a recycleview with search function(base on JSON search). i wanna click-able this recycleview(mean that getting item's ID where shown in item's view ) and then PutExtra this ID to another activity . then another activity get ID. and finally another activity post ID and get values!

this my code , somebody tell my wrongs:):

AdapterFish.java

```<code>public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context context;
private LayoutInflater inflater;
List<DataFish> data= Collections.emptyList();
DataFish current;
int currentPos=0;
public String IDHOLDER;
private Context activity;

// create constructor to initialize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFish> data){
    this.context=context;
    inflater= LayoutInflater.from(context);
    this.data=data;
}

// Inflate the layout when ViewHolder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view=inflater.inflate(R.layout.container_fish, parent,false);
    MyHolder holder=new MyHolder(view);
    return holder;
}

// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    // Get current position of item in RecyclerView to bind data and assign values from list
    MyHolder myHolder= (MyHolder) holder;
    DataFish current=data.get(position);
    myHolder.company.setText(current.company);
    myHolder.name.setText(current.name);
    myHolder.family.setText(current.family);
    myHolder.id.setText(current.id);
    myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

}

// return total item from List
@Override
public int getItemCount() {
    return data.size();
}

public Context getActivity() {
    return activity;
}

public void setActivity(Context activity) {
    this.activity = activity;
}

class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    TextView company;
    TextView name;
    TextView family;
    TextView id;

    // create constructor to get widget reference
    public MyHolder(View itemView) {
        super(itemView);
        company= (TextView) itemView.findViewById(R.id.company);
        name = (TextView) itemView.findViewById(R.id.name);
        family = (TextView) itemView.findViewById(R.id.family);
        id = (TextView) itemView.findViewById(R.id.id);
        itemView.setOnClickListener(this);
    }

    // Click event for all items
    @Override
    public void onClick(View v) {

        Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
        final String ItemId = id.getText().toString().trim();
        Intent intent = new Intent(context, ShowSingleRecordActivity.class);
        intent.putExtra("ID", ItemId);
        context.startActivity(intent);

    }

}}
</code>```

ShowSingleRecordActivity.java (Receiving ID)

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

HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;

// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";

// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";

String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String  CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;

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

    COMPANY = (TextView)findViewById(R.id.ncompany);
    NAME = (TextView)findViewById(R.id.nname);
    FAMILY=(TextView)findViewById(R.id.nfamily);
    GENDER =(TextView)findViewById(R.id.ngender);
    EMAIL1= (TextView)findViewById(R.id.nemail1);
    EMAIL2= (TextView)findViewById(R.id.nemail2);
    PHONE= (TextView)findViewById(R.id.nphone);
    FAX = (TextView)findViewById(R.id.nfax);
    TELLFAX = (TextView)findViewById(R.id.ntellfax);
    MOBILE = (TextView)findViewById(R.id.nmobile);

    UpdateButton = (Button)findViewById(R.id.buttonUpdate);
    DeleteButton = (Button)findViewById(R.id.buttonDelete);

    //Receiving the ListView Clicked item value send by previous activity.
    TempItem = getIntent().getStringExtra("ID");

    //Calling method to filter Student Record and open selected record.
    HttpWebCall(TempItem);

    UpdateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);

            // Sending Student Id, Name, Number and Class to next UpdateActivity.
            intent.putExtra("Id", TempItem);
            intent.putExtra("company",CompanyHolder );
            intent.putExtra("name", NameHolder);
            intent.putExtra("family",FamilyHolder );
            intent.putExtra("gender",GenderHolder );
            intent.putExtra("email1",Email1Holder );
            intent.putExtra("email2",Email2Holder );
            intent.putExtra("phone",PhoneHolder );
            intent.putExtra("fax",FaxHolder );
            intent.putExtra("tellfax",TellfaxHolder );
            intent.putExtra("mobile",MobileHolder );

            startActivity(intent);

            // Finishing current activity after opening next activity.
            finish();

        }
    });

    // Add Click listener on Delete button.
    DeleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Calling Student delete method to delete current record using Student ID.
            StudentDelete(TempItem);

        }
    });

}

// Method to Delete Student Record
public void StudentDelete(final String StudentID) {

    class StudentDeleteClass extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            progressDialog2.dismiss();

            Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            finish();

        }

        @Override
        protected String doInBackground(String... params) {

            // Sending STUDENT id.
            hashMap.put("StudentID", params[0]);

            finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);

            return finalResult;
        }
    }

    StudentDeleteClass studentDeleteClass = new StudentDeleteClass();

    studentDeleteClass.execute(StudentID);
}

//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){

    class HttpWebCallFunction extends AsyncTask<String,Void,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            pDialog.dismiss();

            //Storing Complete JSon Object into String Variable.
            FinalJSonObject = httpResponseMsg ;

            //Parsing the Stored JSOn String to GetHttpResponse Method.
            new GetHttpResponse(ShowSingleRecordActivity.this).execute();

        }

        @Override
        protected String doInBackground(String... params) {

            ResultHash.put("StudentID",params[0]);

            ParseResult = httpParse.postRequest(ResultHash, HttpURL);

            return ParseResult;
        }
    }

    HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();

    httpWebCallFunction.execute(PreviousListViewClickedItem);
}

// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
    public Context context;

    public GetHttpResponse(Context context)
    {
        this.context = context;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0)
    {
        try
        {
            if(FinalJSonObject != null)
            {
                JSONArray jsonArray = null;

                try {
                    jsonArray = new JSONArray(FinalJSonObject);

                    JSONObject jsonObject;

                    for(int i=0; i<jsonArray.length(); i++)
                    {
                        jsonObject = jsonArray.getJSONObject(i);

                        // Storing Student Name, Phone Number, Class into Variables.
                        CompanyHolder = jsonObject.getString("company");
                        NameHolder = jsonObject.getString("name");
                        FamilyHolder= jsonObject.getString("family");
                        GenderHolder= jsonObject.getString("gender");
                        Email1Holder = jsonObject.getString("email1");
                        Email2Holder = jsonObject.getString("email2");
                        PhoneHolder = jsonObject.getString("phone");
                        FaxHolder = jsonObject.getString("fax");
                        TellfaxHolder = jsonObject.getString("tellfax");
                        MobileHolder = jsonObject.getString("mobile");

                    }
                }
                catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {

        // Setting Student Name, Phone Number, Class into TextView after done all process .
        COMPANY.setText(CompanyHolder);
        NAME.setText(NameHolder);
        FAMILY.setText(FamilyHolder);
        GENDER.setText(GenderHolder);
        EMAIL1.setText(Email1Holder);
        EMAIL2.setText(Email2Holder);
        PHONE.setText(PhoneHolder);
        FAX.setText(FaxHolder);
        TELLFAX.setText(TellfaxHolder);
        MOBILE.setText(MobileHolder);

    }
}
</code>```

and Searching.java

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

// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;

SearchView searchView = null;

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // adds item to action bar
    getMenuInflater().inflate(R.menu.search_main, menu);

    // Get Search item from action bar and Get Search service
    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchManager searchManager = (SearchManager) searching.this.getSystemService(Context.SEARCH_SERVICE);
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(searching.this.getComponentName()));
        searchView.setIconified(false);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    return super.onOptionsItemSelected(item);
}

// Every time when you press search button on keypad an Activity is recreated which in turn calls this function
@Override
protected void onNewIntent(Intent intent) {
    // Get search query and create object of class AsyncFetch
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        if (searchView != null) {
            searchView.clearFocus();
        }
        new AsyncFetch(query).execute();

    }
}

// Create class AsyncFetch
private class AsyncFetch extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(searching.this);
    HttpURLConnection conn;
    URL url = null;
    String searchQuery;

    public AsyncFetch(String searchQuery){
        this.searchQuery=searchQuery;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL("http://192.168.137.1/namayeshgah/search/fish-search.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Connection error");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }

    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        pdLoading.dismiss();
        List<DataFish> data=new ArrayList<>();

        pdLoading.dismiss();
        if(result.equals("no rows")) {
            Toast.makeText(searching.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFish fishData = new DataFish();
                    fishData.company = json_data.getString("company");
                    fishData.name = json_data.getString("name");
                    fishData.family = json_data.getString("family");
                    fishData.id = json_data.getString("id");

                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
                mAdapter = new AdapterFish(searching.this, data);
                mRVFish.setAdapter(mAdapter);
                mRVFish.setLayoutManager(new LinearLayoutManager(searching.this));

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                Toast.makeText(searching.this, e.toString(), Toast.LENGTH_LONG).show();
                Toast.makeText(searching.this, result.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }

}
</code>```

答:
Try this</p>

```<code>@Override
    public void onClick(View v) {
        DataFish newCurrent=data.get(getAdapterPosition());
        Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
        final String ItemId = newCurrent.id;
        Intent intent = new Intent(context, ShowSingleRecordActivity.class);
        intent.putExtra("ID", ItemId);
        context.startActivity(intent);

    }
</code>```

Title: Recycleview's onClick and put extra

Body:
Please help!  i have a recycleview with search function(base on JSON search). i wanna click-able this recycleview(mean that getting item's ID where shown in item's view ) and then PutExtra this ID to another activity . then another activity get ID. and finally another activity post ID and get values!

this my code , somebody tell my wrongs:):

AdapterFish.java

public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context context;
private LayoutInflater inflater;
List<DataFish> data= Collections.emptyList();
DataFish current;
int currentPos=0;
public String IDHOLDER;
private Context activity;

// create constructor to initialize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFish> data){
    this.context=context;
    inflater= LayoutInflater.from(context);
    this.data=data;
}

// Inflate the layout when ViewHolder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view=inflater.inflate(R.layout.container_fish, parent,false);
    MyHolder holder=new MyHolder(view);
    return holder;
}

// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    // Get current position of item in RecyclerView to bind data and assign values from list
    MyHolder myHolder= (MyHolder) holder;
    DataFish current=data.get(position);
    myHolder.company.setText(current.company);
    myHolder.name.setText(current.name);
    myHolder.family.setText(current.family);
    myHolder.id.setText(current.id);
    myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

}

// return total item from List
@Override
public int getItemCount() {
    return data.size();
}

public Context getActivity() {
    return activity;
}

public void setActivity(Context activity) {
    this.activity = activity;
}

class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    TextView company;
    TextView name;
    TextView family;
    TextView id;

    // create constructor to get widget reference
    public MyHolder(View itemView) {
        super(itemView);
        company= (TextView) itemView.findViewById(R.id.company);
        name = (TextView) itemView.findViewById(R.id.name);
        family = (TextView) itemView.findViewById(R.id.family);
        id = (TextView) itemView.findViewById(R.id.id);
        itemView.setOnClickListener(this);
    }

    // Click event for all items
    @Override
    public void onClick(View v) {

        Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
        final String ItemId = id.getText().toString().trim();
        Intent intent = new Intent(context, ShowSingleRecordActivity.class);
        intent.putExtra("ID", ItemId);
        context.startActivity(intent);

    }

}}

ShowSingleRecordActivity.java (Receiving ID)

public class ShowSingleRecordActivity extends AppCompatActivity {

HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;

// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";

// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";

String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String  CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;

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

    COMPANY = (TextView)findViewById(R.id.ncompany);
    NAME = (TextView)findViewById(R.id.nname);
    FAMILY=(TextView)findViewById(R.id.nfamily);
    GENDER =(TextView)findViewById(R.id.ngender);
    EMAIL1= (TextView)findViewById(R.id.nemail1);
    EMAIL2= (TextView)findViewById(R.id.nemail2);
    PHONE= (TextView)findViewById(R.id.nphone);
    FAX = (TextView)findViewById(R.id.nfax);
    TELLFAX = (TextView)findViewById(R.id.ntellfax);
    MOBILE = (TextView)findViewById(R.id.nmobile);

    UpdateButton = (Button)findViewById(R.id.buttonUpdate);
    DeleteButton = (Button)findViewById(R.id.buttonDelete);

    //Receiving the ListView Clicked item value send by previous activity.
    TempItem = getIntent().getStringExtra("ID");

    //Calling method to filter Student Record and open selected record.
    HttpWebCall(TempItem);

    UpdateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);

            // Sending Student Id, Name, Number and Class to next UpdateActivity.
            intent.putExtra("Id", TempItem);
            intent.putExtra("company",CompanyHolder );
            intent.putExtra("name", NameHolder);
            intent.putExtra("family",FamilyHolder );
            intent.putExtra("gender",GenderHolder );
            intent.putExtra("email1",Email1Holder );
            intent.putExtra("email2",Email2Holder );
            intent.putExtra("phone",PhoneHolder );
            intent.putExtra("fax",FaxHolder );
            intent.putExtra("tellfax",TellfaxHolder );
            intent.putExtra("mobile",MobileHolder );

            startActivity(intent);

            // Finishing current activity after opening next activity.
            finish();

        }
    });

    // Add Click listener on Delete button.
    DeleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Calling Student delete method to delete current record using Student ID.
            StudentDelete(TempItem);

        }
    });

}

// Method to Delete Student Record
public void StudentDelete(final String StudentID) {

    class StudentDeleteClass extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            progressDialog2.dismiss();

            Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            finish();

        }

        @Override
        protected String doInBackground(String... params) {

            // Sending STUDENT id.
            hashMap.put("StudentID", params[0]);

            finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);

            return finalResult;
        }
    }

    StudentDeleteClass studentDeleteClass = new StudentDeleteClass();

    studentDeleteClass.execute(StudentID);
}

//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){

    class HttpWebCallFunction extends AsyncTask<String,Void,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            pDialog.dismiss();

            //Storing Complete JSon Object into String Variable.
            FinalJSonObject = httpResponseMsg ;

            //Parsing the Stored JSOn String to GetHttpResponse Method.
            new GetHttpResponse(ShowSingleRecordActivity.this).execute();

        }

        @Override
        protected String doInBackground(String... params) {

            ResultHash.put("StudentID",params[0]);

            ParseResult = httpParse.postRequest(ResultHash, HttpURL);

            return ParseResult;
        }
    }

    HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();

    httpWebCallFunction.execute(PreviousListViewClickedItem);
}

// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
    public Context context;

    public GetHttpResponse(Context context)
    {
        this.context = context;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0)
    {
        try
        {
            if(FinalJSonObject != null)
            {
                JSONArray jsonArray = null;

                try {
                    jsonArray = new JSONArray(FinalJSonObject);

                    JSONObject jsonObject;

                    for(int i=0; i<jsonArray.length(); i++)
                    {
                        jsonObject = jsonArray.getJSONObject(i);

                        // Storing Student Name, Phone Number, Class into Variables.
                        CompanyHolder = jsonObject.getString("company");
                        NameHolder = jsonObject.getString("name");
                        FamilyHolder= jsonObject.getString("family");
                        GenderHolder= jsonObject.getString("gender");
                        Email1Holder = jsonObject.getString("email1");
                        Email2Holder = jsonObject.getString("email2");
                        PhoneHolder = jsonObject.getString("phone");
                        FaxHolder = jsonObject.getString("fax");
                        TellfaxHolder = jsonObject.getString("tellfax");
                        MobileHolder = jsonObject.getString("mobile");

                    }
                }
                catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {

        // Setting Student Name, Phone Number, Class into TextView after done all process .
        COMPANY.setText(CompanyHolder);
        NAME.setText(NameHolder);
        FAMILY.setText(FamilyHolder);
        GENDER.setText(GenderHolder);
        EMAIL1.setText(Email1Holder);
        EMAIL2.setText(Email2Holder);
        PHONE.setText(PhoneHolder);
        FAX.setText(FaxHolder);
        TELLFAX.setText(TellfaxHolder);
        MOBILE.setText(MobileHolder);

    }
}

and Searching.java

public class searching extends AppCompatActivity {

// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;

SearchView searchView = null;

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // adds item to action bar
    getMenuInflater().inflate(R.menu.search_main, menu);

    // Get Search item from action bar and Get Search service
    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchManager searchManager = (SearchManager) searching.this.getSystemService(Context.SEARCH_SERVICE);
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(searching.this.getComponentName()));
        searchView.setIconified(false);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    return super.onOptionsItemSelected(item);
}

// Every time when you press search button on keypad an Activity is recreated which in turn calls this function
@Override
protected void onNewIntent(Intent intent) {
    // Get search query and create object of class AsyncFetch
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        if (searchView != null) {
            searchView.clearFocus();
        }
        new AsyncFetch(query).execute();

    }
}

// Create class AsyncFetch
private class AsyncFetch extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(searching.this);
    HttpURLConnection conn;
    URL url = null;
    String searchQuery;

    public AsyncFetch(String searchQuery){
        this.searchQuery=searchQuery;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL("http://192.168.137.1/namayeshgah/search/fish-search.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Connection error");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }

    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        pdLoading.dismiss();
        List<DataFish> data=new ArrayList<>();

        pdLoading.dismiss();
        if(result.equals("no rows")) {
            Toast.makeText(searching.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFish fishData = new DataFish();
                    fishData.company = json_data.getString("company");
                    fishData.name = json_data.getString("name");
                    fishData.family = json_data.getString("family");
                    fishData.id = json_data.getString("id");

                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
                mAdapter = new AdapterFish(searching.this, data);
                mRVFish.setAdapter(mAdapter);
                mRVFish.setLayoutManager(new LinearLayoutManager(searching.this));

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                Toast.makeText(searching.this, e.toString(), Toast.LENGTH_LONG).show();
                Toast.makeText(searching.this, result.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }

}

Body:
Try this

@Override
    public void onClick(View v) {
        DataFish newCurrent=data.get(getAdapterPosition());
        Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
        final String ItemId = newCurrent.id;
        Intent intent = new Intent(context, ShowSingleRecordActivity.class);
        intent.putExtra("ID", ItemId);
        context.startActivity(intent);

    }


问:
Fastest way to negate a std::vector
Assume I have a std::vector of double, namely

```<code>std::vector<double> MyVec(N);
</code>```

Where N is so big that performance matters. Now assume that MyVec is a nontrivial vector (i.e. it is not a vector of zeros, but has been modified by some routine). Now, I need the negated version of the vector: I need -MyVec.

So far, I have been implementing it via

```<code>std::transform(MyVec.cbegin(),MyVec.cend(),MyVec.begin(),std::negate<double>());
</code>```

But, really, I do not know if this is something sensible or it is just super naïve from my side.

Am I doing it correctly? Or std::transform is just a super slow routine in this case?

PS: I am using BLAS and LAPACK libraries all the time, but I have not found anything that matches this particular need. However, if there exists such a function in BLAS/LAPACK which is faster than std::transform, I would be glad to know.

答:
Use for_each

```<code>std::for_each(MyVec.begin(), MyVec.end(), [](double& val) { val = -val });
</code>```

or C++17 parallel

```<code>std::for_each(std::execution::par_unseq, MyVec.begin(), MyVec.end(), [](double& val) { val = -val });
</code>```

Title: Fastest way to negate a std::vector

Body:
Assume I have a std::vector of double, namely

std::vector<double> MyVec(N);

Where N is so big that performance matters. Now assume that MyVec is a nontrivial vector (i.e. it is not a vector of zeros, but has been modified by some routine). Now, I need the negated version of the vector: I need -MyVec.

So far, I have been implementing it via

std::transform(MyVec.cbegin(),MyVec.cend(),MyVec.begin(),std::negate<double>());

But, really, I do not know if this is something sensible or it is just super naïve from my side.

Am I doing it correctly? Or std::transform is just a super slow routine in this case?

PS: I am using BLAS and LAPACK libraries all the time, but I have not found anything that matches this particular need. However, if there exists such a function in BLAS/LAPACK which is faster than std::transform, I would be glad to know.

Body:
Use for_each

std::for_each(MyVec.begin(), MyVec.end(), [](double& val) { val = -val });

or C++17 parallel

std::for_each(std::execution::par_unseq, MyVec.begin(), MyVec.end(), [](double& val) { val = -val });


问:
Does Java-8 support product of elements of array
Java-8 provides stream to sum the array as following, does the stream support product? If steam doesn't support, is there other way to calculate the product without manually writing my loop?

```<code>int[] a = {1, 2, 3, 4};
int sum = IntStream.of(a).sum();
</code>```

答:
Try it with the reduce method. Something like below:

int product = IntStream.of(a)
    .reduce((i, j) -> i * j)
    .orElse(1); // fallback value if stream is empty
```

Body:
Java-8 provides stream to sum the array as following, does the stream support product? If steam doesn't support, is there other way to calculate the product without manually writing my loop?

int[] a = {1, 2, 3, 4};
int sum = IntStream.of(a).sum();


问:
Laravel retrieve only the email address column in database for users table
Hi I had code that stated

```<code>    $users = User::all();
</code>```

But I only want the email addresses of the users in a collection. So I tried:

```<code>    $users = User::select('id', 'email')->first();
</code>```

This does not work as I want. When I do a var_dump I only want to see the users email addresses. Any tips?

UPDATE: I inserted my blade code as well. I use a Vue component that has a dropdown and I filter the data in the Vue method and insert the filtered data under userEmail:

The component:

```<code>    <commands-component
                :entity-config="commandConfig(command.id, command.signature, command.hasUser, command.title, command.groupID, command.groupName)">
                <input style="margin-right:10px;margin-bottom:10px;" type="button" class="btn btn-primary" v-bind:value="command.title" v-on:click='disableEmailText(command.hasUser)'>
        </commands-component>
</code>```

The Vue:

```<code>    var systemadmin = new Vue({
    el: "#sysadmin",
    data: function() {
        return {
          users: <?php echo $users ?>,
          userData: [],
          commands: <?php echo $commands ?>,
        }
    },

    methods: {
      commandConfig: function(ident, signature, hasUser, title, groupId, groupName){
        var that =  this;
        var commandsGetUsers = [];

        commandsGetUsers  = _.map(that.users, function(value) {
            var newValue = {};
            newValue.value = value.id;
            newValue.text = value.email;
            return newValue;
        });

        return {
          id: { text: 'commandModal' + ident, id: null },
          modalTitle: title,
          buttons: [
              {
                  buttonTitle: 'Run Command',
                  buttonClass: 'btn btn-success pull-right',
                  submitUrl: {
                      url: '/admin/artisan/commands/run',

                  },
              }
          ],
          attributes: [
            {name: "message", displayName: "Are you sure you want to proceed with the command?", type: "action-text",  col: "12" },
            {name: "signature", displayName: "Command Signature", type:'text', col:"6"},
            {name: "userEmail", displayName: "Users", type: 'select', options: commandsGetUsers, col:'6'}
          ],
          data: {
              signature:signature,
              hasUser:hasUser
          }
        };

      },
</code>```

答:
You should try this:

```<code>$users = User::first(['id','email']);
</code>```

OR

```<code>$users = User::get(['id','email']);
</code>```

Body:
Hi I had code that stated

    $users = User::all();

But I only want the email addresses of the users in a collection. So I tried:

    $users = User::select('id', 'email')->first();

This does not work as I want. When I do a var_dump I only want to see the users email addresses. Any tips?

UPDATE: I inserted my blade code as well. I use a Vue component that has a dropdown and I filter the data in the Vue method and insert the filtered data under userEmail:

The component:

    <commands-component
                :entity-config="commandConfig(command.id, command.signature, command.hasUser, command.title, command.groupID, command.groupName)">
                <input style="margin-right:10px;margin-bottom:10px;" type="button" class="btn btn-primary" v-bind:value="command.title" v-on:click='disableEmailText(command.hasUser)'>
        </commands-component>

The Vue:

    var systemadmin = new Vue({
    el: "#sysadmin",
    data: function() {
        return {
          users: <?php echo $users ?>,
          userData: [],
          commands: <?php echo $commands ?>,
        }
    },

    methods: {
      commandConfig: function(ident, signature, hasUser, title, groupId, groupName){
        var that =  this;
        var commandsGetUsers = [];

        commandsGetUsers  = _.map(that.users, function(value) {
            var newValue = {};
            newValue.value = value.id;
            newValue.text = value.email;
            return newValue;
        });

        return {
          id: { text: 'commandModal' + ident, id: null },
          modalTitle: title,
          buttons: [
              {
                  buttonTitle: 'Run Command',
                  buttonClass: 'btn btn-success pull-right',
                  submitUrl: {
                      url: '/admin/artisan/commands/run',

                  },
              }
          ],
          attributes: [
            {name: "message", displayName: "Are you sure you want to proceed with the command?", type: "action-text",  col: "12" },
            {name: "signature", displayName: "Command Signature", type:'text', col:"6"},
            {name: "userEmail", displayName: "Users", type: 'select', options: commandsGetUsers, col:'6'}
          ],
          data: {
              signature:signature,
              hasUser:hasUser
          }
        };

      },

Body:
You should try this:

$users = User::first(['id','email']);

OR

$users = User::get(['id','email']);


问:
Passing multiple data in AJAX
Greetings. I wanted to pass multiple data to my server code. Please find the below flow of my program.
HS110:

```<code>function turnplug2On(){

var newval=this.getAttribute("data-id");
var newval1=this.getAttribute("data-id2");
newval=newval+"On"
console.log(newval);

$(document).ready(function() {
 //console.log(newval);
 $.ajax({
        type: "POST",
        url: 'http://localhost:8124/',
        timeout: 2000,
        data: JSON.stringify({data:newval}),

        //data: '{"data":"plug2On"}',
        //data:newval,

    });
});
}
$(document).ready(function () {
Array.from(document.getElementsByClassName("turn-on")).forEach(function      (button) {
button.onclick = turnplug2On;
});
});

ajax.js:

http.createServer(function (req, res) {
//console.log('request received');
//util.log(util.inspect(req));
console.log(req,res);

res.writeHead(200, {'Content-Type': 'text/plain'});
req.on('data', function (chunk) {
    console.log(chunk.toString());
    //req.on(function (chunk) {
    var obj = JSON.parse(chunk.toString());
    console.log(obj.data);
</code>```

Could you please help me how to pass the object data-id2 to server and how to handle that as a separate data ?
Thanks in advance

答:
```<code>var newval=this.getAttribute("data-id");
var newval1=this.getAttribute("data-id2");
 newval=newval+"On"
  console.log(newval);

  $(document).ready(function() {
 //console.log(newval);
  $.ajax({
    type: "POST",
    url: 'http://localhost:8124/',
    timeout: 2000,
    data: JSON.stringify({newval:newval,newval1:newval1}),

    //data: '{"data":"plug2On"}',
    //data:newval,

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

Title: Passing multiple data in AJAX

Body:
Greetings. I wanted to pass multiple data to my server code. Please find the below flow of my program.
HS110:

function turnplug2On(){

var newval=this.getAttribute("data-id");
var newval1=this.getAttribute("data-id2");
newval=newval+"On"
console.log(newval);

$(document).ready(function() {
 //console.log(newval);
 $.ajax({
        type: "POST",
        url: 'http://localhost:8124/',
        timeout: 2000,
        data: JSON.stringify({data:newval}),

        //data: '{"data":"plug2On"}',
        //data:newval,

    });
});
}
$(document).ready(function () {
Array.from(document.getElementsByClassName("turn-on")).forEach(function      (button) {
button.onclick = turnplug2On;
});
});

ajax.js:

http.createServer(function (req, res) {
//console.log('request received');
//util.log(util.inspect(req));
console.log(req,res);

res.writeHead(200, {'Content-Type': 'text/plain'});
req.on('data', function (chunk) {
    console.log(chunk.toString());
    //req.on(function (chunk) {
    var obj = JSON.parse(chunk.toString());
    console.log(obj.data);

Could you please help me how to pass the object data-id2 to server and how to handle that as a separate data ?
Thanks in advance


问:
Breakpoints are crossed out, how can I make them valid?
i got a tricky one:

I can't set valid breakpoints. Not in Tests, neither in my Java Classes. I searched Stackoverflow and google, but I couldn't find anybody with the same problem.

I'm using STS(x86) and Maven.

Edit: It may seem confusing but I solved it by myself.
I have to go Run-> Skip all Breakpoints (it was set, and I wonder how it was set, because I didn't do it)

答:
You should already be in debug perspective. If not just go to debug perspective. You should see disable all breakpoints button.  -

Click on it and it should allow all breakpoints.


问:
Incomplete Stories for the Sprint
As the ScrumMaster, I am interested in a report that would show me which stories did not complete during the sprint.  While I track this manually outside of the tool, I was curious if there is an easier way?

For instance, in Jira, once a sprint ends, you can see the "incomplete stories" in a sprint report.  Is there something similar for VSTS that would easily allow me to pull stories that were originally forecasted for the sprint, but were not closed by the end date of the sprint?

答:
If you don’t care when the stories complete (change state to close), you can create a query to retrieve all story work items with state (close) and sprint (past sprint).

If the stories must be closed in the sprint time period (e.g. some stories are closed, but closed beyond the sprint time period), there isn’t the way to do it in VSTS, you need to track this manually or programmatically (can build an VSTS extension).

Title: Incomplete Stories for the Sprint


问:
Smallest jQuery lightbox script
What's the smallest lightbox plugin for jQuery (in terms of size)? Something close to Fancybox, but smaller :)</p>

答:
My approach to these sort of problems is to find a script that meets my requirements then hack it mercilessly until it only contains what I need. Once that's achieved, I'll minify the script (leaving the compression of the script up to my server).

While we're on the subject, if you are looking for small scripts mainly to reduce the browser fetch time, then also ensure that your web server cache control headers and compression settings are set to good values. A nice writeup (regarding caching) can be found here.  If you don't have a good caching policy defined, then it won't matter much whether the script is small if it is being downloaded from the server on every page view.

Title: Smallest jQuery lightbox script


答:
sum and others are just shortcuts to specific reduce calls.

sum: Returns the sum of elements in this stream. This is a special case of
  a reduction and is equivalent to:

```<code> return reduce(0, Integer::sum);
</code>```

Reduce: Performs a reduction on the elements of this stream, using the
  provided identity value and an associative accumulation function, and
  returns the reduced value.

Then you can write something like:

```<code>int[] a = {1, 2, 3, 4};
int prod = IntStream.of(a).reduce(1,(x,y)->x*y);
</code>```

Title: Does Java-8 support product of elements of array

Body:
sum and others are just shortcuts to specific reduce calls.

sum: Returns the sum of elements in this stream. This is a special case of
  a reduction and is equivalent to:

 return reduce(0, Integer::sum);

Reduce: Performs a reduction on the elements of this stream, using the
  provided identity value and an associative accumulation function, and
  returns the reduced value.

Then you can write something like:

int[] a = {1, 2, 3, 4};
int prod = IntStream.of(a).reduce(1,(x,y)->x*y);


答:
Here's a recursive function that accomplishes the task (although right now it generates a bunch of warnings).

mylist <- list(7, c(10, 11, 12, 211, 446, 469), c(10, 11, 12, 13), c(11, 12, 13, 215), c(15, 16), c(15, 17, 216, 225))

commonElements = function(l,o=list(l[[1]])){
  if(length(l) == 0){return(o)}
  match = which(unlist(lapply(lapply(o,intersect,l[[1]]),any)))
  if(length(match) == 0) o[[length(o)+1]] = l[[1]]
  if(length(match) == 1) o[[match]] = unique(c(o[[match]],l[[1]]))
  if(length(match) > 1){
    o[[match[1]]] = unique(unlist(o[match]))
    p[rev(match)[-1]] = NULL
  }
  l[[1]] = NULL
  commonElements(l,o)
}

commonElements(mylist)
```

Basically, pass in a list and instantiate the output, o, with the first element of l.  Then check each value of l against every group in o, if it matches nothing, make a new element in o, if it matches one, keep the unique set and if it matches more than 1, concatenate the groups in o and drop the extras.

Title: Merging list with common elements

Body:
I have a list

[[1]]
[1] 7

[[2]]
[1] 10 11 12 211 446 469

[[3]]
[1] 10 11 12 13

[[4]]
[1] 11 12 13 215

[[5]]
[1] 15 16

[[6]]
[1] 15 17 216 225

I want to merge list slices that have common elements, and index which list slices have been merged. My desired output is below.

$`1`
[1] 7

$`2`, `3`, `4`
[1] 10 11 12 13 211 215 446 469

$`5`,`6`
[1] 15 16 17 216 225

(I've put the original list slice indices as new list names, but any form of output is fine.)

Reproducible data:

mylist <- list(7, c(10, 11, 12, 211, 446, 469), c(10, 11, 12, 13), c(11,
12, 13, 215), c(15, 16), c(15, 17, 216, 225))

Body:
Here's a recursive function that accomplishes the task (although right now it generates a bunch of warnings).

mylist <- list(7, c(10, 11, 12, 211, 446, 469), c(10, 11, 12, 13), c(11, 12, 13, 215), c(15, 16), c(15, 17, 216, 225))

commonElements = function(l,o=list(l[[1]])){
  if(length(l) == 0){return(o)}
  match = which(unlist(lapply(lapply(o,intersect,l[[1]]),any)))
  if(length(match) == 0) o[[length(o)+1]] = l[[1]]
  if(length(match) == 1) o[[match]] = unique(c(o[[match]],l[[1]]))
  if(length(match) > 1){
    o[[match[1]]] = unique(unlist(o[match]))
    p[rev(match)[-1]] = NULL
  }
  l[[1]] = NULL
  commonElements(l,o)
}

commonElements(mylist)

Basically, pass in a list and instantiate the output, o, with the first element of l.  Then check each value of l against every group in o, if it matches nothing, make a new element in o, if it matches one, keep the unique set and if it matches more than 1, concatenate the groups in o and drop the extras.


问:
PowerShell on Windows 7: Set-ExecutionPolicy for regular users
I want to run PowerShell scripts on Windows 7 as a regular user. Whenever I try, I get the following error:

```<code>File C:\Users\danv\Documents\WindowsPowerShell\profile.ps1 cannot be loaded because the
execution of scripts is disabled on this system. Please see "get-help about_signing" for
more details.
At line:1 char:2
+ . <<<<  'C:\Users\danv\Documents\WindowsPowerShell\profile.ps1'
    + CategoryInfo          : NotSpecified: (:) [], PSSecurityException
    + FullyQualifiedErrorId : RuntimeException
</code>```

Attempting to solve via Set-ExecutionPolicy Unrestricted fails:

```<code>PS C:\Users\danv> Set-ExecutionPolicy Unrestricted
Set-ExecutionPolicy : Access to the registry key
'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell'
is denied.
At line:1 char:20
+ Set-ExecutionPolicy <<<<  Unrestricted
    + CategoryInfo          : NotSpecified: (:) [Set-ExecutionPolicy], UnauthorizedAccessException
    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand
</code>```

I can run the Set-ExecutionPolicy Unrestricted command as administrator, but this doesn't seem to propagate to non-administrator users.

How can I successfully run scripts as a non-administrator?

答:
```<code>Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
</code>```

This will set the execution policy for the current user (stored in HKEY_CURRENT_USER) rather than the local machine (HKEY_LOCAL_MACHINE). This is useful if you don't have administrative control over the computer.

RemoteSigned is a safer execution policy than Unrestricted. If you download a script and RemoteSigned is preventing you from executing it, then after vetting the script, remove the restriction by opening the file's properties and flagging "Unblock". If this is infeasible, then you can set the policy to Unrestricted instead.

Body:
I want to run PowerShell scripts on Windows 7 as a regular user. Whenever I try, I get the following error:

File C:\Users\danv\Documents\WindowsPowerShell\profile.ps1 cannot be loaded because the
execution of scripts is disabled on this system. Please see "get-help about_signing" for
more details.
At line:1 char:2
+ . <<<<  'C:\Users\danv\Documents\WindowsPowerShell\profile.ps1'
    + CategoryInfo          : NotSpecified: (:) [], PSSecurityException
    + FullyQualifiedErrorId : RuntimeException

Attempting to solve via Set-ExecutionPolicy Unrestricted fails:

PS C:\Users\danv> Set-ExecutionPolicy Unrestricted
Set-ExecutionPolicy : Access to the registry key
'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell'
is denied.
At line:1 char:20
+ Set-ExecutionPolicy <<<<  Unrestricted
    + CategoryInfo          : NotSpecified: (:) [Set-ExecutionPolicy], UnauthorizedAccessException
    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand

I can run the Set-ExecutionPolicy Unrestricted command as administrator, but this doesn't seem to propagate to non-administrator users.

How can I successfully run scripts as a non-administrator?

Body:
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

This will set the execution policy for the current user (stored in HKEY_CURRENT_USER) rather than the local machine (HKEY_LOCAL_MACHINE). This is useful if you don't have administrative control over the computer.

RemoteSigned is a safer execution policy than Unrestricted. If you download a script and RemoteSigned is preventing you from executing it, then after vetting the script, remove the restriction by opening the file's properties and flagging "Unblock". If this is infeasible, then you can set the policy to Unrestricted instead.


问:
Remove array from multidimentional array using id in php
I want to remove array from multidimentional array using base of ID. I tried using foreach loop. But, It is not working.

Any one help me how to remove this?

Thanks.

=> Array :

```<code>Array
(
    [0] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 234
        )

    [1] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 237
        )

    [2] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 234
        )

    [3] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 237
        )

    [4] => Array
        (
            [id] => 11111
            [value] => No
            [field_id] => 237
        )

)
</code>```

From this array, I want to remove array which

field_id is 234 and value is "No" && field_id is 237 and value is
"No".

field_id is 234 and value is "Yes" && field_id is 237 and value is

"Yes".

So, From this array only ID 11111 array is display otherwise all array remove from current array.

Here is my code using I tried to remove array.

```<code>foreach ($collection->getData() as $key => $value) {
                        if(($value['field_id'] == $ids[0] && $value['value'] == "No")){
                            echo $value['id'];
                            // exit;
                            break;
                        }
                        echo $value['field_id'];
                        echo $value['value'];
                        if(($value['field_id'] == $ids[1] && $value['value'] == "No")){
                            print_r($collection->getData()[$key]);
                            unset($collection->getData()[$key]);
                            unset($collection->getData()[$key-1]);
                        }
                    }
</code>```

答:
Based on the comment that mentioned its a Magento Collection. I think, You could filter the ids in collection itself so that those are not fetched as part of the collection you want. Like:

```<code>$collection = Mage::getModel('your/model')->getCollection();
$collection->addAttributeToFilter('field_id', array('nin' => array(234, 237)));
</code>```

OR, following if your model is non-eav entity model

```<code>$collection = Mage::getModel('your/model')->getCollection();
$collection->addFieldToFilter('field_id', array('nin' => array(234, 237)));
</code>```

Body:
I want to remove array from multidimentional array using base of ID. I tried using foreach loop. But, It is not working.

Any one help me how to remove this?

Thanks.

=> Array :

Array
(
    [0] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 234
        )

    [1] => Array
        (
            [id] => 11109
            [value] => Yes
            [field_id] => 237
        )

    [2] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 234
        )

    [3] => Array
        (
            [id] => 11110
            [value] => No
            [field_id] => 237
        )

    [4] => Array
        (
            [id] => 11111
            [value] => No
            [field_id] => 237
        )

)

From this array, I want to remove array which

field_id is 234 and value is "No" && field_id is 237 and value is
"No".

field_id is 234 and value is "Yes" && field_id is 237 and value is

"Yes".

So, From this array only ID 11111 array is display otherwise all array remove from current array.

Here is my code using I tried to remove array.

foreach ($collection->getData() as $key => $value) {
                        if(($value['field_id'] == $ids[0] && $value['value'] == "No")){
                            echo $value['id'];
                            // exit;
                            break;
                        }
                        echo $value['field_id'];
                        echo $value['value'];
                        if(($value['field_id'] == $ids[1] && $value['value'] == "No")){
                            print_r($collection->getData()[$key]);
                            unset($collection->getData()[$key]);
                            unset($collection->getData()[$key-1]);
                        }
                    }

Body:
Based on the comment that mentioned its a Magento Collection. I think, You could filter the ids in collection itself so that those are not fetched as part of the collection you want. Like:

$collection = Mage::getModel('your/model')->getCollection();
$collection->addAttributeToFilter('field_id', array('nin' => array(234, 237)));

OR, following if your model is non-eav entity model

$collection = Mage::getModel('your/model')->getCollection();
$collection->addFieldToFilter('field_id', array('nin' => array(234, 237)));


问:
import and export not working when debug within vscode
system configuration

Mac OS High Sierra 10.13.1

vs code 1.18.0

node 6.11.4

babel 6.26.0

I want to text es6 feature import export keyword in a pure js file ( no node_modules folders)

create 2 files as below content

utility.js

```<code>export const generateRandom = () => {
    console.log('inside generate Random');
    return Math.random();
};
</code>```

check.js

```<code>import { generateRandom } from './export';

console.log(generateRandom());
</code>```

when hit F5 from check.js and select environmentnt > Node.js

it gives following error in debug console tab

```<code>/opt/parixan/import.js:1 (function (exports, require, module,
__filename, __dirname) { import { generateRandom } from './utility';
                                                              ^^^^^^ SyntaxError: Unexpected token import
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Timeout.Module.runMain [as _onTimeout] (module.js:604:10)
    at ontimeout (timers.js:386:11)
    at tryOnTimeout (timers.js:250:5)
</code>```

In sublime text I can run the same code through custom javascript build system; But how do we run the same in vs code

below are the necessary files

.eslintrc

```<code>    {
        "env":
        {
            "browser": true,
            "node": true,
            "es6": true
        },
        "extends": "eslint:recommended",
        "ecmaFeatures": {
            "modules": true,
            "spread": true,
            "restParams": true
        },
        "parserOptions": {
            "ecmaVersion": 6,
            "sourceType": "module"
        },
        "globals":
        {
            "angular": true,
            "module": true,
            "inject": true,
            "moment": true,
            "saveAs": true,
            "require": false
        },
        "rules":
        {
            "indent": [0, "tab"],
            "linebreak-style": [0, "unix"],
            "semi": [2, "always"],
            "no-console": "off"
        }
    }
</code>```

jsconfig.json

```<code>    {
        "compilerOptions": {
            "target": "ES6",
            "module": "commonjs"
        }
    }
</code>```

答:
As my macOS was updated and it stopped all installed plugin such as babel-node. that's why it stopped compiling js file which has latest es6 syntax. here is the steps to fix the issue

install latest node

nvm istall node

install babel-cli

npm install babel-cli -g

which babel-node will give full path which can be used but we will us babel-node instead of path

now configure both editors with following steps

VSCODE

install code runner

open User settings in vs code and add this line along with other settings

```<code>  "code-runner.executorMap": {
              "javascript": "babel-node"
  }
</code>```

now select the file and press option + control + N to run the code and see the output in the console

Sublime Text 3

create new build system or edit build system with following content, in my case I have added build system so the location is

/Users/{username}/Library/Application Support/Sublime Text 3/Packages/User/node.sublime-build

```<code>{
    "shell_cmd": "babel-node ${file}",
    "selector": "source.js"
}
</code>```

select file and run Ctrl + B from sublime text and output of file will be displayed in the bottom.

Body:
system configuration

Mac OS High Sierra 10.13.1

vs code 1.18.0

node 6.11.4

babel 6.26.0

I want to text es6 feature import export keyword in a pure js file ( no node_modules folders)

create 2 files as below content

utility.js

export const generateRandom = () => {
    console.log('inside generate Random');
    return Math.random();
};

check.js

import { generateRandom } from './export';

console.log(generateRandom());

when hit F5 from check.js and select environmentnt > Node.js

it gives following error in debug console tab

/opt/parixan/import.js:1 (function (exports, require, module,
__filename, __dirname) { import { generateRandom } from './utility';
                                                              ^^^^^^ SyntaxError: Unexpected token import
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Timeout.Module.runMain [as _onTimeout] (module.js:604:10)
    at ontimeout (timers.js:386:11)
    at tryOnTimeout (timers.js:250:5)

In sublime text I can run the same code through custom javascript build system; But how do we run the same in vs code

below are the necessary files

.eslintrc

    {
        "env":
        {
            "browser": true,
            "node": true,
            "es6": true
        },
        "extends": "eslint:recommended",
        "ecmaFeatures": {
            "modules": true,
            "spread": true,
            "restParams": true
        },
        "parserOptions": {
            "ecmaVersion": 6,
            "sourceType": "module"
        },
        "globals":
        {
            "angular": true,
            "module": true,
            "inject": true,
            "moment": true,
            "saveAs": true,
            "require": false
        },
        "rules":
        {
            "indent": [0, "tab"],
            "linebreak-style": [0, "unix"],
            "semi": [2, "always"],
            "no-console": "off"
        }
    }

jsconfig.json

    {
        "compilerOptions": {
            "target": "ES6",
            "module": "commonjs"
        }
    }

Body:
As my macOS was updated and it stopped all installed plugin such as babel-node. that's why it stopped compiling js file which has latest es6 syntax. here is the steps to fix the issue

install latest node

nvm istall node

install babel-cli

npm install babel-cli -g

which babel-node will give full path which can be used but we will us babel-node instead of path

now configure both editors with following steps

VSCODE

install code runner

open User settings in vs code and add this line along with other settings

  "code-runner.executorMap": {
              "javascript": "babel-node"
  }

now select the file and press option + control + N to run the code and see the output in the console

Sublime Text 3

create new build system or edit build system with following content, in my case I have added build system so the location is

/Users/{username}/Library/Application Support/Sublime Text 3/Packages/User/node.sublime-build

{
    "shell_cmd": "babel-node ${file}",
    "selector": "source.js"
}

select file and run Ctrl + B from sublime text and output of file will be displayed in the bottom.


问:
Is storing a Unix timestamp a bad idea in the long term
I've recently started working on a new application and I need to be able to compare times that the user has been active so basically my logic will be something like:

```<code>func pseudo (user string) {
    v := GET Timestamp FROM users;

    if currentTimestamp - 1800 < dbTimestamp
        // Do something
</code>```

I've though about using Unix timestamps, in specific the number of seconds. However I'm not sure if storing this will become a problem as it only grows and I realize it will take a while to add more digits it does not feel like it's the best for performance reasons. Is storing and comparing a Unix timestamp a good idea for long term applications?

Side note:

My application is written in go so while I can store datetime, I have to extract the datetime from the database and attempt to use the atrocious layout numbers and it becomes more complicated attempting to format it to work with the layout numbers.

答:
I guess number of bits is not a big deal - 64bits will be enough for so long time, that all ourdays computer industry will be totally obsolete.

But there's more serious concern. Time is not so plain and linear. Sometimes you have leap seconds which breaks normal flow. Also timezones are sometimes get changed. So storing and working with time as int you have to deal with all strange issues. I definitely recommend switch special data types as in DB so in applications.

I have been using number of seconds for storing dates. That was my habit since I worked with MySQL 3.x and 4.x - they had awful support for dates, so it was easier to realize in app and keep only integer value. But as I've said I had to go through other issues it's not too hard but takes time and error-prone. If at the start of the project you have to keep only a time, later you'll need calculate intervals, then time with local options and so on.

So I recommend using special date time. Go has nice precision and maximum date is 219248499-12-06 - enough for us :). In PostgreSQL maximum year 294276 AD.

Body:
I've recently started working on a new application and I need to be able to compare times that the user has been active so basically my logic will be something like:

func pseudo (user string) {
    v := GET Timestamp FROM users;

    if currentTimestamp - 1800 < dbTimestamp
        // Do something

I've though about using Unix timestamps, in specific the number of seconds. However I'm not sure if storing this will become a problem as it only grows and I realize it will take a while to add more digits it does not feel like it's the best for performance reasons. Is storing and comparing a Unix timestamp a good idea for long term applications?

Side note:

My application is written in go so while I can store datetime, I have to extract the datetime from the database and attempt to use the atrocious layout numbers and it becomes more complicated attempting to format it to work with the layout numbers.