问:
Android: ListView can't click items
I created a ListView with a new adapter. Each item in a row contains a photo and a subtitle. When I click on an item, I need to turn to another class and then show the details. And I generate data using a java class called XMLPeopleParser which get data from the raw xml file which is already put data.
I am defining a setOnItemClickListener but when clicking an item, nothing happens.
Also, the photo in each row couldn't be added.
Any help will be appreciated!

MainActivity.class

```<code>import android.app.Activity;
import android.content.Intent;
import android.provider.Contacts;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class List_Activity extends AppCompatActivity {

    private ListView list = null;
    private TextView mselection = null;
    private ArrayAdapter<String> adapter = null;

    private XMLPeopleParser parser = null;
    private String [] names = null;
    private String [] addresses = null;
    private String [] images = null;

    private Person [] data = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_);
        list = (ListView) findViewById(R.id.listview);
        mselection = (TextView) findViewById(R.id.selection);

        parser = new XMLPeopleParser(getApplicationContext());
        names = parser.getNames();
        addresses = parser.getAddresses();
        images = parser.getImages();
        data = parser.getData();

        list.setAdapter(new IconicAdapter(this));

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Toast.makeText(getApplicationContext(), "Clicked on " + names[position], Toast.LENGTH_LONG).show();

                mselection.setText(names[position]);

            }
        });
    }

    private class IconicAdapter extends ArrayAdapter {
        Activity context;

        IconicAdapter(Activity context) {
            super(context, R.layout.list_row, data);
            this.context = context;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = context.getLayoutInflater();
            View row = inflater.inflate(R.layout.list_row, null);
            ImageView icon = (ImageView) row.findViewById(R.id.icon);
            TextView name_title = (TextView) row.findViewById(R.id.name_title);
            TextView address_title = (TextView) row.findViewById(R.id.address_title);

            name_title.setText(names[position]);
            address_title.setText(addresses[position]);

            int[] ImageIds = new int[images.length];
            String[] ImageNames = new String[images.length];

            ImageNames[position] = images[position].substring(0, images[position].indexOf("."));
            ImageIds[position] = getResources().getIdentifier(ImageNames[position], "drawable", getPackageName());
            Toast.makeText(getBaseContext(), "ImageId is:  " + position + "  " + ImageNames[position], Toast.LENGTH_SHORT).show();
            icon.setImageResource(ImageIds[position]);

            return (row);

        }
    }

}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.ww.custom_list_a.List_Activity">

    <TextView
        android:id="@+id/selection"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        />

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/selection"
        />

</RelativeLayout>
</code>```

list_row.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    >

    <ImageButton
        android:id="@+id/icon"
        android:src="@android:drawable/btn_star"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/name_title"
            android:gravity="center_horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

        <TextView
            android:id="@+id/address_title"
            android:gravity="center_horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
    </LinearLayout>

</LinearLayout>
</code>```

XMLPeopleParser.class

```<code>public class XMLPeopleParser {

    private Person [] data = null;
    private Context context = null;

    public XMLPeopleParser(Context c){

        this.context = c;

        // grab the data from the xml
        // get the doc parser ready for people.xml
        InputStream is = this.context.getResources().openRawResource(R.raw.people);
        DocumentBuilder builder = null;
        Document doc = null;

        try{
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            doc = builder.parse(is);
        }catch (Exception e){}

        NodeList nameList = doc.getElementsByTagName("name");
        NodeList addressList = doc.getElementsByTagName("address");
        NodeList dobList = doc.getElementsByTagName("dob");
        NodeList colourList = doc.getElementsByTagName("color");
        NodeList imageList = doc.getElementsByTagName("image");
        NodeList urlList = doc.getElementsByTagName("url");

        data = new Person[nameList.getLength()];

        for (int i = 0; i < data.length; i++){

            String name = nameList.item(i).getFirstChild().getNodeValue();
            String address = addressList.item(i).getFirstChild().getNodeValue();
            String dob = dobList.item(i).getFirstChild().getNodeValue();
            String colour = colourList.item(i).getFirstChild().getNodeValue();
            String image = imageList.item(i).getFirstChild().getNodeValue();
            String url = urlList.item(i).getFirstChild().getNodeValue();

            data[i] = new Person(name, address, dob, colour, image, url);

        }
    }

    public Person [] getData(){return data;}

    public Person getData(int i) {return data[i];}

    public String[] getNames(){
        String[] names = new String[data.length];

        for (int i = 0; i < names.length; i ++){

            names[i] = getData(i).getName();
        }
        return names;
    }

    public String[] getAddresses() {
        String[] addresses = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            addresses[i] = getData(i).getAddress();
        }
        return  addresses;
    }

    public String[] getDobs() {
        String[] dobs = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            dobs[i] = getData(i).getDob();
        }
        return  dobs;
    }

    public String[] getColours() {
        String[] colours = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            colours[i] = getData(i).getColour();
        }
        return  colours;
    }

    public String[] getImages() {
        String[] images = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            images[i] = getData(i).getImage();

        }
        return  images;
    }

    public String[] geturls() {
        String[] urls = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            urls[i] = getData(i).getUrl();
        }
        return  urls;
    }

}
</code>```

R.raw.people xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<dataroot xmlns:od="urn:schemas-microsoft-com:officedata"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="people.xsd" generated="2011-11-05T23:09:59">

    <person>
        <name>ANDY</name>
        <address>USA</address>
        <color>BLACK</color>
        <dob>2020/2/2</dob>
        <image>andy.jpeg</image>
        <url>https://en.wikipedia.org/wiki/andy</url>
    </person>

    <person>
        <name>Bill</name>
        <address>UK</address>
        <dob>2020/1/1</dob>
        <color>white</color>
        <image>bill.jpeg</image>
        <url>https://en.wikipedia.org/wiki/bill</url>
    </person>
</code>```

答:
Remove following code from your listActivity class:

```<code>list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Toast.makeText(getApplicationContext(), "Clicked on " + names[position], Toast.LENGTH_LONG).show();

                mselection.setText(names[position]);

            }
        });
</code>```

in your IconicAdapter after:

```<code>ImageNames[position] = images[position].substring(0,
images[position].indexOf("."));
            ImageIds[position] = getResources().getIdentifier(ImageNames[position], "drawable", getPackageName());
            Toast.makeText(getBaseContext(), "ImageId is:  " + position + "  " + ImageNames[position], Toast.LENGTH_SHORT).show();
            icon.setImageResource(ImageIds[position]);
</code>```

and before:

```<code>return (row);
</code>```

Use this for your each row to respond onClick:

```<code>row.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    // Do here whatever you want to do upon click
            });
</code>```

Title: Android: ListView can't click items

Body:
I created a ListView with a new adapter. Each item in a row contains a photo and a subtitle. When I click on an item, I need to turn to another class and then show the details. And I generate data using a java class called XMLPeopleParser which get data from the raw xml file which is already put data.
I am defining a setOnItemClickListener but when clicking an item, nothing happens.
Also, the photo in each row couldn't be added.
Any help will be appreciated!

MainActivity.class

import android.app.Activity;
import android.content.Intent;
import android.provider.Contacts;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class List_Activity extends AppCompatActivity {

    private ListView list = null;
    private TextView mselection = null;
    private ArrayAdapter<String> adapter = null;

    private XMLPeopleParser parser = null;
    private String [] names = null;
    private String [] addresses = null;
    private String [] images = null;

    private Person [] data = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_);
        list = (ListView) findViewById(R.id.listview);
        mselection = (TextView) findViewById(R.id.selection);

        parser = new XMLPeopleParser(getApplicationContext());
        names = parser.getNames();
        addresses = parser.getAddresses();
        images = parser.getImages();
        data = parser.getData();

        list.setAdapter(new IconicAdapter(this));

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Toast.makeText(getApplicationContext(), "Clicked on " + names[position], Toast.LENGTH_LONG).show();

                mselection.setText(names[position]);

            }
        });
    }

    private class IconicAdapter extends ArrayAdapter {
        Activity context;

        IconicAdapter(Activity context) {
            super(context, R.layout.list_row, data);
            this.context = context;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = context.getLayoutInflater();
            View row = inflater.inflate(R.layout.list_row, null);
            ImageView icon = (ImageView) row.findViewById(R.id.icon);
            TextView name_title = (TextView) row.findViewById(R.id.name_title);
            TextView address_title = (TextView) row.findViewById(R.id.address_title);

            name_title.setText(names[position]);
            address_title.setText(addresses[position]);

            int[] ImageIds = new int[images.length];
            String[] ImageNames = new String[images.length];

            ImageNames[position] = images[position].substring(0, images[position].indexOf("."));
            ImageIds[position] = getResources().getIdentifier(ImageNames[position], "drawable", getPackageName());
            Toast.makeText(getBaseContext(), "ImageId is:  " + position + "  " + ImageNames[position], Toast.LENGTH_SHORT).show();
            icon.setImageResource(ImageIds[position]);

            return (row);

        }
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.ww.custom_list_a.List_Activity">

    <TextView
        android:id="@+id/selection"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        />

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/selection"
        />

</RelativeLayout>

list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    >

    <ImageButton
        android:id="@+id/icon"
        android:src="@android:drawable/btn_star"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/name_title"
            android:gravity="center_horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

        <TextView
            android:id="@+id/address_title"
            android:gravity="center_horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
    </LinearLayout>

</LinearLayout>

XMLPeopleParser.class

public class XMLPeopleParser {

    private Person [] data = null;
    private Context context = null;

    public XMLPeopleParser(Context c){

        this.context = c;

        // grab the data from the xml
        // get the doc parser ready for people.xml
        InputStream is = this.context.getResources().openRawResource(R.raw.people);
        DocumentBuilder builder = null;
        Document doc = null;

        try{
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            doc = builder.parse(is);
        }catch (Exception e){}

        NodeList nameList = doc.getElementsByTagName("name");
        NodeList addressList = doc.getElementsByTagName("address");
        NodeList dobList = doc.getElementsByTagName("dob");
        NodeList colourList = doc.getElementsByTagName("color");
        NodeList imageList = doc.getElementsByTagName("image");
        NodeList urlList = doc.getElementsByTagName("url");

        data = new Person[nameList.getLength()];

        for (int i = 0; i < data.length; i++){

            String name = nameList.item(i).getFirstChild().getNodeValue();
            String address = addressList.item(i).getFirstChild().getNodeValue();
            String dob = dobList.item(i).getFirstChild().getNodeValue();
            String colour = colourList.item(i).getFirstChild().getNodeValue();
            String image = imageList.item(i).getFirstChild().getNodeValue();
            String url = urlList.item(i).getFirstChild().getNodeValue();

            data[i] = new Person(name, address, dob, colour, image, url);

        }
    }

    public Person [] getData(){return data;}

    public Person getData(int i) {return data[i];}

    public String[] getNames(){
        String[] names = new String[data.length];

        for (int i = 0; i < names.length; i ++){

            names[i] = getData(i).getName();
        }
        return names;
    }

    public String[] getAddresses() {
        String[] addresses = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            addresses[i] = getData(i).getAddress();
        }
        return  addresses;
    }

    public String[] getDobs() {
        String[] dobs = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            dobs[i] = getData(i).getDob();
        }
        return  dobs;
    }

    public String[] getColours() {
        String[] colours = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            colours[i] = getData(i).getColour();
        }
        return  colours;
    }

    public String[] getImages() {
        String[] images = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            images[i] = getData(i).getImage();

        }
        return  images;
    }

    public String[] geturls() {
        String[] urls = new String[data.length];

        for(int i = 0; i < data.length; i++)
        {
            urls[i] = getData(i).getUrl();
        }
        return  urls;
    }

}

