问:
Child Model List is Empty after DB Add in Entity Framework Core
So I am trying out Entity Framework Core, and am having trouble with my first pair of relational Models. I'm trying to use conventions to form the relationship, as follows:

The principal entity, with conventional principal key (Id) and collection navigation property (the list of Locations):

```<code>public class Site
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public int LocationCount { get; set; } = 1;
    public List<Location> Locations { get; set; } = new List<Location>();
}
</code>```

The dependent entity, with conventional foreign key (SiteId) and reference navigation property (Site):

```<code>public class Location
{
    public int Id { get; set; }
    public int SiteId { get; set; }
    public Site Site { get; set; }
    public int AreaCount { get; set; } = 1;
    public Location(Site site) { SiteId = site.Id; }
}
</code>```

And since I want every Site to already have at least one location, I put this in the Create action of the SiteController, in an attempt to create the dependents along with the principal:

```<code>[HttpPost]
public IActionResult Create(Site site)
{
    _context.Sites.Add(site);
    for (int i = 0; i < site.LocationCount; i++)
        _context.Locations.Add(new Location(site));
    _context.SaveChanges();
    return RedirectToAction("Details", new { Name = site.Name });
}
</code>```

However, on the Details view, when I try to display the Locations that were created, the list is always empty:

```<code><h2>@Model.Locations.Count Locations</h2>
@foreach (Location l in Model.Locations)
{
    <div class="row">
        <div class="col-sm-12">@l.Id</div>
    </div>
}
</code>```

Just results in:

```<code>0 Locations
</code>```

Thank you in advance for any help explaining what I've missed!

Edit: By request, here is the body of the Details action in the Site Controller, which gets the Model data for the Details View:

```<code>public IActionResult Details(string name)
{
    var model = _context.Sites.FirstOrDefault(a => a.Name == name);
    if (model == null) model = new Site();
    return View(model);
}
</code>```

Also, per one suggestion, I have fixed the problem of setting the Location.SiteId before Site.Id has a value, since the Id isn't automatically generated on the Site until after SaveChanges() is called. Unfortunately, the result (empty Locations list) is still the same:

```<code>[HttpPost]
public IActionResult Create(Site site)
{
    int nextsiteid = _context.Sites.Count() + 1;
    _context.Sites.Add(site);
    for (int i = 0; i < site.LocationCount; i++)
        _context.Locations.Add(new Location(siteid));
    _context.SaveChanges();
    return RedirectToAction("Details", new { Name = site.Name });
}
</code>```

And changed the Location constructor to use the Id instead of the instance:

```<code>public Location(int siteid) { SiteId = siteid; }
</code>```

Thanks in advance for any further suggestions!

答:
I'm just transcribing the answer I was given, which was provided in the comments of the original post, so that it can easily be found by anyone reading the post.

The issue was, quite simply, that EF Core does not yet support lazy loading. So when the Site entity is populated, it doesn't lazily load the list of dependent locations into the collection navigation property.

The fix is to use eager loading, by way of:

```<code>var model = _context.Sites.Include(s => s.Locations).FirstOrDefault(a => a.Name == name);
</code>```

When loading the Model data of the Site to provide to the View.

Thanks for the solution, Ivan!

Body:
So I am trying out Entity Framework Core, and am having trouble with my first pair of relational Models. I'm trying to use conventions to form the relationship, as follows:

The principal entity, with conventional principal key (Id) and collection navigation property (the list of Locations):

public class Site
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public int LocationCount { get; set; } = 1;
    public List<Location> Locations { get; set; } = new List<Location>();
}

The dependent entity, with conventional foreign key (SiteId) and reference navigation property (Site):

public class Location
{
    public int Id { get; set; }
    public int SiteId { get; set; }
    public Site Site { get; set; }
    public int AreaCount { get; set; } = 1;
    public Location(Site site) { SiteId = site.Id; }
}

And since I want every Site to already have at least one location, I put this in the Create action of the SiteController, in an attempt to create the dependents along with the principal:

[HttpPost]
public IActionResult Create(Site site)
{
    _context.Sites.Add(site);
    for (int i = 0; i < site.LocationCount; i++)
        _context.Locations.Add(new Location(site));
    _context.SaveChanges();
    return RedirectToAction("Details", new { Name = site.Name });
}

However, on the Details view, when I try to display the Locations that were created, the list is always empty:

@Model.Locations.Count Locations

@foreach (Location l in Model.Locations)
{

@l.Id

}

Just results in:

0 Locations

Thank you in advance for any help explaining what I've missed!

Edit: By request, here is the body of the Details action in the Site Controller, which gets the Model data for the Details View:

public IActionResult Details(string name)
{
    var model = _context.Sites.FirstOrDefault(a => a.Name == name);
    if (model == null) model = new Site();
    return View(model);
}

Also, per one suggestion, I have fixed the problem of setting the Location.SiteId before Site.Id has a value, since the Id isn't automatically generated on the Site until after SaveChanges() is called. Unfortunately, the result (empty Locations list) is still the same:

[HttpPost]
public IActionResult Create(Site site)
{
    int nextsiteid = _context.Sites.Count() + 1;
    _context.Sites.Add(site);
    for (int i = 0; i < site.LocationCount; i++)
        _context.Locations.Add(new Location(siteid));
    _context.SaveChanges();
    return RedirectToAction("Details", new { Name = site.Name });
}

And changed the Location constructor to use the Id instead of the instance:

public Location(int siteid) { SiteId = siteid; }

Thanks in advance for any further suggestions!

Body:
I'm just transcribing the answer I was given, which was provided in the comments of the original post, so that it can easily be found by anyone reading the post.

The issue was, quite simply, that EF Core does not yet support lazy loading. So when the Site entity is populated, it doesn't lazily load the list of dependent locations into the collection navigation property.

The fix is to use eager loading, by way of:

var model = _context.Sites.Include(s => s.Locations).FirstOrDefault(a => a.Name == name);

When loading the Model data of the Site to provide to the View.

Thanks for the solution, Ivan!


来源: stackexchange

问:
Xcode 7.2 generating Generic Xcode Archive instead of IPA
I have just taken over of a legacy project written in Objective-C and started extending it with some Swift elements.

The issue is that I cannot archive the app into an IPA - I constantly get generic Xcode archive instead of IPA that I can submit to the app store

Context :
 - Cocoa pods version 0.39.0, Xcode version 7.2

I use cocoapods but the issue was present earlier, when the project didn't use it yet.

I have tips from other similar issues on stack overflow (one two) but nothing seems to help.

'Skip install' is set to YES on all of the pod building targets. Main project has 'skip install' set to NO.

When I export the build products the folder contains only MyApp.app

All of the copy headers are in 'Project' not in 'Public'. I have also tried a configuration with 'Private' but it didn't help.

My build scheme :

I have also tried building the entire workspace from command line with the following script :

xcodebuild -scheme MyScheme -workspace MyProject.xcworkspace clean archive -archivePath build/MyProject
xcodebuild -exportArchive -exportFormat ipa -archivePath "build/MyProject.xcarchive" -exportPath "build/MyProject.ipa" -exportProvisioningProfile "DistributionProvisioningProfile"

but I'm getting the following error :

```<code>error: the archive at path '/pathtotheappfolder/MyProject.xcarchive' is not a single-bundle archive
</code>```

My main question is - how build it as an IPA?

Side question - how do I find out or at least get direction of what is going wrong?

Update :

When exporting the archive and going to "show package contents" the file structure looks like that :

Thanks!

答: While viewing the Xcode archive (or xcarchive) in Xcode (8.3.2) click Export on the right hand side. Choose your certificate and a method for export. Then you'll get the ipa.

ContentLicense: CC BY-SA 3.0

Body:
I have just taken over of a legacy project written in Objective-C and started extending it with some Swift elements.

The issue is that I cannot archive the app into an IPA - I constantly get generic Xcode archive instead of IPA that I can submit to the app store

Context :
 - Cocoa pods version 0.39.0, Xcode version 7.2

I use cocoapods but the issue was present earlier, when the project didn't use it yet.

I have tips from other similar issues on stack overflow (one two) but nothing seems to help.

'Skip install' is set to YES on all of the pod building targets. Main project has 'skip install' set to NO.

When I export the build products the folder contains only MyApp.app

All of the copy headers are in 'Project' not in 'Public'. I have also tried a configuration with 'Private' but it didn't help.

My build scheme :

I have also tried building the entire workspace from command line with the following script :

xcodebuild -scheme MyScheme -workspace MyProject.xcworkspace clean archive -archivePath build/MyProject
xcodebuild -exportArchive -exportFormat ipa -archivePath "build/MyProject.xcarchive" -exportPath "build/MyProject.ipa" -exportProvisioningProfile "DistributionProvisioningProfile"

but I'm getting the following error :

error: the archive at path '/pathtotheappfolder/MyProject.xcarchive' is not a single-bundle archive

My main question is - how build it as an IPA?

Side question - how do I find out or at least get direction of what is going wrong?

Update :

When exporting the archive and going to "show package contents" the file structure looks like that :

Thanks!

ContentLicense: CC BY-SA 4.0


问:
cannot cast to java.lang.Comparable
Although this question has already been asked but I have an implementation specific doubt.

I am trying to print the top view of the binary tree and following is the complete code for it:

```<code>import java.util.*;

class Node{
    int data;
    Node right;
    Node left;
    Node(int data){
        this.data = data;
    }
}

class Pair<F,S>{
    private F first;
    private S second;
    public Pair(F first, S second){
        this.first = first;
        this.second = second;
    }

    public F getFirst(){return first;}
    public S getSecond(){return second;}
}

class BinaryTreeTopView{

    public static void printTopView(Node root){

        if(root == null)
            return;

    Queue <Pair<Node,Integer>> q = new Queue<>();
    Map <Integer,Node> map = new HashMap<>();
    Pair<Node,Integer> p = new Pair<>(root, 0);
    q.add(p);

    /*
    I am storing nodes and the corresponding horizontal distances
    in the form of a pair which then are being stored in the queue
    to ensure level order traversal
    */

    while(!q.isEmpty()){
        Pair<Node,Integer> temp = q.peek();
        q.remove();

        if(map.containsKey(temp.getSecond())==true){
            map.put(temp.getSecond(),temp.getFirst());
        } else {
            System.out.println(temp.getFirst().data);
            map.put(temp.getSecond(),temp.getFirst());
        }

        if(temp.getFirst().left!=null){
            Pair<Node,Integer> left = new Pair<>(temp.getFirst().left, temp.getSecond()-1);
            q.add(left);
        }

        if(temp.getFirst().right!=null){
            Pair<Node,Integer> right = new Pair<> (temp.getFirst().right, temp.getSecond()+1);
            q.add(right);
        }

    }
}
public static void main(String[] args) {
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.right = new Node(5);
    root.left.left = new Node(4);
    root.right.left = new Node(6);
    root.right.right = new Node(7);
    root.right.left.right = new Node(8);
    root.right.right.left = new Node(10);
    root.right.right.right = new Node(9);
    root.right.right.left.right = new Node(11);
    root.right.right.left.right.right = new Node(12);

    printTopView(root);
}
}
</code>```