R.raw.people xml file:

<?xml version="1.0" encoding="UTF-8"?>
<dataroot xmlns:od="urn:schemas-microsoft-com:officedata"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="people.xsd" generated="2011-11-05T23:09:59">

    <person>
        <name>ANDY</name>
        <address>USA</address>
        <color>BLACK</color>
        <dob>2020/2/2</dob>
        <image>andy.jpeg</image>
        <url>https://en.wikipedia.org/wiki/andy</url>
    </person>

    <person>
        <name>Bill</name>
        <address>UK</address>
        <dob>2020/1/1</dob>
        <color>white</color>
        <image>bill.jpeg</image>
        <url>https://en.wikipedia.org/wiki/bill</url>
    </person>

Body:
Remove following code from your listActivity class:

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Toast.makeText(getApplicationContext(), "Clicked on " + names[position], Toast.LENGTH_LONG).show();

                mselection.setText(names[position]);

            }
        });

in your IconicAdapter after:

ImageNames[position] = images[position].substring(0,
images[position].indexOf("."));
            ImageIds[position] = getResources().getIdentifier(ImageNames[position], "drawable", getPackageName());
            Toast.makeText(getBaseContext(), "ImageId is:  " + position + "  " + ImageNames[position], Toast.LENGTH_SHORT).show();
            icon.setImageResource(ImageIds[position]);

and before:

return (row);

Use this for your each row to respond onClick:

row.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    // Do here whatever you want to do upon click
            });


来源: stackexchange

问:
ios7 app not asking for permission to access photos
My ios 7 app is not asking for permission to view photos. If I delete the app off my device, then build and run again on xcode to install it to the device, whenever the app starts up I can go check the privacy settings and it shows that it has access to photos, even though I never recieved the message box that asks for it like it does location services. I have an imagepicker that is displayed modally at one point during my app and its having issues with displaying a black image preview and I believe its being caused by this photos access issue.

Does anyone know why this is happening?

edit: also, after my app starts, if I go into the privacy settings and change the photo permissions from on to off the app crashes. no warning or error, just crashes.

答:
I was having a similar problem. Creating a NSPhotoLibraryUsageDescription key in the info.plist should fix this, but it doesn't, here is a programming fix:

```<code>func photoLibraryAvailabilityCheck() {
    let status = PHPhotoLibrary.authorizationStatus()
    if (status == PHAuthorizationStatus.authorized) {
        print("PHAuthorizationStatus.authorized")
    }       else if (status == PHAuthorizationStatus.denied) {
        print("PHAuthorizationStatus.denied")
        requestPhotosLibraryAccess()
    }       else if (status == PHAuthorizationStatus.notDetermined) {
        print("PHAuthorizationStatus.notDetermined")
        requestPhotosLibraryAccess()
    }       else if (status == PHAuthorizationStatus.restricted) {
        print("PHAuthorizationStatus.restricted")
    }
}

func requestPhotosLibraryAccess() {
    PHPhotoLibrary.requestAuthorization({ (newStatus) in
        if (newStatus == PHAuthorizationStatus.authorized) {
            print("pressed the allowed button")
        }       else {
            print("pressed the don't allow button")
        }
    })
}
</code>```

To Use:

```<code>photoLibraryAvailabilityCheck()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was having a similar problem. Creating a NSPhotoLibraryUsageDescription key in the info.plist should fix this, but it doesn't, here is a programming fix:

func photoLibraryAvailabilityCheck() {
    let status = PHPhotoLibrary.authorizationStatus()
    if (status == PHAuthorizationStatus.authorized) {
        print("PHAuthorizationStatus.authorized")
    }       else if (status == PHAuthorizationStatus.denied) {
        print("PHAuthorizationStatus.denied")
        requestPhotosLibraryAccess()
    }       else if (status == PHAuthorizationStatus.notDetermined) {
        print("PHAuthorizationStatus.notDetermined")
        requestPhotosLibraryAccess()
    }       else if (status == PHAuthorizationStatus.restricted) {
        print("PHAuthorizationStatus.restricted")
    }
}

func requestPhotosLibraryAccess() {
    PHPhotoLibrary.requestAuthorization({ (newStatus) in
        if (newStatus == PHAuthorizationStatus.authorized) {
            print("pressed the allowed button")
        }       else {
            print("pressed the don't allow button")
        }
    })
}

To Use:

photoLibraryAvailabilityCheck()


问:
jQuery slide in and out issue
Here is my URL site.

Here you can see a search bar on the top right corner. If you click on the search icon it will show you a search box. Now again, If you click on the search icon again then it's should close the search box like sliding effect but it's not working.

JQuery code:

```<code>jQuery(document).ready(function(){
  jQuery('#search2').on("click",(function(e){
    jQuery(".form-group").addClass("sb-search-open");
      e.stopPropagation()
    }));
    jQuery(document).on("click", function(e) {
      if (jQuery(e.target).is("#search2") === false && jQuery(".form-control").val().length == 0) {
        jQuery(".form-group").removeClass("sb-search-open");
      }
    });
    jQuery(".form-control-submit").click(function(e){
      jQuery(".form-control").each(function(){
      if(jQuery(".form-control").val().length == 0){
        e.preventDefault();
        jQuery(this).css('border', '2px solid red');
      }
    })
  })
})
</code>```

How can I fix it?

答:
Change the "addClass" in third line to "toggleClass":</p>

```<code>    jQuery(".form-group").toggleClass("sb-search-open");
</code>```

Title: jQuery slide in and out issue

Body:
Here is my URL site.

Here you can see a search bar on the top right corner. If you click on the search icon it will show you a search box. Now again, If you click on the search icon again then it's should close the search box like sliding effect but it's not working.

JQuery code:

jQuery(document).ready(function(){
  jQuery('#search2').on("click",(function(e){
    jQuery(".form-group").addClass("sb-search-open");
      e.stopPropagation()
    }));
    jQuery(document).on("click", function(e) {
      if (jQuery(e.target).is("#search2") === false && jQuery(".form-control").val().length == 0) {
        jQuery(".form-group").removeClass("sb-search-open");
      }
    });
    jQuery(".form-control-submit").click(function(e){
      jQuery(".form-control").each(function(){
      if(jQuery(".form-control").val().length == 0){
        e.preventDefault();
        jQuery(this).css('border', '2px solid red');
      }
    })
  })
})

How can I fix it?

Body:
Change the "addClass" in third line to "toggleClass":

    jQuery(".form-group").toggleClass("sb-search-open");


问:
Efficient way to define new variables by iterating a dictionary (Julia)
Consider a dictionary d in Julia which contains a thousand of keys. Each key is a symbol and each value is an array. I can access to the value associated with the symbol :S1 and assign it to the variable k1 via

k1 = d[:S1]

Now assume I want to define the new variables k2, k3, k4, ..., k10 by repeating the same procedure for the special keys :S1 ... :S10 (not for all the keys in the dictionary). What is the most efficient way to do it? I have the impression this can be solved using metaprogramming but not sure about that.

答:
If the special keys are all known at compile time, I suggest using Chris Rackauckas's answer
It is much less evil and works to create local variables.

If for some reason they are only known at runtime,
then you can do as follows.
(Though I guess it is actually pretty strange to need to create variables who's name you don't even know at compile time)

@eval is your friend* here. See the manual
@eval $key = $value

Or you can use the functional form eval() taking a quoted expression:
eval(:($key = $value))

Note however you can not use this to introduce new local variables.
eval always executes at module scope.
And that is a intentional restriction for performance reasons

```<code>julia> d = Dict(k => rand(3) for k in [:a, :b1, :c2, :c1])
Dict{Symbol,Array{Float64,1}} with 4 entries:
  :a  => [0.446723, 0.0853543, 0.476118]
  :b1 => [0.212369, 0.846363, 0.854601]
  :c1 => [0.542332, 0.885369, 0.635742]
  :c2 => [0.118641, 0.987508, 0.578754]

julia> for (k,v) in d
          #create constants for only ones starting with `c`
          if first(string(k)) == c
              @eval const $k = $v
          end
       end

julia> c2
3-element Array{Float64,1}:
  0.118641
  0.987508
  0.578754
</code>```

*Honestly eval is not your friend.
It is however the only dude badass enough to walk with you down this dark road of generating code based on runtime values. (@generate is only marginally less badass being willing to generate code based on runtime Types).
If you are in this situation where you absolutely have to generate code based on runtime information consider whether you have not made a design mistake several forks further up the road.

Body:
If the special keys are all known at compile time, I suggest using Chris Rackauckas's answer
It is much less evil and works to create local variables.

If for some reason they are only known at runtime,
then you can do as follows.
(Though I guess it is actually pretty strange to need to create variables who's name you don't even know at compile time)

@eval is your friend* here. See the manual
@eval $key = $value

Or you can use the functional form eval() taking a quoted expression:
eval(:($key = $value))

Note however you can not use this to introduce new local variables.
eval always executes at module scope.
And that is a intentional restriction for performance reasons

julia> d = Dict(k => rand(3) for k in [:a, :b1, :c2, :c1])
Dict{Symbol,Array{Float64,1}} with 4 entries:
  :a  => [0.446723, 0.0853543, 0.476118]
  :b1 => [0.212369, 0.846363, 0.854601]
  :c1 => [0.542332, 0.885369, 0.635742]
  :c2 => [0.118641, 0.987508, 0.578754]

julia> for (k,v) in d
          #create constants for only ones starting with `c`
          if first(string(k)) == c
              @eval const $k = $v
          end
       end

julia> c2
3-element Array{Float64,1}:
  0.118641
  0.987508
  0.578754

*Honestly eval is not your friend.
It is however the only dude badass enough to walk with you down this dark road of generating code based on runtime values. (@generate is only marginally less badass being willing to generate code based on runtime Types).
If you are in this situation where you absolutely have to generate code based on runtime information consider whether you have not made a design mistake several forks further up the road.


问:
Ansible: How to delete files and folders inside a directory?
The below code only deletes the first file it gets inside the web dir. I want to remove all the files and folders inside the web directory and retain the web directory. How can I do that?

- name: remove web dir contents
    file: path='/home/mydata/web/{{ item }}' state=absent
    with_fileglob:
      - /home/mydata/web/*
```

Note: I've tried rm -rf using command and shell, but they don't work. Perhaps I am using them wrongly.

Any help in the right direction will be appreciated.

I am using ansible 2.1.0.0

答:
There is an issue open with respect to this.

For now, the solution works for me: create a empty folder locally and synchronize it with the remote one.

Here is a sample playbook:

```<code>- name: "Empty directory"
  hosts: *
  tasks:
    - name: "Create an empty directory (locally)"
      local_action:
        module: file
        state: directory
        path: "/tmp/empty"

    - name: Empty remote directory
      synchronize:
        src: /tmp/empty/
        dest: /home/mydata/web/
        delete: yes
        recursive: yes
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The below code only deletes the first file it gets inside the web dir. I want to remove all the files and folders inside the web directory and retain the web directory. How can I do that?

- name: remove web dir contents
    file: path='/home/mydata/web/{{ item }}' state=absent
    with_fileglob:
      - /home/mydata/web/*

Note: I've tried rm -rf using command and shell, but they don't work. Perhaps I am using them wrongly.

Any help in the right direction will be appreciated.

I am using ansible 2.1.0.0

Body:
There is an issue open with respect to this.

For now, the solution works for me: create a empty folder locally and synchronize it with the remote one.

Here is a sample playbook:

- name: "Empty directory"
  hosts: *
  tasks:
    - name: "Create an empty directory (locally)"
      local_action:
        module: file
        state: directory
        path: "/tmp/empty"

    - name: Empty remote directory
      synchronize:
        src: /tmp/empty/
        dest: /home/mydata/web/
        delete: yes
        recursive: yes


问:
How to update main form when data from dialog is changed?
We have a main window (MainScreen.xhtml) and a dialog box (DialogScreen.xhtml) in 2 separate files.

In MainScreen.xhtml, there is a link that calls and opens DialogScreen.xhtml. Also, there is a field called fieldA. fieldA's value is updated depending on selected value from DialogScreen.

MainScreen.xhtml sample:

```<code><h:outputText value="#{bean.fieldA}" id="fieldA"/>
</code>```

DialogScreen.xhtml sample:

```<code><cf:autoComplete id="someId" autoCompleteList="#{someBean.listItems}">
   <p:ajax event="itemSelect" update="someId"/>
</cf:autoComplete>
<p:commandLink id="setFieldA" action="{someBean.someAction}" value="set fieldA"/>
</code>```

We tried the following but neither worked:
1. In DialogScreen.xhtml update commandLink:

```<code><p:commandLink id="setFieldA" action="{someBean.someAction}" value="set fieldA"/>
   <p:ajax event="itemSelect" update=":fieldA"/>
</p:commandLink>
</code>```

Update MainScreen data by updating contextrequest in MainScreenBean.java

RequestContext.getCurrentInstance().update(":fieldA");

Both of the above fix resulted in error that :fieldA component cannot be found.
How to update the main form data when the dialog box data is changed?

答:
I assume you have two form in two file. Make sure your dialog in DialogScreen.xhtml has appendTo="@(body)" this attribute set. It will append the html to the MainScreen.xhtml page.  if your MainScreen.xhtml has

```<code><h:form id='mainForm'>
   <h:outputText value="#{bean.fieldA}" id="fieldA"/>
</h:form>
</code>```

you can access update that field from DialogSceen.xhtml by

```<code>    <h:form id="dialogForm">
     <p:commandLink id="setFieldA" action="{someBean.someAction}" value="set
     fieldA"/>
       <p:ajax event="itemSelect" update=":mainForm:fieldA"/>
     </p:commandLink>
   </h:form>
</code>```

So that means you have to put :formId:componentId to address any component outside of the form.

Body:
We have a main window (MainScreen.xhtml) and a dialog box (DialogScreen.xhtml) in 2 separate files.

In MainScreen.xhtml, there is a link that calls and opens DialogScreen.xhtml. Also, there is a field called fieldA. fieldA's value is updated depending on selected value from DialogScreen.

MainScreen.xhtml sample:

<h:outputText value="#{bean.fieldA}" id="fieldA"/>

DialogScreen.xhtml sample:

<cf:autoComplete id="someId" autoCompleteList="#{someBean.listItems}">

</cf:autoComplete>

We tried the following but neither worked:
1. In DialogScreen.xhtml update commandLink:

Update MainScreen data by updating contextrequest in MainScreenBean.java

RequestContext.getCurrentInstance().update(":fieldA");

Both of the above fix resulted in error that :fieldA component cannot be found.
How to update the main form data when the dialog box data is changed?

Body:
I assume you have two form in two file. Make sure your dialog in DialogScreen.xhtml has appendTo="@(body)" this attribute set. It will append the html to the MainScreen.xhtml page.  if your MainScreen.xhtml has

<h:form id='mainForm'>
   <h:outputText value="#{bean.fieldA}" id="fieldA"/>
</h:form>

you can access update that field from DialogSceen.xhtml by

    <h:form id="dialogForm">
     <p:commandLink id="setFieldA" action="{someBean.someAction}" value="set
     fieldA"/>
       <p:ajax event="itemSelect" update=":mainForm:fieldA"/>
     </p:commandLink>
   </h:form>

So that means you have to put :formId:componentId to address any component outside of the form.


问:
MVC Populate input text with ViewBag
I have another problem wherein I have a method in controller that gets a certain data and place it to the view.

Controller

```<code>public ActionResult Index()
{
        var data = (from p in db.eTransactions
                    orderby p.id descending
                    select p.id).Take(1);
        ViewBag.id = data;
        return View();
}
</code>```

View

```<code><input type="text" value="@(ViewBag.id)"/>
</code>```

instead of the data(which is a certain value) I want to get, the data thrown is like a command in an sql server

```<code>SELECT TOP (1)     [Extent1].[id] AS [id]    FROM [dbo].[eTransaction] AS [Extent1]    ORDER BY [Extent1].[id] DESC
</code>```

What is needed to do to fix this?

答:
ok the thing that fixed it was adding FirstOrDefault() after the Take(1).</p>

```<code>public ActionResult Index()
{
    var data = (from p in db.eTransactions
                orderby p.id descending
                select p.id).Take(1).FirstOrDefault();
    ViewBag.id = data;
    return View();
}
</code>```

Title: MVC Populate input text with ViewBag

Body:
I have another problem wherein I have a method in controller that gets a certain data and place it to the view.

Controller

public ActionResult Index()
{
        var data = (from p in db.eTransactions
                    orderby p.id descending
                    select p.id).Take(1);
        ViewBag.id = data;
        return View();
}

View

<input type="text" value="@(ViewBag.id)"/>

instead of the data(which is a certain value) I want to get, the data thrown is like a command in an sql server

SELECT TOP (1)     [Extent1].[id] AS [id]    FROM [dbo].[eTransaction] AS [Extent1]    ORDER BY [Extent1].[id] DESC

What is needed to do to fix this?

Body:
ok the thing that fixed it was adding FirstOrDefault() after the Take(1).

public ActionResult Index()
{
    var data = (from p in db.eTransactions
                orderby p.id descending
                select p.id).Take(1).FirstOrDefault();
    ViewBag.id = data;
    return View();
}


问:
Can my output of Pandas dataframe be graphed?
```<code>import dash, matplotlib
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd

data = pd.read_excel('C:\\Users\\myuser\\Desktop\\Pandas\\$$$$.xlsx')
data2 = data.groupby(['Department']).count()
print data2
</code>```

prints out exactly the information i need, however can i plot this?

C:\Users\dbeiler\Desktop\Pandas>python PythonApplication1.py

```<code>        Email  Completion

Department

dep1         165          62

dep2         147          68

dep3          37           8
</code>```

ideally i'd like to use plotly if convenient https://plot.ly/products/dash/

答:
Yes, you can build plot from your pandas dataframe. Folow instructions from guide : https://plot.ly/dash/getting-started

Simpliest way to build plot is:

```<code>    html.Div(
        dcc.Graph(
                id='mapbox',
                figure={
                    'data': [go.Bar(
                            x = data ['PutXcolumnNameHere'],
                            y = data ['PutYcolumnNameHere'],
                            )
                    ],
                    'layout': go.Layout(
                        legend={'x': 0, 'y': 1},
                        hovermode='closest'
                    )
                }
        )
    )