It compiles fine but an exception is being raised at the runtime.
Now I have been getting the following exception and I am unable to figure out what the problem is:

```<code>Exception in thread "main" java.lang.ClassCastException:
Pair cannot be cast to java.lang.Comparable at  java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:652)
at java.util.PriorityQueue.siftUp(PriorityQueue.java:647)
at java.util.PriorityQueue.offer(PriorityQueue.java:344)
at java.util.PriorityQueue.add(PriorityQueue.java:321)
</code>```

答:
It's because Pair isn't implementing Comparable. Either implement it:

```<code>public class Pair implements Comparable<Pair> {
    public int compareTo(Pair o) {
        // ...
    }
}
</code>```

Or use Comparator in Your priority queue

Using Comparator ;

```<code>PriorityQueue<DummyObject> pq = new
             PriorityQueue<DummyObject>(5, new DummyObjectComparator());
</code>```

Define your Comparator :

```<code>class DummyObjectComparator implements Comparator<DummyObject>{

      // Overriding compare()method of Comparator

       public int compare(DummyObject s1, DummyObject s2) {
                   //some code
       }
 }
</code>```

Title: cannot cast to java.lang.Comparable

Body:
Although this question has already been asked but I have an implementation specific doubt.

I am trying to print the top view of the binary tree and following is the complete code for it:

import java.util.*;

class Node{
    int data;
    Node right;
    Node left;
    Node(int data){
        this.data = data;
    }
}

class Pair<F,S>{
    private F first;
    private S second;
    public Pair(F first, S second){
        this.first = first;
        this.second = second;
    }

    public F getFirst(){return first;}
    public S getSecond(){return second;}
}

class BinaryTreeTopView{

    public static void printTopView(Node root){

        if(root == null)
            return;

    Queue <Pair<Node,Integer>> q = new Queue<>();
    Map <Integer,Node> map = new HashMap<>();
    Pair<Node,Integer> p = new Pair<>(root, 0);
    q.add(p);

    /*
    I am storing nodes and the corresponding horizontal distances
    in the form of a pair which then are being stored in the queue
    to ensure level order traversal
    */

    while(!q.isEmpty()){
        Pair<Node,Integer> temp = q.peek();
        q.remove();

        if(map.containsKey(temp.getSecond())==true){
            map.put(temp.getSecond(),temp.getFirst());
        } else {
            System.out.println(temp.getFirst().data);
            map.put(temp.getSecond(),temp.getFirst());
        }

        if(temp.getFirst().left!=null){
            Pair<Node,Integer> left = new Pair<>(temp.getFirst().left, temp.getSecond()-1);
            q.add(left);
        }

        if(temp.getFirst().right!=null){
            Pair<Node,Integer> right = new Pair<> (temp.getFirst().right, temp.getSecond()+1);
            q.add(right);
        }

    }
}
public static void main(String[] args) {
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.right = new Node(5);
    root.left.left = new Node(4);
    root.right.left = new Node(6);
    root.right.right = new Node(7);
    root.right.left.right = new Node(8);
    root.right.right.left = new Node(10);
    root.right.right.right = new Node(9);
    root.right.right.left.right = new Node(11);
    root.right.right.left.right.right = new Node(12);

    printTopView(root);
}
}

It compiles fine but an exception is being raised at the runtime.
Now I have been getting the following exception and I am unable to figure out what the problem is:

Exception in thread "main" java.lang.ClassCastException:
Pair cannot be cast to java.lang.Comparable at  java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:652)
at java.util.PriorityQueue.siftUp(PriorityQueue.java:647)
at java.util.PriorityQueue.offer(PriorityQueue.java:344)
at java.util.PriorityQueue.add(PriorityQueue.java:321)

Body:
It's because Pair isn't implementing Comparable. Either implement it:

public class Pair implements Comparable<Pair> {
    public int compareTo(Pair o) {
        // ...
    }
}

Or use Comparator in Your priority queue

Using Comparator ;

PriorityQueue<DummyObject> pq = new
             PriorityQueue<DummyObject>(5, new DummyObjectComparator());

Define your Comparator :

class DummyObjectComparator implements Comparator<DummyObject>{

      // Overriding compare()method of Comparator

       public int compare(DummyObject s1, DummyObject s2) {
                   //some code
       }
 }


问:
Android Custom listview event listener
I need some help. I want to extract data from my custom ListView, but don't know how. I want to get the data for the item selected in a another activity. I have to show the menu that the user selected.

Here is my code:

```<code>package com.example.mouhamedalysidibe.restaurant;

public class Menus extends AppCompatActivity {
    public TabHost host ;

int[] Imagesfood = {R.drawable.pizza,R.drawable.baguette, R.drawable.pastas , R.drawable.donuts , R.drawable.snacks };
    String [] nomsfood = {"Pizza" , "Baguettes" ,"Pastas" , "Donuts" , "Snacks"};
    String [] descriptionfood = {"Les meilleurs pizzas de Dakar" , "Explosion de saveurs a prix mini" , "Laissez vous tenter" , "Al dente et tellement genereuses ", "Un delice a chaque bouchée"};

    int[] Imagesdrink = {R.drawable.gazeuse,R.drawable.alcool, R.drawable.cocktail , R.drawable.chaude};
    String [] nomsdrink = {"Boissons gazeuses" , "Alccol " ,"Cocktails" , "Boissons chaudes"};
    String [] descriptiondrink = {"Pensez a vous desalterer" , "De la bonne qualite" , "Decouvrez nos coktails" , "Un bon cafe ne fait jamais de mal"};

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menus);

        //tabhost
        host = (TabHost)findViewById(R.id.tabHost);
        host.setup();

        //Layouts
        TabHost.TabSpec spec = host.newTabSpec("EAT");
        spec.setContent(R.id.Eat);
        spec.setIndicator("FOOD");
        host.addTab(spec);

        //Widgets
        spec = host.newTabSpec("DRINKS");
        spec.setContent(R.id.Drink);
        spec.setIndicator("DRINK");
        host.addTab(spec);

        TextView tablefood = (TextView)findViewById(R.id.table);
        TextView tableDrink =(TextView)findViewById(R.id.tableD);
        Intent intent = getIntent();

        String tabletextfood = intent.getStringExtra("table");
        tablefood.setText(""+tabletextfood);
        String tabletextdrink = intent.getStringExtra("table");
        tableDrink.setText(""+tabletextdrink);

        //Listview Food

        final ListView listmenufood = (ListView)findViewById(R.id.listView_food);
        CustomAdapterFood customAdapterFood = new CustomAdapterFood();
        listmenufood.setAdapter(customAdapterFood);
        listmenufood.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                view =(View) adapterView.getItemAtPosition(i);
                Intent intent = new Intent(Menus.this,Plats.class);

                startActivity(intent);

            }
        });

        //Listview drink

        ListView listmenudrink = (ListView)findViewById(R.id.listView_drink);
        CustomAdapterDrink customAdapterDrink = new CustomAdapterDrink();

        listmenudrink.setAdapter(customAdapterDrink);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==R.id.appel){
            final AlertDialog retry = new AlertDialog.Builder( this ).create();
            retry.setTitle(R.string.app_name);
            retry.setMessage("MERCI DE PATIENTER QUELQUES INSTANTS , NOUS VENONS BIENTOT PRENDRE VOTRE COMMANDE");
            retry.setButton(AlertDialog.BUTTON_NEUTRAL,"OK",new  DialogInterface.OnClickListener(){
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    retry.cancel();
                }
            });

            retry.show();

        }
        return super.onOptionsItemSelected(item);
    }

    // Foods

    public class CustomAdapterFood extends BaseAdapter{

        @Override
        public int getCount() {
            return Imagesfood.length;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = getLayoutInflater().inflate(R.layout.customlayout ,null);
            ImageView imageView = (ImageView)view.findViewById(R.id.img);
            TextView nom = (TextView)view.findViewById(R.id.TextView_nom);
            TextView descrip =(TextView)view.findViewById(R.id.TextView_description);
            imageView.setImageResource(Imagesfood[i]);
            nom.setText(nomsfood[i]);
            descrip.setText(descriptionfood[i]);

            return view;
        }
    }

    //Drinks

    public class CustomAdapterDrink extends BaseAdapter{

        @Override
        public int getCount() {
            return Imagesdrink.length;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = getLayoutInflater().inflate(R.layout.customdrinklayout,null);
            ImageView imageView = (ImageView)view.findViewById(R.id.img);
            TextView nom = (TextView)view.findViewById(R.id.TextView_nom);
            TextView descrip =(TextView)view.findViewById(R.id.TextView_description);
            imageView.setImageResource(Imagesdrink[i]);
            nom.setText(nomsdrink[i]);
            descrip.setText(descriptiondrink[i]);
            return view;
        }
    }
}
</code>```

答:
If you want to return image,name & description you need to create classes for your Food and Drink

```<code>//food
public class food {
int image;
String name,description;

public food(int image, String name, String description) {

    this.image = image;
    this.name = name;
    this.description = description;
}
public String getDescription() {
    return description;
}

public String getName() {
    return name;
}

public int getImage() {
    return image;
}

}
</code>```

similarly for drinks

add food  and drink objects to list

```<code> foods.add(new food(R.drawable.pizza,"Pizza","description"));
    foods.add(new food(R.drawable.pasta,"Pasta","description"));
    //add the rest

        //similarly for drink

    drinks.add(new drink(R.drawable.somedrink,"name","description"));
    drinks.add(new drink(R.drawable.somedrink,"name","description"));

    //add the rest
</code>```

change your custom adapters to these

```<code>        public class CustomAdapterFood extends BaseAdapter {
</code>```

ArrayList foodlist;

```<code>    public CustomAdapterFood(ArrayList<food> foodlist) {
        this.foodlist = foodlist;
    }

    @Override
    public int getCount() {
        return foodlist.size();
    }

    @Override
    public Object getItem(int i) {
        return foodlist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = getLayoutInflater().inflate(R.layout.customlayout ,null);
        ImageView imageView = (ImageView)view.findViewById(R.id.img);
        TextView nom = (TextView)view.findViewById(R.id.TextView_nom);
        TextView descrip =(TextView)view.findViewById(R.id.TextView_description);
        imageView.setImageResource(foodlist.get(i).getImage());
        nom.setText(foodlist.get(i).getName());
        descrip.setText(foodlist.get(i).getDescription());

        return view;
    }
}
</code>```

and

```<code>    public class CustomAdapterDrink extends BaseAdapter{
    ArrayList<drink> drinklist;

    public CustomAdapterDrink(ArrayList<drink> drinklist) {
        this.drinklist = drinklist;
    }

    @Override
    public int getCount() {
        return drinklist.size();
    }

    @Override
    public Object getItem(int i) {
        return drinklist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = getLayoutInflater().inflate(R.layout.customdrinklayout,null);
        ImageView imageView = (ImageView)view.findViewById(R.id.img);
        TextView nom = (TextView)view.findViewById(R.id.TextView_nom);
        TextView descrip =(TextView)view.findViewById(R.id.TextView_description);
        imageView.setImageResource(drinklist.get(i).getImage());
        nom.setText(drinklist.get(i).getName());
        descrip.setText(drinklist.get(i).getDescription());
        return view;
    }
}
</code>```

while creating your adapters pass the list to them
like this:

```<code>        CustomAdapterDrink customAdapterDrink = new CustomAdapterDrink(drinks);

        CustomAdapterFood customAdapterFood = new CustomAdapterFood(foods);
</code>```

Title: Android Custom listview event listener

Body:
I need some help. I want to extract data from my custom ListView, but don't know how. I want to get the data for the item selected in a another activity. I have to show the menu that the user selected.

Here is my code:

package com.example.mouhamedalysidibe.restaurant;

public class Menus extends AppCompatActivity {
    public TabHost host ;

int[] Imagesfood = {R.drawable.pizza,R.drawable.baguette, R.drawable.pastas , R.drawable.donuts , R.drawable.snacks };
    String [] nomsfood = {"Pizza" , "Baguettes" ,"Pastas" , "Donuts" , "Snacks"};
    String [] descriptionfood = {"Les meilleurs pizzas de Dakar" , "Explosion de saveurs a prix mini" , "Laissez vous tenter" , "Al dente et tellement genereuses ", "Un delice a chaque bouchée"};

    int[] Imagesdrink = {R.drawable.gazeuse,R.drawable.alcool, R.drawable.cocktail , R.drawable.chaude};
    String [] nomsdrink = {"Boissons gazeuses" , "Alccol " ,"Cocktails" , "Boissons chaudes"};
    String [] descriptiondrink = {"Pensez a vous desalterer" , "De la bonne qualite" , "Decouvrez nos coktails" , "Un bon cafe ne fait jamais de mal"};

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menus);

        //tabhost
        host = (TabHost)findViewById(R.id.tabHost);
        host.setup();

        //Layouts
        TabHost.TabSpec spec = host.newTabSpec("EAT");
        spec.setContent(R.id.Eat);
        spec.setIndicator("FOOD");
        host.addTab(spec);

        //Widgets
        spec = host.newTabSpec("DRINKS");
        spec.setContent(R.id.Drink);
        spec.setIndicator("DRINK");
        host.addTab(spec);

        TextView tablefood = (TextView)findViewById(R.id.table);
        TextView tableDrink =(TextView)findViewById(R.id.tableD);
        Intent intent = getIntent();

        String tabletextfood = intent.getStringExtra("table");
        tablefood.setText(""+tabletextfood);
        String tabletextdrink = intent.getStringExtra("table");
        tableDrink.setText(""+tabletextdrink);

        //Listview Food

        final ListView listmenufood = (ListView)findViewById(R.id.listView_food);
        CustomAdapterFood customAdapterFood = new CustomAdapterFood();
        listmenufood.setAdapter(customAdapterFood);
        listmenufood.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                view =(View) adapterView.getItemAtPosition(i);
                Intent intent = new Intent(Menus.this,Plats.class);

                startActivity(intent);

            }
        });

        //Listview drink

        ListView listmenudrink = (ListView)findViewById(R.id.listView_drink);
        CustomAdapterDrink customAdapterDrink = new CustomAdapterDrink();

        listmenudrink.setAdapter(customAdapterDrink);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==R.id.appel){
            final AlertDialog retry = new AlertDialog.Builder( this ).create();
            retry.setTitle(R.string.app_name);
            retry.setMessage("MERCI DE PATIENTER QUELQUES INSTANTS , NOUS VENONS BIENTOT PRENDRE VOTRE COMMANDE");
            retry.setButton(AlertDialog.BUTTON_NEUTRAL,"OK",new  DialogInterface.OnClickListener(){
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    retry.cancel();
                }
            });

            retry.show();

        }
        return super.onOptionsItemSelected(item);
    }

    // Foods

    public class CustomAdapterFood extends BaseAdapter{

        @Override
        public int getCount() {
            return Imagesfood.length;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = getLayoutInflater().inflate(R.layout.customlayout ,null);
            ImageView imageView = (ImageView)view.findViewById(R.id.img);
            TextView nom = (TextView)view.findViewById(R.id.TextView_nom);
            TextView descrip =(TextView)view.findViewById(R.id.TextView_description);
            imageView.setImageResource(Imagesfood[i]);
            nom.setText(nomsfood[i]);
            descrip.setText(descriptionfood[i]);

            return view;
        }
    }

    //Drinks

    public class CustomAdapterDrink extends BaseAdapter{

        @Override
        public int getCount() {
            return Imagesdrink.length;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = getLayoutInflater().inflate(R.layout.customdrinklayout,null);
            ImageView imageView = (ImageView)view.findViewById(R.id.img);
            TextView nom = (TextView)view.findViewById(R.id.TextView_nom);
            TextView descrip =(TextView)view.findViewById(R.id.TextView_description);
            imageView.setImageResource(Imagesdrink[i]);
            nom.setText(nomsdrink[i]);
            descrip.setText(descriptiondrink[i]);
            return view;
        }
    }
}

Body:
If you want to return image,name & description you need to create classes for your Food and Drink

//food
public class food {
int image;
String name,description;

public food(int image, String name, String description) {

    this.image = image;
    this.name = name;
    this.description = description;
}
public String getDescription() {
    return description;
}

public String getName() {
    return name;
}

public int getImage() {
    return image;
}

}

similarly for drinks

add food  and drink objects to list

 foods.add(new food(R.drawable.pizza,"Pizza","description"));
    foods.add(new food(R.drawable.pasta,"Pasta","description"));
    //add the rest

        //similarly for drink

    drinks.add(new drink(R.drawable.somedrink,"name","description"));
    drinks.add(new drink(R.drawable.somedrink,"name","description"));

    //add the rest

change your custom adapters to these

        public class CustomAdapterFood extends BaseAdapter {

ArrayList foodlist;

    public CustomAdapterFood(ArrayList<food> foodlist) {
        this.foodlist = foodlist;
    }

    @Override
    public int getCount() {
        return foodlist.size();
    }

    @Override
    public Object getItem(int i) {
        return foodlist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = getLayoutInflater().inflate(R.layout.customlayout ,null);
        ImageView imageView = (ImageView)view.findViewById(R.id.img);
        TextView nom = (TextView)view.findViewById(R.id.TextView_nom);
        TextView descrip =(TextView)view.findViewById(R.id.TextView_description);
        imageView.setImageResource(foodlist.get(i).getImage());
        nom.setText(foodlist.get(i).getName());
        descrip.setText(foodlist.get(i).getDescription());

        return view;
    }
}

and

    public class CustomAdapterDrink extends BaseAdapter{
    ArrayList<drink> drinklist;

    public CustomAdapterDrink(ArrayList<drink> drinklist) {
        this.drinklist = drinklist;
    }

    @Override
    public int getCount() {
        return drinklist.size();
    }

    @Override
    public Object getItem(int i) {
        return drinklist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = getLayoutInflater().inflate(R.layout.customdrinklayout,null);
        ImageView imageView = (ImageView)view.findViewById(R.id.img);
        TextView nom = (TextView)view.findViewById(R.id.TextView_nom);
        TextView descrip =(TextView)view.findViewById(R.id.TextView_description);
        imageView.setImageResource(drinklist.get(i).getImage());
        nom.setText(drinklist.get(i).getName());
        descrip.setText(drinklist.get(i).getDescription());
        return view;
    }
}

while creating your adapters pass the list to them
like this:

        CustomAdapterDrink customAdapterDrink = new CustomAdapterDrink(drinks);

        CustomAdapterFood customAdapterFood = new CustomAdapterFood(foods);


问:
Formatting the way a string is entered into my database
I am wanting to format data entered into a string column (confusingly named time) of my database in a certain way. Because of legacy data issues on this project I can't simply change the column type from string to time because I would lose the old entries.

I simply want to require that the format of the information entered into the form and then submitted to the database is as follows:

00:00 where a 0 can by any integer 0-9.

How would I do that within a form_for.

I am using Rails 2.3.8.

答:
Your regex would be:

```<code>/[0-9]{2}:[0-9]{2}/
</code>```

or

```<code>/\d\d:\d\d/
</code>```

Here are some tests:

```<code>'00:00'[/[0-9]{2}:[0-9]{2}/] # => "00:00"
'12:00'[/\d\d:\d\d/]         # => "12:00"
'11:59'[/[0-9]{2}:[0-9]{2}/] # => "11:59"
'23:59'[/\d\d:\d\d/]         # => "23:59"

':'[/[0-9]{2}:[0-9]{2}/] # => nil
':0'[/[0-9]{2}:[0-9]{2}/] # => nil
'0:0'[/[0-9]{2}:[0-9]{2}/] # => nil
'000:0'[/[0-9]{2}:[0-9]{2}/] # => nil
'0:000'[/[0-9]{2}:[0-9]{2}/] # => nil
</code>```

Up to this point I was working with your specified solution, but here's where it breaks down:

```<code># BUG?
'1:00'[/[0-9]{2}:[0-9]{2}/] # => nil

# Fix?
'1:00'[/[0-9]{1,2}:[0-9]{2}/] # => "1:00"

# *** BUG ***
'99:99'[/[0-9]{2}:[0-9]{2}/] # => "99:99"
</code>```

Note that '99:99' is accepted.

Trying to use a regex to check the range is not really very workable when dealing with something like a time value. It can be done, but the regex becomes ugly.

Here's the start of a solution. Finishing the tests for appropriate range is left as an exercise for the reader:

```<code>timeval = '00:00'[/[0-9]{2}:[0-9]{2}/]
(timeval.split(':').map(&:to_i) <=> [11,59]) <= 0 # => true

timeval = '1:00'[/[0-9]{1,2}:[0-9]{2}/]
(timeval.split(':').map(&:to_i) <=> [11,59]) <= 0 # => true

timeval = '1:00'[/[0-9]{1,2}:[0-9]{2}/]
(timeval.split(':').map(&:to_i) <=> [11,59]) <= 0 # => true

timeval = '0:99'[/[0-9]{1,2}:[0-9]{2}/]
(timeval.split(':').map(&:to_i) <=> [11,59]) <= 0 # => true

timeval = '99:99'[/[0-9]{1,2}:[0-9]{2}/]
(timeval.split(':').map(&:to_i) <=> [11,59]) <= 0 # => false
</code>```