</code>```

Body:
import dash, matplotlib
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd

data = pd.read_excel('C:\\Users\\myuser\\Desktop\\Pandas\\$$$$.xlsx')
data2 = data.groupby(['Department']).count()
print data2

prints out exactly the information i need, however can i plot this?

C:\Users\dbeiler\Desktop\Pandas>python PythonApplication1.py

        Email  Completion

Department

dep1         165          62

dep2         147          68

dep3          37           8

ideally i'd like to use plotly if convenient https://plot.ly/products/dash/

Body:
Yes, you can build plot from your pandas dataframe. Folow instructions from guide : https://plot.ly/dash/getting-started

Simpliest way to build plot is:

    html.Div(
        dcc.Graph(
                id='mapbox',
                figure={
                    'data': [go.Bar(
                            x = data ['PutXcolumnNameHere'],
                            y = data ['PutYcolumnNameHere'],
                            )
                    ],
                    'layout': go.Layout(
                        legend={'x': 0, 'y': 1},
                        hovermode='closest'
                    )
                }
        )
    )


问:
Memory requirements for FFT on STM32F103C8
I have a limited system and would like to implement FFT within STM32F103C8 without any extra memory buffers.

So I want to know how many memories are needed to implement if I have 2592x1944x8bit size's one image?

Actually, I want to have a process such as

Origial image ---> FFT ---> Blur ---> IFFT ---> Modified image

What is the memory requirements for FFT on STM32F103C8 ?

答:
So I want to know how many memories are needed to implement if I have 2592x1944x8bit size's one image?

Much more than you have. This isn't going to work out.

2592x1944 @ 8bpp is roughly 5 MB. Your microcontroller has 20 KB of RAM, which isn't even enough to store eight lines of your image.


问:
database datatype performance: int or string
I'm storing phone country codes. They range from 1 to about 300. What's going to be more performant for datatype: int or string? I'm using SQL server 2008 and linq-to-sql.

Thanks.

答:
Note: Whoa, really wierd - you asked about phone codes and I wrote about ZIP codes.  Sorry about that!  I think the advice still stands though...

Original answer: Performance will most likely be negligible - assign the proper type based on what the data is.  ZIP codes, while numeric (in the US at least), aren't numbers - they should be stored as strings.

It is very important to understand the semantic nature of the data you are storing.  Once you understand what something is then you can begin to reason about how it should be stored.  I am assuming that currently you are storing only the first 5 numbers of a US postal code (like this: 12345).

If you were to store this data as a number this would work.  Then imagine that your manager tells you that there is a new requirement that the app you are building will start to collect ZIP codes in the ZIP+4 format (which looks like this: 12345-6789).  Now you are stuck with a nasty refactoring that involves either changing the type in the database to varchar(10) or doing some crazy voodoo in your app to strip out the dash when you save the ZIP code and then add it back in for display later.

ContentLicense: CC BY-SA 2.5


问:
How can I get rid of the text next to the navigation back button in Swift?
How can I get rid of the text and just have the back arrow show up for ALL view controllers that show up on the navigation stack.

I already know that this code will work to remove the text on a single view controller:

```<code>let item = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
self.navigationItem.backBarButtonItem = item
</code>```

However, I am looking for a solution where I don't have to copy and paste code into each individual view controller.

I am already subclassing every single navigation controller in my app to the same class, so I'm trying to find a solution I can write once in this UINavigationController subclass that will cause all children view controllers that might show up on the stack to show only the back arrow with no text.

答:
In your case better option is to select the navigation item of your controller and add space in the back button option. See below image for reference :

You don't have to write any code in this scenario.

Body:
How can I get rid of the text and just have the back arrow show up for ALL view controllers that show up on the navigation stack.

I already know that this code will work to remove the text on a single view controller:

let item = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
self.navigationItem.backBarButtonItem = item

However, I am looking for a solution where I don't have to copy and paste code into each individual view controller.

I am already subclassing every single navigation controller in my app to the same class, so I'm trying to find a solution I can write once in this UINavigationController subclass that will cause all children view controllers that might show up on the stack to show only the back arrow with no text.


问:
In Internet Explorer not able to convert UTC date to local date
Here is date that I received from Backend "2017-05-23T18:30:00",

This works fine in Chrome:

Call:  new Date('2017-05-23T18:30:00').toString()

Result: "Wed May 24 2017 00:00:00 GMT+0530 (India Standard Time)"

But on the Internet Explorer:

Call: new Date('2017-05-23T18:30:00').toString()

Result: "Tue May 23 2017 18:30:00 GMT+0530 (India Standard Time)",

What to do get local date time from UTC date in Internet Explorer as I am getting in Chrome?

答:
IE browser will take in the format of 'mm-dd-yy'. if you give in the format of 'yy-mm-dd' it results Invalid Date.

use following function to convert UTC to LocalDate.

```<code>function convertUTCDateToLocalDate(utcDate) {
    var formattedDate = utcDate.getMonth()+'-'+utcDate.getDate()+'-'+utcDate.getFullYear();
    var hours = utcDate.getHours();
        var minutes = utcDate.getMinutes();
        var seconds = utcDate.getSeconds()
        var newDate = new Date(formattedDate + ' ' + hours + ':' + minutes+":"+seconds+" UTC");
    return newDate;
}
var localDate = convertUTCDateToLocalDate(yourUTCDate);
</code>```

Body:
IE browser will take in the format of 'mm-dd-yy'. if you give in the format of 'yy-mm-dd' it results Invalid Date.

use following function to convert UTC to LocalDate.

function convertUTCDateToLocalDate(utcDate) {
    var formattedDate = utcDate.getMonth()+'-'+utcDate.getDate()+'-'+utcDate.getFullYear();
    var hours = utcDate.getHours();
        var minutes = utcDate.getMinutes();
        var seconds = utcDate.getSeconds()
        var newDate = new Date(formattedDate + ' ' + hours + ':' + minutes+":"+seconds+" UTC");
    return newDate;
}
var localDate = convertUTCDateToLocalDate(yourUTCDate);


答:
Try this code.</p>

```<code>jQuery(document).ready(function(){
  jQuery('#search2').on("click",(function(e){
    jQuery("#search").toggleClass("sb-search-open");
      e.stopPropagation()
    }));

});
</code>```

Title: jQuery slide in and out issue

Body:
Try this code.

jQuery(document).ready(function(){
  jQuery('#search2').on("click",(function(e){
    jQuery("#search").toggleClass("sb-search-open");
      e.stopPropagation()
    }));

});


问:
I need to set up eclipse with flex plugin
I want to work with flex from eclipse, could you tell me how to install the flex plugin within eclipse:

What version of eclipse do I need?

Where can I download the flex plugin?

Thanks in advance.

答:
I have not tried Flex with Eclipse, I know for sure you can work with NetBeans IDE using FlexBean plugin. You can find the Eclipse/Flex plugin details below.

http://www.darronschall.com/weblog/2005/08/setting-up-eclipse-for-flex.cfm

Hope this helps.


问:
Mapping real-world coordinate to OpenGL coordinate system
I'm currently trying to implement an AR-browser based on indoor maps, but I'm facing several problems, let's take a look at the figure:

In this figure, I've already changed the coordinate to OpenGL's right-handed coordinate system.

In our real-world scenario,

given the angle FOV/2 and the camera height h then I can get nearest visible point P(0,0,-n).

Given the angle B and the camera height h then I can get a point  Q(0,0,-m) between nearest visible point and longest visible point.

Here comes a problem: when I finished setup my vertices(including P and Q) and use the method Matrix.setLookAtM like

```<code>Matrix.setLookAtM(modelMatrix, 0, 0f,h,0f,0f,-2000f,0f,0f,1f,0f);
</code>```

the aspect ratio is incorrect.
If the camera height h is set to 0.92 and FOV is set to 68 degrees, n should be 1.43, But in OpenGL the coordinate of the nearest point is not (0,0,-1.43f). So I'm wondering how to fix this problem, how to map real-world coordinate to OpenGL's coordinate system?

答:
In a rendering, each mesh of the scene usually is transformed by the model matrix, the view matrix and the projection matrix.

Model matrix:

The model matrix defines the location, oriantation and the relative size of a mesh in the scene. The model matrix transforms the vertex positions of the mesh to the world space.

View matrix:

The view matrix describes the direction and position from which the scene is looked at. The view matrix transforms from the wolrd space to the view (eye) space. In the coordinat system on the viewport, the X-axis points to the left, the Y-axis up and the Z-axis out of the view (Note in a right hand system the Z-Axis is the cross product of the X-Axis and the Y-Axis).

The view matrix can be set up by Matrix.setLookAtM

Projection matrix:

The projection matrix describes the mapping from 3D points of a scene, to 2D points of the viewport. The projection matrix transforms from view space to the clip space, and the coordinates in the clip space are transformed to the normalized device coordinates (NDC) in the range (-1, -1, -1) to (1, 1, 1) by dividing with the w component of the clip coordinates.
At Perspective Projection the projection matrix describes the mapping from 3D points in the world as they are seen from of a pinhole camera, to 2D points of the viewport.
 The eye space coordinates in the camera frustum (a truncated pyramid) are mapped to a cube (the normalized device coordinates).

The perspective projection matrix can be set up by Matrix.perspectiveM

You can set up a separate view matrix and a separate projection matrix and finally multiply them. The aspect ratio and the field of view are parameters to [Matrix.perspectiveM]:

```<code>Matrix viewM = new Matrix();
Matrix.setLookAtM(viewM, 0, 0, 0, 0f, 0f,-2000f, 0f, 0f, 1.0f, 0.0f);

Matrix prjM = new Matrix();
Matrix.perspectiveM(prjM, 0, fovy, aspect, zNear, zFar);