Alternately, you might want to look into using some <select> popups for the values, or a jQuery plugin that is designed for time input, or something like validates_timeliness or validates_date_time. I also found time_select with 12 hour time and Time Zone in Ruby on Rails. You can search Stack Overflow too.

ContentLicense: CC BY-SA 2.5

Body:
Your regex would be:

/[0-9]{2}:[0-9]{2}/

or

/\d\d:\d\d/

Here are some tests:

'00:00'[/[0-9]{2}:[0-9]{2}/] # => "00:00"
'12:00'[/\d\d:\d\d/]         # => "12:00"
'11:59'[/[0-9]{2}:[0-9]{2}/] # => "11:59"
'23:59'[/\d\d:\d\d/]         # => "23:59"

':'[/[0-9]{2}:[0-9]{2}/] # => nil
':0'[/[0-9]{2}:[0-9]{2}/] # => nil
'0:0'[/[0-9]{2}:[0-9]{2}/] # => nil
'000:0'[/[0-9]{2}:[0-9]{2}/] # => nil
'0:000'[/[0-9]{2}:[0-9]{2}/] # => nil

Up to this point I was working with your specified solution, but here's where it breaks down:

# BUG?
'1:00'[/[0-9]{2}:[0-9]{2}/] # => nil

# Fix?
'1:00'[/[0-9]{1,2}:[0-9]{2}/] # => "1:00"

# *** BUG ***
'99:99'[/[0-9]{2}:[0-9]{2}/] # => "99:99"

Note that '99:99' is accepted.

Trying to use a regex to check the range is not really very workable when dealing with something like a time value. It can be done, but the regex becomes ugly.

Here's the start of a solution. Finishing the tests for appropriate range is left as an exercise for the reader:

timeval = '00:00'[/[0-9]{2}:[0-9]{2}/]
(timeval.split(':').map(&:to_i) <=> [11,59]) <= 0 # => true

timeval = '1:00'[/[0-9]{1,2}:[0-9]{2}/]
(timeval.split(':').map(&:to_i) <=> [11,59]) <= 0 # => true

timeval = '1:00'[/[0-9]{1,2}:[0-9]{2}/]
(timeval.split(':').map(&:to_i) <=> [11,59]) <= 0 # => true

timeval = '0:99'[/[0-9]{1,2}:[0-9]{2}/]
(timeval.split(':').map(&:to_i) <=> [11,59]) <= 0 # => true

timeval = '99:99'[/[0-9]{1,2}:[0-9]{2}/]
(timeval.split(':').map(&:to_i) <=> [11,59]) <= 0 # => false

Alternately, you might want to look into using some <select> popups for the values, or a jQuery plugin that is designed for time input, or something like validates_timeliness or validates_date_time. I also found time_select with 12 hour time and Time Zone in Ruby on Rails. You can search Stack Overflow too.


问:
Python - filter column from a .dat file and return a given value from other columns
I'm new to Python and been practicing with sample data I created (150 rows) of student ID numbers, grades, age, class_code, area_code, etc. What I'm trying to do with the data is not only filtered by a certain column (by grade, age, etc), but then to also create a list of a different column from that row (student ID). I've manged to find how to isolate the column I need to find the certain value by, but then can't figure out how to create that list of the values I need to return.

So here's a sample of 5 rows of the data:

```<code>1/A/15/13/43214
2/I/15/21/58322
3/C/17/89/68470
4/I/18/6/57362
5/I/14/4/00000
6/A/16/23/34567
</code>```

I need a list of the 1st column (student ID), based on filtering the second column (grade)...(and eventually the 3rd column, 4th column, etc. But if I see how it looks with just the 2nd, I think I can figure out the others) Also note: I didn't use headers in the .dat file.

I figured out how to isolate/view the 2nd column.

```<code>import numpy

data = numpy.genfromtxt('/testdata.dat', delimiter='/', dtype='unicode')

grades = data[:,1]
print (grades)
</code>```

to print:

```<code>['A' 'I' 'C' 'I' 'I' 'A']
</code>```

But now, how can I pull just the first column's that correspond to the A's, C's, I's into separate  lists?

So I'd want to see a list, also with the commas between the integers of column 1 for the A's, C's, and I's

```<code>list from A = [1, 6]
list from C = [3]
list from I = [2, 4, 5]
</code>```

Again, if I can just see how it's done with just the 2nd column, with just one of the values (say A's), I think I could figure out how to do it for B's, C's, D's, etc and probably the other columns. I just need to see one example to how the syntax would be applied and then like to play around with the rest.

Also, I've been using numpy, but also read about panda, csv and I think those libraries could be possibilities too. But like I said, been using numpy for the .dat files. I don't know if the other libraries would be easier to use?

答:
You actually don't need any additional modules for such a simple task. Pure-Python solution would be reading file line-by-line and 'parsing' them using str.split() will give you your lists, and then you can pretty much filter on any parameter. Something like:

```<code>students = {}  # store for our students by grade
with open("testdata.dat", "r") as f:  # open the file
    for line in f:  # read the file line by line
        row = line.strip().split("/")  # split the line into individual columns
        # you can now directly filter your row, or you can store the row in a list for later
        # let's split them by grade:
        grade = row[1]  # second column of our row is the grade
        # create/append the sublist in our `students` dict keyed by the grade
        students[grade] = students.get(grade, []) + [row]
# now your students dict contains all students split by grade, e.g.:
a_students = students["A"]
# [['1', 'A', '15', '13', '43214'], ['6', 'A', '16', '23', '34567']]

# if you want only to collect the A-grade student IDs, you can get a list of them as:
student_ids = [entry[0] for entry in students["A"]]
# ['1', '6']
</code>```

But let's go back a few steps - if you want a more generalized solution you should just store your list and then create a function to filter it by passed parameters, so:

```<code># define a filter function
# filters should contain a list of filters whereas a filter would be defined as:
# [position, [values]]
# and you can define as many as you want
def filter_sublists(source, filters=None):
    result = []  # store for our result
    filters = filters or []  # in case no filter is returned
    for element in source:  # go through every element of our source data
        try:
            if all(element[f[0]] in f[1] for f in filters):  # check if all our filters match
                result.append(element)  # add the element
        except IndexError:  # invalid filter position or data position, ignore
            pass
    return result  # return the result

# now we can use it to filter our data, first lets load our data:

with open("testdata.dat", "r") as f:  # open the file
    students = [line.strip().split("/") for line in f]  # store all our students as a list

# now we have all the data in the `students` list and we can filter it by any element
a_students = filter_sublists(students, [[1, ["A"]]])
# [['1', 'A', '15', '13', '43214'], ['6', 'A', '16', '23', '34567']]

# or again, if you just need the IDs:
a_student_ids = [entry[0] for entry in filter_sublists(students, [[1, ["A"]]])]
# ['1', '6']

# but you can filter by any parameter, for example:
age_15_students = filter_sublists(students, [[2, ["15"]]])
# [['1', 'A', '15', '13', '43214'], ['2', 'I', '15', '21', '58322']]

# or you can get all I-grade students aged 14 or 15:
i_students = filter_sublists(students, [[1, ["I"]], [2, ["14", "15"]]])
# [['2', 'I', '15', '21', '58322'], ['5', 'I', '14', '4', '00000']]
</code>```

Body:
I'm new to Python and been practicing with sample data I created (150 rows) of student ID numbers, grades, age, class_code, area_code, etc. What I'm trying to do with the data is not only filtered by a certain column (by grade, age, etc), but then to also create a list of a different column from that row (student ID). I've manged to find how to isolate the column I need to find the certain value by, but then can't figure out how to create that list of the values I need to return.

So here's a sample of 5 rows of the data:

1/A/15/13/43214
2/I/15/21/58322
3/C/17/89/68470
4/I/18/6/57362
5/I/14/4/00000
6/A/16/23/34567

I need a list of the 1st column (student ID), based on filtering the second column (grade)...(and eventually the 3rd column, 4th column, etc. But if I see how it looks with just the 2nd, I think I can figure out the others) Also note: I didn't use headers in the .dat file.

I figured out how to isolate/view the 2nd column.

import numpy

data = numpy.genfromtxt('/testdata.dat', delimiter='/', dtype='unicode')

grades = data[:,1]
print (grades)

to print:

['A' 'I' 'C' 'I' 'I' 'A']

But now, how can I pull just the first column's that correspond to the A's, C's, I's into separate  lists?

So I'd want to see a list, also with the commas between the integers of column 1 for the A's, C's, and I's

list from A = [1, 6]
list from C = [3]
list from I = [2, 4, 5]

Again, if I can just see how it's done with just the 2nd column, with just one of the values (say A's), I think I could figure out how to do it for B's, C's, D's, etc and probably the other columns. I just need to see one example to how the syntax would be applied and then like to play around with the rest.

Also, I've been using numpy, but also read about panda, csv and I think those libraries could be possibilities too. But like I said, been using numpy for the .dat files. I don't know if the other libraries would be easier to use?

Body:
You actually don't need any additional modules for such a simple task. Pure-Python solution would be reading file line-by-line and 'parsing' them using str.split() will give you your lists, and then you can pretty much filter on any parameter. Something like:

students = {}  # store for our students by grade
with open("testdata.dat", "r") as f:  # open the file
    for line in f:  # read the file line by line
        row = line.strip().split("/")  # split the line into individual columns
        # you can now directly filter your row, or you can store the row in a list for later
        # let's split them by grade:
        grade = row[1]  # second column of our row is the grade
        # create/append the sublist in our `students` dict keyed by the grade
        students[grade] = students.get(grade, []) + [row]
# now your students dict contains all students split by grade, e.g.:
a_students = students["A"]
# [['1', 'A', '15', '13', '43214'], ['6', 'A', '16', '23', '34567']]

# if you want only to collect the A-grade student IDs, you can get a list of them as:
student_ids = [entry[0] for entry in students["A"]]
# ['1', '6']

But let's go back a few steps - if you want a more generalized solution you should just store your list and then create a function to filter it by passed parameters, so:

# define a filter function
# filters should contain a list of filters whereas a filter would be defined as:
# [position, [values]]
# and you can define as many as you want
def filter_sublists(source, filters=None):
    result = []  # store for our result
    filters = filters or []  # in case no filter is returned
    for element in source:  # go through every element of our source data
        try:
            if all(element[f[0]] in f[1] for f in filters):  # check if all our filters match
                result.append(element)  # add the element
        except IndexError:  # invalid filter position or data position, ignore
            pass
    return result  # return the result

# now we can use it to filter our data, first lets load our data:

with open("testdata.dat", "r") as f:  # open the file
    students = [line.strip().split("/") for line in f]  # store all our students as a list

# now we have all the data in the `students` list and we can filter it by any element
a_students = filter_sublists(students, [[1, ["A"]]])
# [['1', 'A', '15', '13', '43214'], ['6', 'A', '16', '23', '34567']]