Matrix viewPrjM = new Matrix();
Matrix.multiplyMM(viewPrjM, 0, prjM, 0, viewM, 0);
</code>```

Body:
I'm currently trying to implement an AR-browser based on indoor maps, but I'm facing several problems, let's take a look at the figure:

In this figure, I've already changed the coordinate to OpenGL's right-handed coordinate system.

In our real-world scenario,

given the angle FOV/2 and the camera height h then I can get nearest visible point P(0,0,-n).

Given the angle B and the camera height h then I can get a point  Q(0,0,-m) between nearest visible point and longest visible point.

Here comes a problem: when I finished setup my vertices(including P and Q) and use the method Matrix.setLookAtM like

Matrix.setLookAtM(modelMatrix, 0, 0f,h,0f,0f,-2000f,0f,0f,1f,0f);

the aspect ratio is incorrect.
If the camera height h is set to 0.92 and FOV is set to 68 degrees, n should be 1.43, But in OpenGL the coordinate of the nearest point is not (0,0,-1.43f). So I'm wondering how to fix this problem, how to map real-world coordinate to OpenGL's coordinate system?

Body:
In a rendering, each mesh of the scene usually is transformed by the model matrix, the view matrix and the projection matrix.

Model matrix:

The model matrix defines the location, oriantation and the relative size of a mesh in the scene. The model matrix transforms the vertex positions of the mesh to the world space.

View matrix:

The view matrix describes the direction and position from which the scene is looked at. The view matrix transforms from the wolrd space to the view (eye) space. In the coordinat system on the viewport, the X-axis points to the left, the Y-axis up and the Z-axis out of the view (Note in a right hand system the Z-Axis is the cross product of the X-Axis and the Y-Axis).

The view matrix can be set up by Matrix.setLookAtM

Projection matrix:

The projection matrix describes the mapping from 3D points of a scene, to 2D points of the viewport. The projection matrix transforms from view space to the clip space, and the coordinates in the clip space are transformed to the normalized device coordinates (NDC) in the range (-1, -1, -1) to (1, 1, 1) by dividing with the w component of the clip coordinates.
At Perspective Projection the projection matrix describes the mapping from 3D points in the world as they are seen from of a pinhole camera, to 2D points of the viewport.
 The eye space coordinates in the camera frustum (a truncated pyramid) are mapped to a cube (the normalized device coordinates).

The perspective projection matrix can be set up by Matrix.perspectiveM

You can set up a separate view matrix and a separate projection matrix and finally multiply them. The aspect ratio and the field of view are parameters to [Matrix.perspectiveM]:

Matrix viewM = new Matrix();
Matrix.setLookAtM(viewM, 0, 0, 0, 0f, 0f,-2000f, 0f, 0f, 1.0f, 0.0f);

Matrix prjM = new Matrix();
Matrix.perspectiveM(prjM, 0, fovy, aspect, zNear, zFar);

Matrix viewPrjM = new Matrix();
Matrix.multiplyMM(viewPrjM, 0, prjM, 0, viewM, 0);


问:
html video not working in apple devices
I have html video tag on my page it works fine in all desktop browsers, and in android devices but its not even showing in apple devices.</p>

```<code><div class="item video ">
  <video loop preload="auto">
    <source src="./video/video1.mp4" type="video/mp4">
    <source src="./video/webm/video1.webm" type="video/webm">
  </video>
</div>
</code>```

答:
Web video does not play automatically on mobile devices because of bandwidth considerations.

https://www.aerserv.com/why-does-video-autoplay-on-mobile-devices-not-work/

Title: html video not working in apple devices

Body:
I have html video tag on my page it works fine in all desktop browsers, and in android devices but its not even showing in apple devices.

  <video loop preload="auto">
    <source src="./video/video1.mp4" type="video/mp4">
    <source src="./video/webm/video1.webm" type="video/webm">
  </video>


问:
Batch script to extract part of a string
I need a batch script that will read in another batch script (batch2) and:

look for the string "configout:" OR "configin:"

If it encounters one of these two strings, extract what's after it until the string ".xml"

copy paste it in a new text file.

and do this for each line of batch2.

For exemple:
If this is my first line in the batch script

```<code>/configin:%faxml%fm_sellin_in.xml /configout:%faxml%transco_fm_sellin_out%col_transco%.xml /inputfile:
</code>```

I should have this in my text file:

```<code>%faxml%fa_sellin_in.xml
%faxml%transco_fm_sellin_out%col_transco%.xml
</code>```

I have seen a good code in Here:

```<code>for /f "tokens=1-2 delims=~" %%b in ("yourfile.txt") do (
  echo %%b >> newfile.txt
  echo removed %%a)
</code>```

but i don't know how to adapt it to my specific case.

答:
Why not replace all the /configin and /configout with newlines? -

(Replace string with a new line in Batch)

For example

```<code>setlocal EnableDelayedExpansion

set "str=/configin:%%faxml%%fm_sellin_in.xml /configout:%%faxml%%transco_fm_sellin_out%%col_transco%%.xml /inputfile:"

set str=!str:/configin^:=^

!
set str=!str:/configout^:=^

!
</code>```

Now, !str! would contain

```<code>fm_sellin_in.xml
transco_fm_sellin_out.xml /inputfile:
</code>```

Then, you could use the for loop to extract the strings

```<code>for /f "tokens=1,2 delims=. " %%a in ("!str!") do ()
</code>```

this for loop iterates through each line and splits each line with the  and . characters.

So %%a is your file name and %%b is the extension.

then

```<code>if [%%b]==[xml] (echo %%a.%%b>>mytextfile.txt)
</code>```

We will do this for all the lines of batch2.

And the finished code is

```<code>setlocal EnableDelayedExpansion

for /f "delims=" %%c in (batch2.txt) do (
set str=%%c
set str=!str:/configin^:=^

!
set str=!str:/configout^:=^

!
for /f "tokens=1,2 delims=. " %%a in ("!str!") do (if [%%b]==[xml] (echo %%a.%%b>>mytextfile.txt))
)
</code>```

Body:
I need a batch script that will read in another batch script (batch2) and:

look for the string "configout:" OR "configin:"

If it encounters one of these two strings, extract what's after it until the string ".xml"

copy paste it in a new text file.

and do this for each line of batch2.

For exemple:
If this is my first line in the batch script

/configin:%faxml%fm_sellin_in.xml /configout:%faxml%transco_fm_sellin_out%col_transco%.xml /inputfile:

I should have this in my text file:

%faxml%fa_sellin_in.xml
%faxml%transco_fm_sellin_out%col_transco%.xml

I have seen a good code in Here:

for /f "tokens=1-2 delims=~" %%b in ("yourfile.txt") do (
  echo %%b >> newfile.txt
  echo removed %%a)

but i don't know how to adapt it to my specific case.

Body:
Why not replace all the /configin and /configout with newlines? -

(Replace string with a new line in Batch)

For example

setlocal EnableDelayedExpansion

set "str=/configin:%%faxml%%fm_sellin_in.xml /configout:%%faxml%%transco_fm_sellin_out%%col_transco%%.xml /inputfile:"

set str=!str:/configin^:=^

!
set str=!str:/configout^:=^

!

Now, !str! would contain

fm_sellin_in.xml
transco_fm_sellin_out.xml /inputfile:

Then, you could use the for loop to extract the strings

for /f "tokens=1,2 delims=. " %%a in ("!str!") do ()

this for loop iterates through each line and splits each line with the  and . characters.

So %%a is your file name and %%b is the extension.

then

if [%%b]==[xml] (echo %%a.%%b>>mytextfile.txt)

We will do this for all the lines of batch2.

And the finished code is

setlocal EnableDelayedExpansion

for /f "delims=" %%c in (batch2.txt) do (
set str=%%c
set str=!str:/configin^:=^

!
set str=!str:/configout^:=^

!
for /f "tokens=1,2 delims=. " %%a in ("!str!") do (if [%%b]==[xml] (echo %%a.%%b>>mytextfile.txt))
)


问:
C++ Creating Binary Search Tree: EXC_BAD_ACCESS error. Bad Algorithm or coding error?

Question: I keep receiving exc_bad_access (process code 11) error. Is this due to a bad algorithm or simply a coding error? Can anyone help me fix it?

My class assignment is to create a binary search tree whose nodes can store a name, a balance, and a key. Nodes are to be organized and searched for using the key. This tree should support insertion, inorder traversal, and searching based on a key (I haven't built this function yet). I've also included several other functions to facilitate building these. If it matters, I'm using CLion on OSX High Sierra. Additionally, I get the error on the first prompt to enter node information, the error does not seem to be related to the input itself.

```<code>//Genghis Khan
#include <iostream>
#include <vector>
using namespace std;
class node
{
public:
    int key;
    string name;
    double balance;
    node *leftptr;
    node *rightptr;
    friend class tree;
};
class tree
{
public:
    node *root, *temp, *v;

    //Constructor
    tree()
    {
        root = NULL;
        temp = root;
    }

    bool empty()
    {
        return(root == NULL);
    }

    bool isleaf(node *x)
    {
        return((x->leftptr == NULL) && (x->rightptr == NULL));
    }

    void inorder(node *temp)
    {
        if(~isleaf(temp))
        {
            inorder(temp->leftptr);
            cout << "Name: " << temp->name << " " << "Balance: " <<
    temp->balance << " " << "Key: " << temp->key;
            inorder(temp->rightptr);
        }
    }

    node* createnode()
    {
        v = new node;
        cout << "Enter name (string): " << endl;
        getline(cin, v->name);
        cout << "Enter key (integer): " << endl;
        cin >> v->key;
        cout << "Enter balance (double): " << endl;
        cin >> v->balance;
        return(v);
    }

    void set()
    {
        temp = root;
    }

    void insert(node *v)
    {
        while(~isleaf(temp))
        {
            if((v->key < temp->key))
            {
                temp = temp->leftptr;
                insert(v);
            }
            else if(v->key > temp->key)
            {
                temp = temp->rightptr;
                insert(v);
            }
        }
    temp->key = v->key;
    temp->balance = v->balance;
    temp->name = v->name;
    }

};

int main()
{
    int n;
    cout << "Enter number of people: ";
    cin >> n;

    //Creating instance of tree, inserting all data into tree
    tree b;
    for(int i = 0; i < n; i++)
    {
        b.set();
        node *a = b.createnode();
        b.insert(a);
    }

    //inorder part
    b.set();
    b.inorder(b.temp);

}
</code>```

The functions are (pseudocode):

```<code>1. function isleaf(x): return(x's left pointer and x's right pointer are both NULL)

2. function set(): set temp to root //temp will be reset every time an insertion, traversal, or search occurs

3. function createnode():

   v is  a new node

   get all the fields for v

   return v

4. function insert(v)

   while(not isleaf(temp)):
   -if(v's key < temp's key)
  temp = temp's left pointer (to the lower value child node)
  insert(node *v)

   -if(v's key > temp's key)
  temp = temp's right pointer (to the higher value child node)
  insert(node *v)
  end while
  duplicate v's data to temp, now that temp is a leaf