# or again, if you just need the IDs:
a_student_ids = [entry[0] for entry in filter_sublists(students, [[1, ["A"]]])]
# ['1', '6']

# but you can filter by any parameter, for example:
age_15_students = filter_sublists(students, [[2, ["15"]]])
# [['1', 'A', '15', '13', '43214'], ['2', 'I', '15', '21', '58322']]

# or you can get all I-grade students aged 14 or 15:
i_students = filter_sublists(students, [[1, ["I"]], [2, ["14", "15"]]])
# [['2', 'I', '15', '21', '58322'], ['5', 'I', '14', '4', '00000']]


问:
Ionic 2 - How to remove split panel on login page only?
I use this code in app.html, the split-pane is working beautifully. But the problem is, the pane is working for every page like login or SignUp, so please help me to prevent the split pane working for every page.</p>

```<code><ion-split-pane when="(min-width: 768px)">
<ion-menu [content]="content">
  <ion-content id="Chat">
  </ion-content>
</ion-menu>
<ion-nav [root]="rootPage" #content></ion-nav>
</ion-split-pane>
</code>```

答:
```<code>    import { Component } from '@angular/core';
    import { MenuController,IonicPage, NavController } from 'ionic-angular';

    @IonicPage()

    @Component({
      selector: 'page-signup',
      templateUrl: 'signup.html',
    })

    export class SignUp {

    constructor(public navCtrl: NavController, public menu : MenuController)
    {
       this.menu.enable(false);
       this.menu.swipeEnable(false);
    }

    ionViewWillLeave(){
    this.menu.enable(true);
    this.menu.swipeEnable(true);
    }
  }
</code>```

Hope this helps. just disable menu and swipe the menu with that splitpane automatically hides.

Body:
I use this code in app.html, the split-pane is working beautifully. But the problem is, the pane is working for every page like login or SignUp, so please help me to prevent the split pane working for every page.

<ion-split-pane when="(min-width: 768px)">
<ion-menu [content]="content">
  <ion-content id="Chat">
  </ion-content>
</ion-menu>
<ion-nav [root]="rootPage" #content></ion-nav>
</ion-split-pane>

Body:
    import { Component } from '@angular/core';
    import { MenuController,IonicPage, NavController } from 'ionic-angular';

    @IonicPage()

    @Component({
      selector: 'page-signup',
      templateUrl: 'signup.html',
    })

    export class SignUp {

    constructor(public navCtrl: NavController, public menu : MenuController)
    {
       this.menu.enable(false);
       this.menu.swipeEnable(false);
    }

    ionViewWillLeave(){
    this.menu.enable(true);
    this.menu.swipeEnable(true);
    }
  }

Hope this helps. just disable menu and swipe the menu with that splitpane automatically hides.


问:
Why are these templates ambiguous?
The book C++ Templates : The Complete Guide has an example on page 275 that I'm having trouble wrapping my head around.

Quoting excerpts from the book...

```<code>template <typename T>
class Promotion<T,T> {
  public:
    typdef T ResultT;
};

template<typename T1, typename T2>
class Promotion<Array<T1>, Array<T2> > {
  public:
    typedef Array<typename Promotion<T1,T2>::ResultT> ResultT;
};

template<typename T>
class Promotion<Array<T>, Array<T> > {
  public:
    typedef Array<typename Promotion<T,T>::ResultT> ResultT;
};
</code>```

Unfortunately, the partial specialization Promotion<Array<T1>, Array<T2> > is
  neither more nor less specialized than the partial specialization
  Promotion<T,T>. To avoid template selection ambiguity, the last partial
  specialization was added. It is more specialized than either of the previous
  two partial specializations.

Why are the first two templates ambiguous, and why does the last template solve the ambiguity issue? When I try to apply the rules I either can't figure out how it comes up with an ambiguity, or if I think I have a way for it to happen I don't know why the last template solves the problem.

答:
Maybe your confusion stems from how the relation "is more specialised than" works.  It's a partial order, not a total order -- that means that given 2 template specialisations, it's not always the case that one is more specialised than the other.

Anon's comment is right: Suppose that 3rd specialisation didn't exist, and later in your code you had:

```<code>Promotion<Array<double>, Array<double> > foo;
</code>```

(Of course you probably wouldn't actually create a variable of this empty struct type, but this is just the simplest way to force its instantiation.)

Given this declaration of foo, which of the 1st 2 specialisations would be picked?

Specialisation 1 applies, with T = Array<double>.

Specialisation 2 applies, with T1 = double, T2 = double.

Both specialisations are applicable, so we need to determine which "is more specialised than" the other, and pick that one.  How?  We will say that X is more specialised than Y if it is at least as specialised as Y, but Y is not at least as specialised as X.  Although it seems like this is just dancing around the problem, there is a clever rule that we can use to answer this new question:

X is at least as specialised as Y if, regardless of what types we assign to the template parameters of X, the resulting type could always be matched by Y.

Note that we forget about the particular types involved in the current instantiation (in this case, double) -- the "is at least as specialised as" relation is a property of the partial specialisations themselves, and doesn't depend on particular instantiations.

Can specialisation 1 always be matched by specialisation 2?  The process is a bit like algebra.  We require that for any type T, we can find types T1 and T2 such that:

```<code>Promotion<Array<T1>, Array<T2> > = Promotion<T, T>
</code>```

This implies:

```<code>Array<T1> = T
Array<T2> = T
</code>```

So the answer is no.  Looking at just the first implied result, given any type T, in general it's not possible to find a type T1 such that Array<T1> is the same type as T.  (It would work if T happened to be Array<long>, but not if T is int or char* or most other types.)

What about the other way around?  Can specialisation 2 always be matched by specialisation 1?  We require that for any types T1 and T2, we can find a type T such that:

```<code>Promotion<T, T> = Promotion<Array<T1>, Array<T2> >
</code>```

Implying:

```<code>T = Array<T1>
T = Array<T2>
</code>```

So the answer is again no.  Given any type T1, it's always possible to find a type T such that T is the same type as Array<T1> -- just literally set T = Array<T1>.  But in general the other type T2 is not constrained to be the same as T1, and if it's not (e.g. if T1 = bool but T2 = float) then it will not be possible to find a type T that is the same as both Array<T1> and Array<T2>.  So in general, it's not possible to find such a type T.

In this case, not only is neither specialisation more specialised than the other, neither is even as specialised as the other.  As a result, if the need arises to instantiate this template class and both specialisations match -- as it does in the example Anon gave -- there is no way to choose a "best" one.

Title: Why are these templates ambiguous?

Body:
The book C++ Templates : The Complete Guide has an example on page 275 that I'm having trouble wrapping my head around.

Quoting excerpts from the book...

template <typename T>
class Promotion<T,T> {
  public:
    typdef T ResultT;
};

template<typename T1, typename T2>
class Promotion<Array<T1>, Array<T2> > {
  public:
    typedef Array<typename Promotion<T1,T2>::ResultT> ResultT;
};

template<typename T>
class Promotion<Array<T>, Array<T> > {
  public:
    typedef Array<typename Promotion<T,T>::ResultT> ResultT;
};

Unfortunately, the partial specialization Promotion<Array<T1>, Array<T2> > is
  neither more nor less specialized than the partial specialization
  Promotion<T,T>. To avoid template selection ambiguity, the last partial
  specialization was added. It is more specialized than either of the previous
  two partial specializations.

Why are the first two templates ambiguous, and why does the last template solve the ambiguity issue? When I try to apply the rules I either can't figure out how it comes up with an ambiguity, or if I think I have a way for it to happen I don't know why the last template solves the problem.

Body:
Maybe your confusion stems from how the relation "is more specialised than" works.  It's a partial order, not a total order -- that means that given 2 template specialisations, it's not always the case that one is more specialised than the other.

Anon's comment is right: Suppose that 3rd specialisation didn't exist, and later in your code you had:

Promotion<Array<double>, Array<double> > foo;

(Of course you probably wouldn't actually create a variable of this empty struct type, but this is just the simplest way to force its instantiation.)

Given this declaration of foo, which of the 1st 2 specialisations would be picked?

Specialisation 1 applies, with T = Array<double>.

Specialisation 2 applies, with T1 = double, T2 = double.

Both specialisations are applicable, so we need to determine which "is more specialised than" the other, and pick that one.  How?  We will say that X is more specialised than Y if it is at least as specialised as Y, but Y is not at least as specialised as X.  Although it seems like this is just dancing around the problem, there is a clever rule that we can use to answer this new question:

X is at least as specialised as Y if, regardless of what types we assign to the template parameters of X, the resulting type could always be matched by Y.

Note that we forget about the particular types involved in the current instantiation (in this case, double) -- the "is at least as specialised as" relation is a property of the partial specialisations themselves, and doesn't depend on particular instantiations.

Can specialisation 1 always be matched by specialisation 2?  The process is a bit like algebra.  We require that for any type T, we can find types T1 and T2 such that:

Promotion<Array<T1>, Array<T2> > = Promotion<T, T>

This implies:

Array<T1> = T
Array<T2> = T

So the answer is no.  Looking at just the first implied result, given any type T, in general it's not possible to find a type T1 such that Array<T1> is the same type as T.  (It would work if T happened to be Array<long>, but not if T is int or char* or most other types.)

What about the other way around?  Can specialisation 2 always be matched by specialisation 1?  We require that for any types T1 and T2, we can find a type T such that:

Promotion<T, T> = Promotion<Array<T1>, Array<T2> >

Implying:

T = Array<T1>
T = Array<T2>

So the answer is again no.  Given any type T1, it's always possible to find a type T such that T is the same type as Array<T1> -- just literally set T = Array<T1>.  But in general the other type T2 is not constrained to be the same as T1, and if it's not (e.g. if T1 = bool but T2 = float) then it will not be possible to find a type T that is the same as both Array<T1> and Array<T2>.  So in general, it's not possible to find such a type T.

In this case, not only is neither specialisation more specialised than the other, neither is even as specialised as the other.  As a result, if the need arises to instantiate this template class and both specialisations match -- as it does in the example Anon gave -- there is no way to choose a "best" one.


问:
Why am I getting "array initializer must be an initializer list or string literal"?
I am completely new to C programming and the language I used to work on before C was Java. I am trying to get a method to return a char array and it is not working. Here is my syntax:

```<code>char * insertToArray(char * val){
    int k;
    char arr[2] = val;
    // do some other staffs here to the value
    return arr;
}

int main(){
    char s1[] = {"one", "two"};
    char newArr[];
    int i;

    for(i = 0; i < 2; i++){
        newArr[] = insertToArray(s1[i]);
    }

    return 0;
}
</code>```

All I am trying to do is pass the s1 array to insertToArray and do some kind of calculation on the values, then return a whole new single array. I am a complete beginner and I couldn't find any other help online. What am I doing wrong?

答:
The rules of C says that you can't initialize an array using a pointer. Instead define the array then copy to it:

```<code>char arr[strlen(val) + 1];  // Make sure there's enough space
strcpy(arr, val);
</code>```

Then you can not define empty arrays. An array must have a size. And using the array newArr in the main function is wrong anyway since the function you call returns a pointer. So newArr must be a pointer as well.

Now with that out of the way, there are a couple of other things in your (current) code that are very wrong.

The first being the size of the array arr. An array of two characters can only hold space for one-character string. Remember that strings are null terminated, there must be space for the full string plus the terminator.

The second problem is that you return a pointer to a local variable. Once the function insertToArray returns, all its local variables cease to exist. Having a pointer to one of those variables will lead to undefined behavior when you use it.

The fix to the first problem is shown above. The fix to the second problem is a little harder, and involves either passing an extra argument to the function or allocating memory dynamically. I recommend the extra argument way:

```<code>char * insertToArray(const char * val, char * arr){
    strcpy(val, arr);

    // do some other staffs here to the value

    return arr;
}
</code>```

Then call it like

```<code>char newArr[strlen(s1[i]) + 1];
insertToArray(s1[i], newArr);
</code>```

Body:
I am completely new to C programming and the language I used to work on before C was Java. I am trying to get a method to return a char array and it is not working. Here is my syntax:

char * insertToArray(char * val){
    int k;
    char arr[2] = val;
    // do some other staffs here to the value
    return arr;
}

int main(){
    char s1[] = {"one", "two"};
    char newArr[];
    int i;

    for(i = 0; i < 2; i++){
        newArr[] = insertToArray(s1[i]);
    }

    return 0;
}

All I am trying to do is pass the s1 array to insertToArray and do some kind of calculation on the values, then return a whole new single array. I am a complete beginner and I couldn't find any other help online. What am I doing wrong?

Body:
The rules of C says that you can't initialize an array using a pointer. Instead define the array then copy to it:

char arr[strlen(val) + 1];  // Make sure there's enough space
strcpy(arr, val);

Then you can not define empty arrays. An array must have a size. And using the array newArr in the main function is wrong anyway since the function you call returns a pointer. So newArr must be a pointer as well.

Now with that out of the way, there are a couple of other things in your (current) code that are very wrong.

The first being the size of the array arr. An array of two characters can only hold space for one-character string. Remember that strings are null terminated, there must be space for the full string plus the terminator.

The second problem is that you return a pointer to a local variable. Once the function insertToArray returns, all its local variables cease to exist. Having a pointer to one of those variables will lead to undefined behavior when you use it.

The fix to the first problem is shown above. The fix to the second problem is a little harder, and involves either passing an extra argument to the function or allocating memory dynamically. I recommend the extra argument way:

char * insertToArray(const char * val, char * arr){
    strcpy(val, arr);

    // do some other staffs here to the value

    return arr;
}

Then call it like

char newArr[strlen(s1[i]) + 1];
insertToArray(s1[i], newArr);


问:
Why doesn't the JVM emit prefetch instructions on Windows x86
As the title states, why doesn't the OpenJDK JVM emit prefetch instruction on Windows x86? See OpenJDK Mercurial @ http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/c49dcaf78a65/src/os_cpu/windows_x86/vm/prefetch_windows_x86.inline.hpp

```<code>inline void Prefetch::read (void *loc, intx interval) {}
inline void Prefetch::write(void *loc, intx interval) {}
</code>```

There are no comments and I've found no other resources besides the source code. I am asking because it does so for Linux x86, see http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/c49dcaf78a65/src/os_cpu/linux_x86/vm/prefetch_linux_x86.inline.hpp

```<code>inline void Prefetch::read (void *loc, intx interval) {
#ifdef AMD64
  __asm__ ("prefetcht0 (%0,%1,1)" : : "r" (loc), "r" (interval));
#endif // AMD64
}

inline void Prefetch::write(void *loc, intx interval) {
#ifdef AMD64

  // Do not use the 3dnow prefetchw instruction.  It isn't supported on em64t.
  //  __asm__ ("prefetchw (%0,%1,1)" : : "r" (loc), "r" (interval));
  __asm__ ("prefetcht0 (%0,%1,1)" : : "r" (loc), "r" (interval));

#endif // AMD64
}
</code>```

答:
The files you cited all has asm code fragment  (inline assembler), which is used by some C/C++ software in its own code (as apangin, the JVM expert pointed, mostly in GC code). And there is actually the difference: Linux, Solaris and BSD variants of x86_64 hotspot have prefetches in the hotspot and windows has them disabled/unimplemented which is partially  strange, partially unexplainable why, and it may also make JVM bit (some percents; more on platforms without hardware prefetch) slower on Windows, but still will not help to sell more solaris/solaris paid support contracts for Sun/Oracle.  Ross also guessed that inline asm syntax may be not supported with MS C++ compiler, but _mm_prefetch should (Who will open JDK bug to add it to the file?).

JVM hotspot is JIT, and the JITted code is emitted (generated) by JIT as bytes (while it is possible for JIT to copy code from its own functions into generated code or to emit call to the support functions, prefetches are emitted as bytes in hotspot). How can we find how it is emitted? Simple online way is to find some online searchable copy of jdk8u (or better in cross-reference like metager), for example on github: https://github.com/JetBrains/jdk8u_hotspot and do the search of prefetch or prefetch emit or prefetchr or lir_prefetchr. There are some relevant results:

Actual bytes emitted in JVM's c1 compiler / LIR in jdk8u_hotspot/src/cpu/x86/vm/assembler_x86.cpp:

```<code>void Assembler::prefetch_prefix(Address src) {
  prefix(src);
  emit_int8(0x0F);
}

void Assembler::prefetchnta(Address src) {
  NOT_LP64(assert(VM_Version::supports_sse(), "must support"));
  InstructionMark im(this);
  prefetch_prefix(src);
  emit_int8(0x18);
  emit_operand(rax, src); // 0, src
}

void Assembler::prefetchr(Address src) {
  assert(VM_Version::supports_3dnow_prefetch(), "must support");
  InstructionMark im(this);
  prefetch_prefix(src);
  emit_int8(0x0D);
  emit_operand(rax, src); // 0, src
}

void Assembler::prefetcht0(Address src) {
  NOT_LP64(assert(VM_Version::supports_sse(), "must support"));
  InstructionMark im(this);
  prefetch_prefix(src);
  emit_int8(0x18);
  emit_operand(rcx, src); // 1, src
}

void Assembler::prefetcht1(Address src) {
  NOT_LP64(assert(VM_Version::supports_sse(), "must support"));
  InstructionMark im(this);
  prefetch_prefix(src);
  emit_int8(0x18);
  emit_operand(rdx, src); // 2, src
}

void Assembler::prefetcht2(Address src) {
  NOT_LP64(assert(VM_Version::supports_sse(), "must support"));
  InstructionMark im(this);
  prefetch_prefix(src);
  emit_int8(0x18);
  emit_operand(rbx, src); // 3, src
}

void Assembler::prefetchw(Address src) {
  assert(VM_Version::supports_3dnow_prefetch(), "must support");
  InstructionMark im(this);
  prefetch_prefix(src);
  emit_int8(0x0D);
  emit_operand(rcx, src); // 1, src
}
</code>```

Usage in c1 LIR: src/share/vm/c1/c1_LIRAssembler.cpp

```<code>void LIR_Assembler::emit_op1(LIR_Op1* op) {
  switch (op->code()) {
...
    case lir_prefetchr:
      prefetchr(op->in_opr());
      break;

    case lir_prefetchw:
      prefetchw(op->in_opr());
      break;
</code>```

Now we know the opcode lir_prefetchr and can search for it or in OpenGrok xref and lir_prefetchw, to find the only example in src/share/vm/c1/c1_LIR.cpp

```<code>void LIR_List::prefetch(LIR_Address* addr, bool is_store) {
  append(new LIR_Op1(
            is_store ? lir_prefetchw : lir_prefetchr,
            LIR_OprFact::address(addr)));
}
</code>```

There are other place where prefetch instructions are defined (for C2, as noted by apangin), the src/cpu/x86/vm/x86_64.ad:

```<code>// Prefetch instructions. ...
instruct prefetchr( memory mem ) %{
  predicate(ReadPrefetchInstr==3);
  match(PrefetchRead mem);
  ins_cost(125);

  format %{ "PREFETCHR $mem\t# Prefetch into level 1 cache" %}
  ins_encode %{
    __ prefetchr($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

instruct prefetchrNTA( memory mem ) %{
  predicate(ReadPrefetchInstr==0);
  match(PrefetchRead mem);
  ins_cost(125);

  format %{ "PREFETCHNTA $mem\t# Prefetch into non-temporal cache for read" %}
  ins_encode %{
    __ prefetchnta($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

instruct prefetchrT0( memory mem ) %{
  predicate(ReadPrefetchInstr==1);
  match(PrefetchRead mem);
  ins_cost(125);

  format %{ "PREFETCHT0 $mem\t# prefetch into L1 and L2 caches for read" %}
  ins_encode %{
    __ prefetcht0($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

instruct prefetchrT2( memory mem ) %{
  predicate(ReadPrefetchInstr==2);
  match(PrefetchRead mem);
  ins_cost(125);

  format %{ "PREFETCHT2 $mem\t# prefetch into L2 caches for read" %}
  ins_encode %{
    __ prefetcht2($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

instruct prefetchwNTA( memory mem ) %{
  match(PrefetchWrite mem);
  ins_cost(125);

  format %{ "PREFETCHNTA $mem\t# Prefetch to non-temporal cache for write" %}
  ins_encode %{
    __ prefetchnta($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

// Prefetch instructions for allocation.

instruct prefetchAlloc( memory mem ) %{
  predicate(AllocatePrefetchInstr==3);
  match(PrefetchAllocation mem);
  ins_cost(125);

  format %{ "PREFETCHW $mem\t# Prefetch allocation into level 1 cache and mark modified" %}
  ins_encode %{
    __ prefetchw($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

instruct prefetchAllocNTA( memory mem ) %{
  predicate(AllocatePrefetchInstr==0);
  match(PrefetchAllocation mem);
  ins_cost(125);

  format %{ "PREFETCHNTA $mem\t# Prefetch allocation to non-temporal cache for write" %}
  ins_encode %{
    __ prefetchnta($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

instruct prefetchAllocT0( memory mem ) %{
  predicate(AllocatePrefetchInstr==1);
  match(PrefetchAllocation mem);
  ins_cost(125);

  format %{ "PREFETCHT0 $mem\t# Prefetch allocation to level 1 and 2 caches for write" %}
  ins_encode %{
    __ prefetcht0($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

instruct prefetchAllocT2( memory mem ) %{
  predicate(AllocatePrefetchInstr==2);
  match(PrefetchAllocation mem);
  ins_cost(125);

  format %{ "PREFETCHT2 $mem\t# Prefetch allocation to level 2 cache for write" %}
  ins_encode %{
    __ prefetcht2($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}
</code>```

Body:
As the title states, why doesn't the OpenJDK JVM emit prefetch instruction on Windows x86? See OpenJDK Mercurial @ http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/c49dcaf78a65/src/os_cpu/windows_x86/vm/prefetch_windows_x86.inline.hpp

inline void Prefetch::read (void *loc, intx interval) {}
inline void Prefetch::write(void *loc, intx interval) {}

There are no comments and I've found no other resources besides the source code. I am asking because it does so for Linux x86, see http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/c49dcaf78a65/src/os_cpu/linux_x86/vm/prefetch_linux_x86.inline.hpp

inline void Prefetch::read (void *loc, intx interval) {
#ifdef AMD64
  __asm__ ("prefetcht0 (%0,%1,1)" : : "r" (loc), "r" (interval));
#endif // AMD64
}

inline void Prefetch::write(void *loc, intx interval) {
#ifdef AMD64

  // Do not use the 3dnow prefetchw instruction.  It isn't supported on em64t.
  //  __asm__ ("prefetchw (%0,%1,1)" : : "r" (loc), "r" (interval));
  __asm__ ("prefetcht0 (%0,%1,1)" : : "r" (loc), "r" (interval));

#endif // AMD64
}

Body:
The files you cited all has asm code fragment  (inline assembler), which is used by some C/C++ software in its own code (as apangin, the JVM expert pointed, mostly in GC code). And there is actually the difference: Linux, Solaris and BSD variants of x86_64 hotspot have prefetches in the hotspot and windows has them disabled/unimplemented which is partially  strange, partially unexplainable why, and it may also make JVM bit (some percents; more on platforms without hardware prefetch) slower on Windows, but still will not help to sell more solaris/solaris paid support contracts for Sun/Oracle.  Ross also guessed that inline asm syntax may be not supported with MS C++ compiler, but _mm_prefetch should (Who will open JDK bug to add it to the file?).

JVM hotspot is JIT, and the JITted code is emitted (generated) by JIT as bytes (while it is possible for JIT to copy code from its own functions into generated code or to emit call to the support functions, prefetches are emitted as bytes in hotspot). How can we find how it is emitted? Simple online way is to find some online searchable copy of jdk8u (or better in cross-reference like metager), for example on github: https://github.com/JetBrains/jdk8u_hotspot and do the search of prefetch or prefetch emit or prefetchr or lir_prefetchr. There are some relevant results:

Actual bytes emitted in JVM's c1 compiler / LIR in jdk8u_hotspot/src/cpu/x86/vm/assembler_x86.cpp:

void Assembler::prefetch_prefix(Address src) {
  prefix(src);
  emit_int8(0x0F);
}

void Assembler::prefetchnta(Address src) {
  NOT_LP64(assert(VM_Version::supports_sse(), "must support"));
  InstructionMark im(this);
  prefetch_prefix(src);
  emit_int8(0x18);
  emit_operand(rax, src); // 0, src
}

void Assembler::prefetchr(Address src) {
  assert(VM_Version::supports_3dnow_prefetch(), "must support");
  InstructionMark im(this);
  prefetch_prefix(src);
  emit_int8(0x0D);
  emit_operand(rax, src); // 0, src
}

void Assembler::prefetcht0(Address src) {
  NOT_LP64(assert(VM_Version::supports_sse(), "must support"));
  InstructionMark im(this);
  prefetch_prefix(src);
  emit_int8(0x18);
  emit_operand(rcx, src); // 1, src
}

void Assembler::prefetcht1(Address src) {
  NOT_LP64(assert(VM_Version::supports_sse(), "must support"));
  InstructionMark im(this);
  prefetch_prefix(src);
  emit_int8(0x18);
  emit_operand(rdx, src); // 2, src
}

void Assembler::prefetcht2(Address src) {
  NOT_LP64(assert(VM_Version::supports_sse(), "must support"));
  InstructionMark im(this);
  prefetch_prefix(src);
  emit_int8(0x18);
  emit_operand(rbx, src); // 3, src
}

void Assembler::prefetchw(Address src) {
  assert(VM_Version::supports_3dnow_prefetch(), "must support");
  InstructionMark im(this);
  prefetch_prefix(src);
  emit_int8(0x0D);
  emit_operand(rcx, src); // 1, src
}

Usage in c1 LIR: src/share/vm/c1/c1_LIRAssembler.cpp

void LIR_Assembler::emit_op1(LIR_Op1* op) {
  switch (op->code()) {
...
    case lir_prefetchr:
      prefetchr(op->in_opr());
      break;

    case lir_prefetchw:
      prefetchw(op->in_opr());
      break;

Now we know the opcode lir_prefetchr and can search for it or in OpenGrok xref and lir_prefetchw, to find the only example in src/share/vm/c1/c1_LIR.cpp

void LIR_List::prefetch(LIR_Address* addr, bool is_store) {
  append(new LIR_Op1(
            is_store ? lir_prefetchw : lir_prefetchr,
            LIR_OprFact::address(addr)));
}

There are other place where prefetch instructions are defined (for C2, as noted by apangin), the src/cpu/x86/vm/x86_64.ad:

// Prefetch instructions. ...
instruct prefetchr( memory mem ) %{
  predicate(ReadPrefetchInstr==3);
  match(PrefetchRead mem);
  ins_cost(125);

  format %{ "PREFETCHR $mem\t# Prefetch into level 1 cache" %}
  ins_encode %{
    __ prefetchr($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

instruct prefetchrNTA( memory mem ) %{
  predicate(ReadPrefetchInstr==0);
  match(PrefetchRead mem);
  ins_cost(125);

  format %{ "PREFETCHNTA $mem\t# Prefetch into non-temporal cache for read" %}
  ins_encode %{
    __ prefetchnta($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

instruct prefetchrT0( memory mem ) %{
  predicate(ReadPrefetchInstr==1);
  match(PrefetchRead mem);
  ins_cost(125);

  format %{ "PREFETCHT0 $mem\t# prefetch into L1 and L2 caches for read" %}
  ins_encode %{
    __ prefetcht0($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

instruct prefetchrT2( memory mem ) %{
  predicate(ReadPrefetchInstr==2);
  match(PrefetchRead mem);
  ins_cost(125);

  format %{ "PREFETCHT2 $mem\t# prefetch into L2 caches for read" %}
  ins_encode %{
    __ prefetcht2($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

instruct prefetchwNTA( memory mem ) %{
  match(PrefetchWrite mem);
  ins_cost(125);

  format %{ "PREFETCHNTA $mem\t# Prefetch to non-temporal cache for write" %}
  ins_encode %{
    __ prefetchnta($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

// Prefetch instructions for allocation.

instruct prefetchAlloc( memory mem ) %{
  predicate(AllocatePrefetchInstr==3);
  match(PrefetchAllocation mem);
  ins_cost(125);

  format %{ "PREFETCHW $mem\t# Prefetch allocation into level 1 cache and mark modified" %}
  ins_encode %{
    __ prefetchw($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

instruct prefetchAllocNTA( memory mem ) %{
  predicate(AllocatePrefetchInstr==0);
  match(PrefetchAllocation mem);
  ins_cost(125);

  format %{ "PREFETCHNTA $mem\t# Prefetch allocation to non-temporal cache for write" %}
  ins_encode %{
    __ prefetchnta($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

instruct prefetchAllocT0( memory mem ) %{
  predicate(AllocatePrefetchInstr==1);
  match(PrefetchAllocation mem);
  ins_cost(125);

  format %{ "PREFETCHT0 $mem\t# Prefetch allocation to level 1 and 2 caches for write" %}
  ins_encode %{
    __ prefetcht0($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}

instruct prefetchAllocT2( memory mem ) %{
  predicate(AllocatePrefetchInstr==2);
  match(PrefetchAllocation mem);
  ins_cost(125);

  format %{ "PREFETCHT2 $mem\t# Prefetch allocation to level 2 cache for write" %}
  ins_encode %{
    __ prefetcht2($mem$$Address);
  %}
  ins_pipe(ialu_mem);
%}


问:
Get ViewGroup(Layout) of custom view
I made a custom View, called ColorPicker. I create my ColorPicker in my xml.

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

    <visuals.customview.ColorPicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
</code>```

In the ColorPicker's Constr i need a ref to my LinearLayout, but i can't find any answer here.

```<code>public ColorPicker(Context context, AttributeSet attrs) {
    super(context, attrs);

    //LinearLayout layout = ???;
}
</code>```

I tried following solutions which i read on similar questions:

```<code>getParent();
</code>```

returns null

```<code>getRootView();
</code>```

returns the ColorPicker itself

```<code>findViewByID(R.id.linearlayout_settings);
</code>```

returns null

Thank's in advance

答:
The problem is that you're calling getParent() inside your View's constructor, at that point the View has not been attached to the parent. If you want to get the parent and be sure it is not null, override your custom View's protected void onAttachedToWindow()

```<code>public class ColorPicker extends View {

    public ColorPicker(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        // call getParent() here
    }
}
</code>```

Title: Get ViewGroup(Layout) of custom view

Body:
I made a custom View, called ColorPicker. I create my ColorPicker in my xml.

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

    <visuals.customview.ColorPicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

In the ColorPicker's Constr i need a ref to my LinearLayout, but i can't find any answer here.

public ColorPicker(Context context, AttributeSet attrs) {
    super(context, attrs);

    //LinearLayout layout = ???;
}

I tried following solutions which i read on similar questions:

getParent();

returns null

getRootView();

returns the ColorPicker itself

findViewByID(R.id.linearlayout_settings);

returns null

Thank's in advance

Body:
The problem is that you're calling getParent() inside your View's constructor, at that point the View has not been attached to the parent. If you want to get the parent and be sure it is not null, override your custom View's protected void onAttachedToWindow()

public class ColorPicker extends View {

    public ColorPicker(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        // call getParent() here
    }
}


问:
bash: oneliner to convert hex numbers in output to decimals
Does anyone know of a oneliner into which some output can be piped into in bash, to match and convert all occurrences of hexadecimal numbers and leave all other text untouched?

maybe match rather arbitrary output which could be a hexadecimal
shall somehow converted through a regexp, i.e.
/(0x)?[0-9a-fA-F]{5,}/

a leading 0x shall not be neccessary, but
also be handled properly

there can be false-positives, if not
specifying a minimum length of the numbers, but that should not be an
issue

the goal is to find solution which can be used with as much possible outputs having hex numbers in them

It should work on output like:

```<code>ssg sjas # cat /proc/net/stat/arp_cache | column -t
entries   allocs    destroys  hash_grows  lookups   hits      res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
0000000d  00000006  00000004  00000000    0000c3b9  0000c35e  00000000    00000000          00000000          0000965b          00000000        00000000             00000000
0000000d  0000000d  00000004  00000001    00000000  00000000  00000000    00000000          00000000          000007cd          00000000        00000000             00000000
0000000d  00000008  00000008  00000001    00000000  00000000  00000000    00000000          00000000          000006e0          00000000        00000000             00000000
0000000d  0000000a  00000008  00000000    00000000  00000000  00000002    00000000          00000000          00000704          00000000        00000000             00000000
</code>```

Most other questions on stackoverflow only tackle the issue of how to convert single numbers between number systems, only do the conversion for a specified column or completely kill the formatting being present in the input.

Desired output should look like: (column -t is there anyway, it really just need to replace the hex values it can find, and adding leading zeroes to a printf statement is also not a problem)

```<code>ssg sjas # cat /proc/net/stat/arp_cache | perl -pe 's/(?:0x)?[0-9a-f]{5,}/hex($&)/ge' | column -t
entries  allocs  destroys  hash_grows  lookups  hits   res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
13       6       4         0           50105    50014  0           0                 0                 38491             0               0                    0
13       13      4         1           0        0      0           0                 0                 1997              0               0                    0
13       8       8         1           0        0      0           0                 0                 1760              0               0                    0
13       10      8         0           0        0      2           0                 0                 1796              0               0                    0
</code>```

I could not find a short viable/reliable solution via sed/awk/perl in the last two hours, so I came here for help.

答:
Sorry for the confusion.  Here's a one-liner that uses that feature of bash:</p>

```<code>cat /proc/net/stat/arp_cache | sed -e '2,$s/\s*\([0-9a-f][0-9a-f]*\)\s*/ \$\(\( 0x\1 \)\) /g' -e 's/^/echo /' | bash | column -t
entries  allocs  destroys  hash_grows  lookups  hits  res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
8        2       0         0           0        0     0           0                 0                 0                 0               0                    0
8        0       0         0           211      58    0           0                 0                 0                 0               0                    0
8        2       0         0           6319     1677  0           0                 0                 3882              0               0                    0
8        4       0         0           4731     1299  0           0                 0                 0                 0               0                    0
</code>```

Body:
Does anyone know of a oneliner into which some output can be piped into in bash, to match and convert all occurrences of hexadecimal numbers and leave all other text untouched?

maybe match rather arbitrary output which could be a hexadecimal
shall somehow converted through a regexp, i.e.
/(0x)?[0-9a-fA-F]{5,}/

a leading 0x shall not be neccessary, but
also be handled properly

there can be false-positives, if not
specifying a minimum length of the numbers, but that should not be an
issue

the goal is to find solution which can be used with as much possible outputs having hex numbers in them

It should work on output like:

ssg sjas # cat /proc/net/stat/arp_cache | column -t
entries   allocs    destroys  hash_grows  lookups   hits      res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
0000000d  00000006  00000004  00000000    0000c3b9  0000c35e  00000000    00000000          00000000          0000965b          00000000        00000000             00000000
0000000d  0000000d  00000004  00000001    00000000  00000000  00000000    00000000          00000000          000007cd          00000000        00000000             00000000
0000000d  00000008  00000008  00000001    00000000  00000000  00000000    00000000          00000000          000006e0          00000000        00000000             00000000
0000000d  0000000a  00000008  00000000    00000000  00000000  00000002    00000000          00000000          00000704          00000000        00000000             00000000

Most other questions on stackoverflow only tackle the issue of how to convert single numbers between number systems, only do the conversion for a specified column or completely kill the formatting being present in the input.

Desired output should look like: (column -t is there anyway, it really just need to replace the hex values it can find, and adding leading zeroes to a printf statement is also not a problem)

ssg sjas # cat /proc/net/stat/arp_cache | perl -pe 's/(?:0x)?[0-9a-f]{5,}/hex($&)/ge' | column -t
entries  allocs  destroys  hash_grows  lookups  hits   res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
13       6       4         0           50105    50014  0           0                 0                 38491             0               0                    0
13       13      4         1           0        0      0           0                 0                 1997              0               0                    0
13       8       8         1           0        0      0           0                 0                 1760              0               0                    0
13       10      8         0           0        0      2           0                 0                 1796              0               0                    0

I could not find a short viable/reliable solution via sed/awk/perl in the last two hours, so I came here for help.

Body:
Sorry for the confusion.  Here's a one-liner that uses that feature of bash:

cat /proc/net/stat/arp_cache | sed -e '2,$s/\s*\([0-9a-f][0-9a-f]*\)\s*/ \$\(\( 0x\1 \)\) /g' -e 's/^/echo /' | bash | column -t
entries  allocs  destroys  hash_grows  lookups  hits  res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
8        2       0         0           0        0     0           0                 0                 0                 0               0                    0
8        0       0         0           211      58    0           0                 0                 0                 0               0                    0
8        2       0         0           6319     1677  0           0                 0                 3882              0               0                    0
8        4       0         0           4731     1299  0           0                 0                 0                 0               0                    0


问:
Summing binary numbers representing fractions in Sagemath
I'm just starting to learn how to code in Sagemath, I know it's similar to python but I don't have much experience with that either.

I'm trying to add two binary numbers representing fractions. That is, something like

```<code>a = '110'
b = '011'
bin(int(a,2) + int(b,2))
</code>```

But using values representing fractions, such as '1.1'.

Thanks in advance!

答:
If you want to do this in vanilla Python, parsing the binary fractions by hand isn't too bad (the first part being from this answer);</p>

```<code>def binstr_to_float(s):
    t = s.split('.')
    return int(t[0], 2) + int(t[1], 2) / 2.**len(t[1])

def float_to_binstr(f):
    i = 0
    while int(f) != f:
        f *= 2
        i += 1
    as_str = str(bin(int(f)))
    if i == 0:
        return as_str[2:]
    return as_str[2:-i] + '.' + as_str[-i:]

float_to_binstr(parse_bin('11.1') + parse_bin('0.111'))  # is '100.011'
</code>```

Body:
I'm just starting to learn how to code in Sagemath, I know it's similar to python but I don't have much experience with that either.

I'm trying to add two binary numbers representing fractions. That is, something like

a = '110'
b = '011'
bin(int(a,2) + int(b,2))

But using values representing fractions, such as '1.1'.

Thanks in advance!

Body:
If you want to do this in vanilla Python, parsing the binary fractions by hand isn't too bad (the first part being from this answer);

def binstr_to_float(s):
    t = s.split('.')
    return int(t[0], 2) + int(t[1], 2) / 2.**len(t[1])

def float_to_binstr(f):
    i = 0
    while int(f) != f:
        f *= 2
        i += 1
    as_str = str(bin(int(f)))
    if i == 0:
        return as_str[2:]
    return as_str[2:-i] + '.' + as_str[-i:]

float_to_binstr(parse_bin('11.1') + parse_bin('0.111'))  # is '100.011'


问:
Alternative way to access environment variables in Node.js
I'm trying to store production db and email passwords on environment variables to hide to GitHub users.

I set up my vars using export command on terminal:

$ export DB_PASS=mydbpass

But I can't access via process.env.DB_PASS

I'm not sure this is the correct way. I saw that is possible to access by running:

DB_PASS=mydbpass node server.js

But I'm looking for a more practical way to do this.

答:
Here's a practical way to do this.

First of all, you have ti understand that you have to execute shell file to pass data to Node's process objects, i.e, Environment variables.

Ok, so let's create a shell file where you will store all the env variables. Like this,

```<code>#!/usr/bin/env bash
export NODE_ENV='development'
export ENVIRONMENT='development'

export PORT='4000'
export TEST_PORT='4040'

# MongoDB
export MONGO_URL='mongodb://localhost:27017/test'
</code>```

Let's name this file env.sh.

Now let's say your node app is testApp  and you run your app by running npm start, so this is what you need to do now:

```<code>testApp~$ . ./env.sh && npm start
</code>```

What above command is doing, it's running your config shell file and then your node app, so in your node app you can access these fields:

```<code>process.env.PORT
process.env.TEST_PORT // and so on, basically whatever you have in env.sh file
</code>```

I hope everything's clear. Let me know in case of any clarification.

Body:
Here's a practical way to do this.

First of all, you have ti understand that you have to execute shell file to pass data to Node's process objects, i.e, Environment variables.

Ok, so let's create a shell file where you will store all the env variables. Like this,

#!/usr/bin/env bash
export NODE_ENV='development'
export ENVIRONMENT='development'

export PORT='4000'
export TEST_PORT='4040'

# MongoDB
export MONGO_URL='mongodb://localhost:27017/test'

Let's name this file env.sh.

Now let's say your node app is testApp  and you run your app by running npm start, so this is what you need to do now:

testApp~$ . ./env.sh && npm start

What above command is doing, it's running your config shell file and then your node app, so in your node app you can access these fields:

process.env.PORT
process.env.TEST_PORT // and so on, basically whatever you have in env.sh file

I hope everything's clear. Let me know in case of any clarification.


问:
How to create a list from another list according to a function?
I would like to create a list which has values which correspond to another list.
For example if I had:

```<code>listA = [1, 2, 3, 4, 5,...]
</code>```

and I would like to create another list which is the same, except all the values were varied according to x^2 (or any other function), giving:

```<code>listB = [1, 4, 9, 16,25, ...]
</code>```

I have already tried to do this by doing a while loop:

```<code>listA = [1, 2, 3, 4]
listB = range(1, 4, 1)
i = 0
while i <= 4:
    listB [i] = (listA [i]) ** 2
    i = i + 1
print listA
print listB
</code>```

But it just spits out an error message:

```<code>Traceback (most recent call last):
  File "/home/tim/Desktop/Python/test.py", line 5, in <module>
    listB [i] = (listA [i]) ** 2
IndexError: list assignment index out of range
</code>```

Any advice?
Thanks

答:
You can use a list comprehension:

```<code>listA = [1, 2, 3, 4]

listB = [x**2 for x in listA]
</code>```

Or a normal loop:

```<code>listA = [1, 2, 3, 4]

listB = []
for x in listA:
    listB.append(x**2)
</code>```

Body:
I would like to create a list which has values which correspond to another list.
For example if I had:

listA = [1, 2, 3, 4, 5,...]

and I would like to create another list which is the same, except all the values were varied according to x^2 (or any other function), giving:

listB = [1, 4, 9, 16,25, ...]

I have already tried to do this by doing a while loop:

listA = [1, 2, 3, 4]
listB = range(1, 4, 1)
i = 0
while i <= 4:
    listB [i] = (listA [i]) ** 2
    i = i + 1
print listA
print listB

But it just spits out an error message:

Traceback (most recent call last):
  File "/home/tim/Desktop/Python/test.py", line 5, in <module>
    listB [i] = (listA [i]) ** 2
IndexError: list assignment index out of range

Any advice?
Thanks

Body:
You can use a list comprehension:

listA = [1, 2, 3, 4]

listB = [x**2 for x in listA]

Or a normal loop:

listA = [1, 2, 3, 4]

listB = []
for x in listA:
    listB.append(x**2)