5. function inorder(temp):
   if(not isleaf(temp):
   inorder(temp's left pointer)
   output all info in temp node
   inorder(temp's right pointer)
</code>```

Main Algorithm

for the number of nodes to be entered:

 1. set

 2. node *a = createnode

 3. insert(a)

Update

The error seems to be coming from the 'if((v->key < temp->key))' line.

答:
EXC_BAD_ACCESS just means that you are trying to access an invalid memory. By a quick brief,  your function isleaf doesn't check whether x is null.

May have other errors, you can debug and find it by yourself.

Body:
Question: I keep receiving exc_bad_access (process code 11) error. Is this due to a bad algorithm or simply a coding error? Can anyone help me fix it?

My class assignment is to create a binary search tree whose nodes can store a name, a balance, and a key. Nodes are to be organized and searched for using the key. This tree should support insertion, inorder traversal, and searching based on a key (I haven't built this function yet). I've also included several other functions to facilitate building these. If it matters, I'm using CLion on OSX High Sierra. Additionally, I get the error on the first prompt to enter node information, the error does not seem to be related to the input itself.

//Genghis Khan
#include <iostream>
#include <vector>
using namespace std;
class node
{
public:
    int key;
    string name;
    double balance;
    node *leftptr;
    node *rightptr;
    friend class tree;
};
class tree
{
public:
    node *root, *temp, *v;

    //Constructor
    tree()
    {
        root = NULL;
        temp = root;
    }

    bool empty()
    {
        return(root == NULL);
    }

    bool isleaf(node *x)
    {
        return((x->leftptr == NULL) && (x->rightptr == NULL));
    }

    void inorder(node *temp)
    {
        if(~isleaf(temp))
        {
            inorder(temp->leftptr);
            cout << "Name: " << temp->name << " " << "Balance: " <<
    temp->balance << " " << "Key: " << temp->key;
            inorder(temp->rightptr);
        }
    }

    node* createnode()
    {
        v = new node;
        cout << "Enter name (string): " << endl;
        getline(cin, v->name);
        cout << "Enter key (integer): " << endl;
        cin >> v->key;
        cout << "Enter balance (double): " << endl;
        cin >> v->balance;
        return(v);
    }

    void set()
    {
        temp = root;
    }

    void insert(node *v)
    {
        while(~isleaf(temp))
        {
            if((v->key < temp->key))
            {
                temp = temp->leftptr;
                insert(v);
            }
            else if(v->key > temp->key)
            {
                temp = temp->rightptr;
                insert(v);
            }
        }
    temp->key = v->key;
    temp->balance = v->balance;
    temp->name = v->name;
    }

};

int main()
{
    int n;
    cout << "Enter number of people: ";
    cin >> n;

    //Creating instance of tree, inserting all data into tree
    tree b;
    for(int i = 0; i < n; i++)
    {
        b.set();
        node *a = b.createnode();
        b.insert(a);
    }

    //inorder part
    b.set();
    b.inorder(b.temp);

}

The functions are (pseudocode):

1. function isleaf(x): return(x's left pointer and x's right pointer are both NULL)

2. function set(): set temp to root //temp will be reset every time an insertion, traversal, or search occurs

3. function createnode():

   v is  a new node

   get all the fields for v

   return v

4. function insert(v)

   while(not isleaf(temp)):
   -if(v's key < temp's key)
  temp = temp's left pointer (to the lower value child node)
  insert(node *v)

   -if(v's key > temp's key)
  temp = temp's right pointer (to the higher value child node)
  insert(node *v)
  end while
  duplicate v's data to temp, now that temp is a leaf

5. function inorder(temp):
   if(not isleaf(temp):
   inorder(temp's left pointer)
   output all info in temp node
   inorder(temp's right pointer)

Main Algorithm

for the number of nodes to be entered:

 1. set

 2. node *a = createnode

 3. insert(a)

Update

The error seems to be coming from the 'if((v->key < temp->key))' line.


问:
Disable/Enable a textbox in bootstrap modal form based on radio button click
I have a bootsrap modal form.In that if i click on the radio button,'For All Subjects','Subject' textbox should be in disabled state.Similarly,if I click on radio button 'Specific Subject', 'Subject' textbox should be enabled.

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

        <button type="button" class="btn  btn-lg"
         data-toggle="modal" data-target="#addMasterData" >Add Master</button>

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

          Add Master

        <form id="mastercreate" action="addConfig" method="post">

          Subjects:
           <input type="radio" name="roleSubjectRadio" id="forAllSubjects"
           value="Yes"  >For All Subjects
            <input type="radio"
           name="roleSubjectRadio" id="specificFlights"
         value="Specific"  checked>Specific Subject
           <input type="hidden" class="form-control" id="specs" name="specs"
           value="">

            Subject
             Name: <input type="text" class="form-control" id="subNo"
             name="subNo" >

          <button type="button" class="btn btn-primary"
           onclick="addMaster()">Submit</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        </form>

```

Please suggest how to do it from javascript.

答:
you should add a click function depends on your library
lets get from a point you don`t use any library

you should do this : (you can copy past and it will work)

```<code><head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
</head>
<div class="container" id="adminContent">
        <div class="row">
            <div class="col s12 m12 l12" style="float: right">
                <button type="button" class="btn  btn-lg"
                    data-toggle="modal" data-target="#addMasterData" >Add Master</button>
            </div>
        </div>  </div>

    <div  id="addMasterData"
        role="dialog" style="width: 500px"; role="dialog"
        data-backdrop="static" data-keyboard="false">

        <div class="modal-dialog ">

            <div class="modal-content ">
                <div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            <h4 class="modal-title">
                        <b><font class="font">Add Master</font></b>
                    </h4>

                </div>
                <form id="mastercreate" action="addConfig" method="post">

                    <div class="modal-content ">

                        <div class="modal-body ">

                    <div class="form-group">
                        <label for="text">Subjects:</label> <label class="radio-inline">
                            <input type="radio" name="roleSubjectRadio" id="forAllSubjects"
                            value="true" onclick="radioClicked(this.id)"  >For All Subjects
                        </label>
                        <label class="radio-inline">
                        <input type="radio"
                            name="roleSubjectRadio" id="specificFlights"
                    value="Specific" onclick="radioClicked(this.id)"  checked>
                    Specific Subject
                        </label> <input type="hidden" class="form-control" id="specs" name="specs"
                            value="">
                    </div>
                    <div class="form-group" id="subName">
                                <label for="createorigin" class="form-control-label"><font >Subject
                                    Name:</font></label> <input type="text" class="form-control" id="subNo"
                                    name="subNo" >
                            </div>
                        <div class="modal-footer">
                        <button type="button" class="btn btn-primary"
                            onclick="addMaster()">Submit</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                    </div>
                    </div>
                </form>
            </div>

        </div>
    </div>

    <script>
        function radioClicked (me){
        //specificFlights
        //forAllSubjects

            if(me === "forAllSubjects" && document.getElementById("subNo").classList.contains('disabled') === false){
                document.getElementById("subNo").setAttribute("disabled",'disabled');
            }else{
                document.getElementById("subNo").removeAttribute("disabled",'disabled');
            }
        }

    </script>
</code>```

Body:
I have a bootsrap modal form.In that if i click on the radio button,'For All Subjects','Subject' textbox should be in disabled state.Similarly,if I click on radio button 'Specific Subject', 'Subject' textbox should be enabled.

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

        <button type="button" class="btn  btn-lg"
         data-toggle="modal" data-target="#addMasterData" >Add Master</button>

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

          Add Master

        <form id="mastercreate" action="addConfig" method="post">

          Subjects:
           <input type="radio" name="roleSubjectRadio" id="forAllSubjects"
           value="Yes"  >For All Subjects
            <input type="radio"
           name="roleSubjectRadio" id="specificFlights"
         value="Specific"  checked>Specific Subject
           <input type="hidden" class="form-control" id="specs" name="specs"
           value="">

            Subject
             Name: <input type="text" class="form-control" id="subNo"
             name="subNo" >

          <button type="button" class="btn btn-primary"
           onclick="addMaster()">Submit</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        </form>

Please suggest how to do it from javascript.

Body:
you should add a click function depends on your library
lets get from a point you don`t use any library

you should do this : (you can copy past and it will work)

<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
</head>
<div class="container" id="adminContent">
        <div class="row">
            <div class="col s12 m12 l12" style="float: right">
                <button type="button" class="btn  btn-lg"
                    data-toggle="modal" data-target="#addMasterData" >Add Master</button>
            </div>
        </div>  </div>

    <div  id="addMasterData"
        role="dialog" style="width: 500px"; role="dialog"
        data-backdrop="static" data-keyboard="false">

        <div class="modal-dialog ">

            <div class="modal-content ">
                <div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">
                        <b><font class="font">Add Master</font></b>
                    </h4>

                </div>
                <form id="mastercreate" action="addConfig" method="post">

                    <div class="modal-content ">

                        <div class="modal-body ">

                    <div class="form-group">
                        <label for="text">Subjects:</label> <label class="radio-inline">
                            <input type="radio" name="roleSubjectRadio" id="forAllSubjects"
                            value="true" onclick="radioClicked(this.id)"  >For All Subjects
                        </label>
                        <label class="radio-inline">
                        <input type="radio"
                            name="roleSubjectRadio" id="specificFlights"
                    value="Specific" onclick="radioClicked(this.id)"  checked>
                    Specific Subject
                        </label> <input type="hidden" class="form-control" id="specs" name="specs"
                            value="">
                    </div>
                    <div class="form-group" id="subName">
                                <label for="createorigin" class="form-control-label"><font >Subject
                                    Name:</font></label> <input type="text" class="form-control" id="subNo"
                                    name="subNo" >
                            </div>
                        <div class="modal-footer">
                        <button type="button" class="btn btn-primary"
                            onclick="addMaster()">Submit</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                    </div>
                    </div>
                </form>
            </div>

        </div>
    </div>

    <script>
        function radioClicked (me){
        //specificFlights
        //forAllSubjects

            if(me === "forAllSubjects" && document.getElementById("subNo").classList.contains('disabled') === false){
                document.getElementById("subNo").setAttribute("disabled",'disabled');
            }else{
                document.getElementById("subNo").removeAttribute("disabled",'disabled');
            }
        }

    </script>


问:
Dividing microservices in Lagom
Lagom by default creates two modules for every microservice - API and implementation.

Is it possible to divide one microservices into 3+ modules?

答:
Absolutely. You would do this the same way you would with any other Java or Scala project: create a sub-project that is an internal library included into your service.

For an example of this look at the Online Auction Java example Lagom project. Specifically, the security and tools sub-projects. These are included into other services using the sbt dependsOn method in build.sbt.

For example:

```<code>lazy val itemApi = (project in file("item-api"))
  .settings(commonSettings: _*)
  .settings(
    version := "1.0-SNAPSHOT",
    libraryDependencies ++= Seq(
      lagomJavadslApi,
      lombok
    )
  )
  .dependsOn(security, tools)
</code>```

In this case, it is the API project that depends on the additional libraries, but you could do the same thing with your implementation project to use libraries that are not needed by the API. Note that the implementation project also depends on its corresponding API, so any dependencies of the API are inherited by the implementation.

Title: Dividing microservices in Lagom

Body:
Absolutely. You would do this the same way you would with any other Java or Scala project: create a sub-project that is an internal library included into your service.

For an example of this look at the Online Auction Java example Lagom project. Specifically, the security and tools sub-projects. These are included into other services using the sbt dependsOn method in build.sbt.

For example:

lazy val itemApi = (project in file("item-api"))
  .settings(commonSettings: _*)
  .settings(
    version := "1.0-SNAPSHOT",
    libraryDependencies ++= Seq(
      lagomJavadslApi,
      lombok
    )
  )
  .dependsOn(security, tools)

In this case, it is the API project that depends on the additional libraries, but you could do the same thing with your implementation project to use libraries that are not needed by the API. Note that the implementation project also depends on its corresponding API, so any dependencies of the API are inherited by the implementation.


问:
How to calculate a path around a moving Object
I wrote a little game-engine, featuring a tile-based map and the A* algorithm for pathfinding. But I have a problem, when 2 objects collide and block a waypoint. They are coming from opposite directions, so they can't move anymore and will never reach their next waypoint.
I thought of some possible solutions like

movable objects cannot collide with other movable objects

recalculate the path flagging the blocked tiles

just calculate the path to the next free waypoint, flagging every tile with movable objects as blocked

I really don't want to do the first possibility, thats a little bit shabby for a not action-game like engine. The last two possibilities could get very slow if there are much movable objects on the map.
What do you think should I do? By the way, the first possibility is implemented in "Stronghold", the other two can be found in any newer strategy game.

答:
There's no single correct answer of course, but I can share what I've done with a similar problem:

I agree that passing through looks old school at this point. However, if your objects are smaller than your navigation mesh, you can do collision avoidance with bounding boxes without actually invalidating the path. Make collision avoidance small and local relative to the larger path.

If that doesn't work for your game, adding blocks is usually the best way. If you are concerned about the cost of pathfinding, you can wait until there is a collision, temporary add "blocks", and re-path. Another approach is to just periodically insert blocks and re-path. This can give natural looking paths and avoids the "run into each other before moving" which can look odd.

The cost depends a lot on your A* algorithm. If the algorithm doesn't cache results, then the blocks don't have incremental cost, and you can run A* as often as makes sense. For example: run A* once a frame and keep a queue of A* tasks.

If your algorithm does cache results, try to group A* computation so that you do multiple solves before moving the blocks around.


问:
How to remove border right form last child div?

How do i remove border right form the last div?

.process {
  border-right: 1px solid #e0e0e0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="job-posting">
  <div class="row">
    <div class="col-md-4">
      <div class="process">
        <header>STEP 1</header>
        <div class="process-content">
          <i class="fa fa-user-plus icon" aria-hidden="true"></i>
          <h1>Signup</h1>
          <p>Sign Up as a Company or an Individual</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 2</header>
        <div class="process-content">
          <i class="fa fa-upload icon" aria-hidden="true"></i>
          <h1>Upload Resume</h1>
          <p>Upload your resume and provide us with details of you experience and skills</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 3</header>
        <div class="process-content">
          <i class="fa fa-smile-o icon" aria-hidden="true"></i>
          <h1>Get Hired</h1>
          <p>Browse the available job postings and get hired according to your skills</p>
        </div>
      </div>
    </div>
  </div>
</div></code>```

I'm having trouble removing the right border form the last div I tried using the :last-child:border:remove;

答:
```<code>.process:not(:last-child){
    border-right: 1px solid #e0e0e0;
}
</code>```

Apply style to all elements except last child.

Body:
How do i remove border right form the last div?

.process {
  border-right: 1px solid #e0e0e0;
}

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

        STEP 1

Signup

Sign Up as a Company or an Individual

        STEP 2

Upload Resume

Upload your resume and provide us with details of you experience and skills

        STEP 3

Get Hired

Browse the available job postings and get hired according to your skills

I'm having trouble removing the right border form the last div I tried using the :last-child:border:remove;

Body:
.process:not(:last-child){
    border-right: 1px solid #e0e0e0;
}

Apply style to all elements except last child.


问:
how to create multiple foreach with one save?
I create multiple foreach in the controller function framework yii and create one storage, but the data stored only the last foreach data, how the solution  master?

```<code>$arrItems = array();
$data = LineTransaksi::model()->findAllByAttributes(array('id_header'=>$id));
foreach ($_POST['jml_kembali_bgs'] as $q3k => $q3v)
{
    if(isset($data[$q3k]))
    {
        $tabdata=LineTransaksi::model()->findByPk($data[$q3k]->id_line);
    }
    else
    {
        $tabdata=new LineTransaksi;
    }
    $tabdata->jml_kembali_bgs=$q3v;
    $arrItems[] = $tabdata;
}
foreach ($_POST['jml_kembali_retak'] as $q3r => $q3t)
{
    if(isset($data[$q3r]))
    {
        $tabdata=LineTransaksi::model()->findByPk($data[$q3r]->id_line);
    }
    else
    {
        $tabdata=new LineTransaksi;
    }
    $tabdata->jml_kembali_retak=$q3t;
    $tabdata->last_updated_date=new CDbExpression('now()');
    $arrItems[] = $tabdata;
}
foreach ($arrItems as $object)
{
    $object->save();
}
</code>```

thanks for the attention.

答:
Each time you use $arrItems[] = $tabdata; you are replacing the $arrItems[] array with the new values in $tabdata.

You should use array_push($arrItems, $tabdata); instead.

So that your code should look like:

```<code>$arrItems = array();
foreach ($_POST['jml_kembali_bgs'] as $q3k => $q3v)
{
if(isset($data[$q3k]))
{
    $tabdata=LineTransaksi::model()->findByPk($data[$q3k]->id_line);
}
else
{
    $tabdata=new LineTransaksi;
}
$tabdata->jml_kembali_bgs=$q3v;
array_push($arrItems, $tabdata);
}
foreach ($_POST['jml_kembali_retak'] as $q3r => $q3t)
{
if(isset($data[$q3r]))
{
    $tabdata=LineTransaksi::model()->findByPk($data[$q3r]->id_line);
}
else
{
    $tabdata=new LineTransaksi;
}
$tabdata->jml_kembali_retak=$q3t;
$tabdata->last_updated_date=new CDbExpression('now()');
array_push($arrItems, $tabdata);
}
foreach ($arrItems as $object)
{
$object->save();
}
</code>```

UPDATED:

You could try this:

```<code>$arrItems = array();
foreach ($_POST['jml_kembali_bgs'] as $q3k => $q3v)
{
if(isset($data[$q3k]))
{
    $tabdata=LineTransaksi::model()->findByPk($data[$q3k]->id_line);
}
else
{
    $tabdata=new LineTransaksi;
}
$tabdata->jml_kembali_bgs=$q3v;
array_push($arrItems, $tabdata);
}
foreach ($arrItems as $object)
{
$object->save();
}
foreach ($_POST['jml_kembali_retak'] as $q3r => $q3t)
{
if(isset($data[$q3r]))
{
    $tabdata=LineTransaksi::model()->findByPk($data[$q3r]->id_line);
}
else
{
    $tabdata=new LineTransaksi;
}
$tabdata->jml_kembali_retak=$q3t;
$tabdata->last_updated_date=new CDbExpression('now()');
array_push($arrItems, $tabdata);
}
foreach ($arrItems as $object)
{
$object->save();
}
</code>```

Body:
I create multiple foreach in the controller function framework yii and create one storage, but the data stored only the last foreach data, how the solution  master?

$arrItems = array();
$data = LineTransaksi::model()->findAllByAttributes(array('id_header'=>$id));
foreach ($_POST['jml_kembali_bgs'] as $q3k => $q3v)
{
    if(isset($data[$q3k]))
    {
        $tabdata=LineTransaksi::model()->findByPk($data[$q3k]->id_line);
    }
    else
    {
        $tabdata=new LineTransaksi;
    }
    $tabdata->jml_kembali_bgs=$q3v;
    $arrItems[] = $tabdata;
}
foreach ($_POST['jml_kembali_retak'] as $q3r => $q3t)
{
    if(isset($data[$q3r]))
    {
        $tabdata=LineTransaksi::model()->findByPk($data[$q3r]->id_line);
    }
    else
    {
        $tabdata=new LineTransaksi;
    }
    $tabdata->jml_kembali_retak=$q3t;
    $tabdata->last_updated_date=new CDbExpression('now()');
    $arrItems[] = $tabdata;
}
foreach ($arrItems as $object)
{
    $object->save();
}

thanks for the attention.

Body:
Each time you use $arrItems[] = $tabdata; you are replacing the $arrItems[] array with the new values in $tabdata.

You should use array_push($arrItems, $tabdata); instead.

So that your code should look like:

$arrItems = array();
foreach ($_POST['jml_kembali_bgs'] as $q3k => $q3v)
{
if(isset($data[$q3k]))
{
    $tabdata=LineTransaksi::model()->findByPk($data[$q3k]->id_line);
}
else
{
    $tabdata=new LineTransaksi;
}
$tabdata->jml_kembali_bgs=$q3v;
array_push($arrItems, $tabdata);
}
foreach ($_POST['jml_kembali_retak'] as $q3r => $q3t)
{
if(isset($data[$q3r]))
{
    $tabdata=LineTransaksi::model()->findByPk($data[$q3r]->id_line);
}
else
{
    $tabdata=new LineTransaksi;
}
$tabdata->jml_kembali_retak=$q3t;
$tabdata->last_updated_date=new CDbExpression('now()');
array_push($arrItems, $tabdata);
}
foreach ($arrItems as $object)
{
$object->save();
}

UPDATED:

You could try this:

$arrItems = array();
foreach ($_POST['jml_kembali_bgs'] as $q3k => $q3v)
{
if(isset($data[$q3k]))
{
    $tabdata=LineTransaksi::model()->findByPk($data[$q3k]->id_line);
}
else
{
    $tabdata=new LineTransaksi;
}
$tabdata->jml_kembali_bgs=$q3v;
array_push($arrItems, $tabdata);
}
foreach ($arrItems as $object)
{
$object->save();
}
foreach ($_POST['jml_kembali_retak'] as $q3r => $q3t)
{
if(isset($data[$q3r]))
{
    $tabdata=LineTransaksi::model()->findByPk($data[$q3r]->id_line);
}
else
{
    $tabdata=new LineTransaksi;
}
$tabdata->jml_kembali_retak=$q3t;
$tabdata->last_updated_date=new CDbExpression('now()');
array_push($arrItems, $tabdata);
}
foreach ($arrItems as $object)
{
$object->save();
}


问:
android 2013 nexus 7 and windows 8.1 x-64 drivers
i have made drivers work for the 2012 nexus 7, and a few other android devces.

i just got 6 2013 nexus 7's and can not seem to get the drivers installed. i upgraded the software to 6.0.1.

but i am unable to get to the screen shown here.

adb does not find any devices. in ptp mode, windows finds most of these and assigns a usb driver 6.3.9600.17415 dated 2006. trying update the driver to add a more specific driver fails because windows does not know it's a phone. using have disk fails when opening the .inf file like these: 1, 2, 3.

in charging mode, windows device manager thinks it's a google nexus adb  interface, but does not show and phone options. have disk fails also.

so adb devices fails.

this used to work somehow, but i deleted some of the drivers.

plugging in a 2012 nexus 7 shows up as an android composite adb interface and he shows up in adb list-devices.

does anyone know a way out of this trap?

edit this may be part of the problem. tried this to disable driver signature verification, but no joy.

trying shazar's idea required an uninstall (repair failed) of the clockwork driver, so some (5/6) of the devices are using the clockwork driver version 7.0.0.4 8/27/2012 when the nexus is in ptp mode. another is not recognized (no connection info when swiped down from the top).

答:
Alternate Official.

Update to Android studio 2.3.3 causes not recognizing my Nexus 7, 2012. The pre-Installed USB driver was tampered. It was working before.

I have fixed it by,

Go to https://developer.android.com/studio/run/win-usb.html

Download the Driver zip file and update the driver software at PC's Device Manager-->Portable devices-->Update driver software--> < browse and select the downloaded USB driver path >


问:
Force merge branch from specific commit
I have a branch "mybranch" which was created from the master but it has not been updated for the last couple of months. I want to update "mybarch" from a specific commit of the master branch. I want to ignore anything additional which is in "mybarch" and keep it in sync with the specific commit of the master branch. How can I achieve this? I'm trying this, does this sound ok? This results into many conflicts whereas I want to accept what comes from the master.</p>

```<code>git checkout mybranch
git merge --squash master <commit-id>
</code>```

答:
suppose master has A+B and mybranch has A+C, after merge I will be getting A+B+C where I want mybranch is same as master which is A+B

Then you can simulate the merge with one of the --theirs strategy:

```<code>git checkout -b tmp master
git merge -s ours mybranch           # ignoring all changes from mybranch
git checkout mybranch
git merge tmp                        # fast-forward to tmp HEAD
git branch -D tmp                    # deleting tmp
</code>```

Title: Force merge branch from specific commit

Body:
I have a branch "mybranch" which was created from the master but it has not been updated for the last couple of months. I want to update "mybarch" from a specific commit of the master branch. I want to ignore anything additional which is in "mybarch" and keep it in sync with the specific commit of the master branch. How can I achieve this? I'm trying this, does this sound ok? This results into many conflicts whereas I want to accept what comes from the master.

git checkout mybranch
git merge --squash master <commit-id>

Body:
suppose master has A+B and mybranch has A+C, after merge I will be getting A+B+C where I want mybranch is same as master which is A+B

Then you can simulate the merge with one of the --theirs strategy:

git checkout -b tmp master
git merge -s ours mybranch           # ignoring all changes from mybranch
git checkout mybranch
git merge tmp                        # fast-forward to tmp HEAD
git branch -D tmp                    # deleting tmp


问:
javascript code to get the html tag information and store in a variable in js code
I have an html page with content and a button. When clicked on the getData button, a javascript function is called where I have to store each html tag information to a variable.

Demo : https://plnkr.co/edit/wuIsu1qhcrYeoxtkrGxC?p=preview

js code:

```<code>function getData(){
        var $divs = $('.div1')
        alert($divs);   //[object Object] is printed
      //var p_tags;
      //var ul_tags;
    }
</code>```

html code:

```<code> <div>
        <button onClick="getData()">GetData</button>

   <div class="div1">
<p>The identity of the longest word in English depends upon the definition of what constitutes a word in the English language, as well as how length should be compared. In addition to words derived naturally from the language's roots (without any known intentional invention), English allows new words to be formed by coinage and construction; place names may be considered words; technical terms may be arbitrarily long. Length may be understood in terms of orthography and number of written letters, or (less commonly) </p>

<p><span style="color: rgb(34, 34, 34); font-family: sans-serif; font-style: italic;">This article is about the Internet encyclopedia. For Wikipedia's home page, see </span><a href="https://en.wikipedia.org/wiki/Main_Page" title="Main Page" style="color: rgb(11, 0, 128); background-image: none; background-color: rgb(255, 255, 255); font-family: sans-serif; font-style: italic;">Wikipedia's Main Page</a><span style="color: rgb(34, 34, 34); font-family: sans-serif; font-style: italic;">. For Wikipedia's visitor introduction, see </span><a href="https://en.wikipedia.org/wiki/Wikipedia:About" title="Wikipedia:About" style="color: rgb(11, 0, 128); background-image: none; background-color: rgb(255, 255, 255); font-family: sans-serif; font-style: italic;">Wikipedia's About Page</a><span style="color: rgb(34, 34, 34); font-family: sans-serif; font-style: italic;">. For other uses, see </span><a href="https://en.wikipedia.org/wiki/Wikipedia_(disambiguation)" class="mw-disambig" title="Wikipedia (disambiguation)" style="text-decoration-line: underline; color: rgb(11, 0, 128); background-image: none; background-color: rgb(255, 255, 255); font-family: sans-serif; font-style: italic;">Wikipedia </a></p>
<ul><li>one</li><li>two</li></ul>
  </div></div>
</code>```

答:
Yes it prints [object Object] but it has a little expando-toggly button.So,loop through the elements in it and display it.</p>

```<code>console.log($divs.html())
</code>```

Body:
I have an html page with content and a button. When clicked on the getData button, a javascript function is called where I have to store each html tag information to a variable.

Demo : https://plnkr.co/edit/wuIsu1qhcrYeoxtkrGxC?p=preview

js code:

function getData(){
        var $divs = $('.div1')
        alert($divs);   //[object Object] is printed
      //var p_tags;
      //var ul_tags;
    }

html code:

        <button onClick="getData()">GetData</button>

The identity of the longest word in English depends upon the definition of what constitutes a word in the English language, as well as how length should be compared. In addition to words derived naturally from the language's roots (without any known intentional invention), English allows new words to be formed by coinage and construction; place names may be considered words; technical terms may be arbitrarily long. Length may be understood in terms of orthography and number of written letters, or (less commonly)

This article is about the Internet encyclopedia. For Wikipedia's home page, see Wikipedia's Main Page. For Wikipedia's visitor introduction, see Wikipedia's About Page. For other uses, see Wikipedia

one

two

Body:
Yes it prints [object Object] but it has a little expando-toggly button.So,loop through the elements in it and display it.

console.log($divs.html())


问:
How to get all values of check boxes on button click asp.net
I have 10 check boxes populated using repeater

I want to grab all check boxes values which are checked on asp.net button click event in c#

Thank you very much for your help

答:
puesdo codeish

checkedBoxes as new list(of checkbox)

```<code>for each item as repeater in repeater.items

 checkbox = (CheckBox)item.findcontrol("checkboxid")

 if checkbox.checked
  checkedBoxes.add(checkbox)
 end if

end for
</code>```

Body:
puesdo codeish

checkedBoxes as new list(of checkbox)

for each item as repeater in repeater.items

 checkbox = (CheckBox)item.findcontrol("checkboxid")

 if checkbox.checked
  checkedBoxes.add(checkbox)
 end if

end for


问:
Zxing lib. does not work above Android M
I have successfully integrated zxing core.jar library below android Marshmallow, but while integrating this into above Marshmallow, it gives me following error:

```<code>android.content.ActivityNotFoundException: NO activity found to handle
intent{act=com.google.zxing.client.android.SCAN}
</code>```

Thanks in advance.

答:
You should edit code at Manifest file:

```<code><activity
            android:name="com.google.zxing.client.android.CaptureActivity"
            android:configChanges="orientation|keyboardHidden"
            android:screenOrientation="landscape"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
            android:windowSoftInputMode="stateAlwaysHidden" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="com.google.zxing.client.android.SCAN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
</code>```

And don't forget add permission:

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA"/>
</code>```

Body:
I have successfully integrated zxing core.jar library below android Marshmallow, but while integrating this into above Marshmallow, it gives me following error:

android.content.ActivityNotFoundException: NO activity found to handle
intent{act=com.google.zxing.client.android.SCAN}

Thanks in advance.

Body:
You should edit code at Manifest file:

<activity
            android:name="com.google.zxing.client.android.CaptureActivity"
            android:configChanges="orientation|keyboardHidden"
            android:screenOrientation="landscape"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
            android:windowSoftInputMode="stateAlwaysHidden" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="com.google.zxing.client.android.SCAN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

And don't forget add permission:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA"/>