问:
Filter only parameters that are present in the request
There are lots of articles that are about Java 8 lambda operations however I couldn't find what I need until now. I tried to convert them to my approach unfortunately I couldn't succeed

Imagine that you have request that comes in POJO such as ;

```<code>public class DummyRequest {

    private String name;
    private String surname;
    private String country;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country= country;
    }

}
</code>```

During REST/SOAP request surname variable will be assigned as null.

```<code>List<Person> persons = Arrays.asList(
                new Person("maria", "gambert", "italy"),
                new Person("jack", "johson", "usa"),
                new Person("johnson", "jack", "usa"),
                new Person("kate", "julia", "spain"),
                new Person("jack","bob","uk");

DummyRequest dr = new DummyRequest();
dr.setName("jack");
dr.setCountry("usa");
</code>```

If I knew in advance that the surname field would be null, I could manage to filter the list like this, ignoring that field:

```<code>List<Person> result4 = persons.stream().
filter(x -> dummyRequest.getName().equals(x.getName())).
filter( x-> dummyRequest.getCountry().equals(x.getCountry())).
collect(Collectors.toList());
</code>```

However I don't know which fields will be null and which will not. How could I instead filter my data according to non-null request parameters only?

答:
You could create a checkNonNullProperties helper method that returns a Predicate<Person> that only checks for equality of non-null properties of your DummyRequest instance. You could use it as follows:

```<code>Predicate<Person> condition = checkNonNullProperties(
    Arrays.asList(
        dr.getCountry(),
        dr.getName(),
        dr.getSurname()),
    Arrays.asList(
        Person::getCountry,
        Person::getName,
        Person::getSurname));

List<Person> result = people.stream()
    .filter(condition)
    .collect(Collectors.toList());
</code>```

The helper method:

```<code>private static <T> Predicate<T> checkNonNullProperties(
        List<?> values,
        List<Function<T, ?>> extractors) {
    return IntStream.range(0, values.size()).mapToObj(i ->
            (Predicate<T>) t -> {
                Object value = values.get(i);
                Object property = extractors.get(i).apply(t);
                return value == null || value.equals(property);
            })
            .reduce(t -> true, Predicate::and);
}
</code>```

The checkNonNullProperties method receives a list of values to check for equality and a list of functions that will extract the properties from the argument of the returned predicate. The extracted properties will be checked for equality against their corresponding values only for those values that are non-null.

I'm using an IntStream to drive iteration over both lists. In the mapToObj method I'm mapping the stream's int value to a predicate that returns true when the provided value is null or when it's equal to the extracted property.

In the end, these predicates are reduced to a final predicate via the Predicate::and operator. In the reduce call, I'm providing the identity predicate for the AND operator, which is t -> true (always returns true).

Body:
There are lots of articles that are about Java 8 lambda operations however I couldn't find what I need until now. I tried to convert them to my approach unfortunately I couldn't succeed

Imagine that you have request that comes in POJO such as ;

public class DummyRequest {

    private String name;
    private String surname;
    private String country;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country= country;
    }

}

During REST/SOAP request surname variable will be assigned as null.

List<Person> persons = Arrays.asList(
                new Person("maria", "gambert", "italy"),
                new Person("jack", "johson", "usa"),
                new Person("johnson", "jack", "usa"),
                new Person("kate", "julia", "spain"),
                new Person("jack","bob","uk");

DummyRequest dr = new DummyRequest();
dr.setName("jack");
dr.setCountry("usa");

If I knew in advance that the surname field would be null, I could manage to filter the list like this, ignoring that field:

List<Person> result4 = persons.stream().
filter(x -> dummyRequest.getName().equals(x.getName())).
filter( x-> dummyRequest.getCountry().equals(x.getCountry())).
collect(Collectors.toList());

However I don't know which fields will be null and which will not. How could I instead filter my data according to non-null request parameters only?

Body:
You could create a checkNonNullProperties helper method that returns a Predicate<Person> that only checks for equality of non-null properties of your DummyRequest instance. You could use it as follows:

Predicate<Person> condition = checkNonNullProperties(
    Arrays.asList(
        dr.getCountry(),
        dr.getName(),
        dr.getSurname()),
    Arrays.asList(
        Person::getCountry,
        Person::getName,
        Person::getSurname));

List<Person> result = people.stream()
    .filter(condition)
    .collect(Collectors.toList());

The helper method:

private static <T> Predicate<T> checkNonNullProperties(
        List<?> values,
        List<Function<T, ?>> extractors) {
    return IntStream.range(0, values.size()).mapToObj(i ->
            (Predicate<T>) t -> {
                Object value = values.get(i);
                Object property = extractors.get(i).apply(t);
                return value == null || value.equals(property);
            })
            .reduce(t -> true, Predicate::and);
}

The checkNonNullProperties method receives a list of values to check for equality and a list of functions that will extract the properties from the argument of the returned predicate. The extracted properties will be checked for equality against their corresponding values only for those values that are non-null.

I'm using an IntStream to drive iteration over both lists. In the mapToObj method I'm mapping the stream's int value to a predicate that returns true when the provided value is null or when it's equal to the extracted property.

In the end, these predicates are reduced to a final predicate via the Predicate::and operator. In the reduce call, I'm providing the identity predicate for the AND operator, which is t -> true (always returns true).


来源: stackexchange

问:
Regarding union and multiple integer values
I'm getting into C and I experimented with union. My code is the following:

```<code>#include <stdio.h>

union date {
 int year  ;
 char month;
 char day  ;
 };

int main() {
 union date birth;
 birth.year = 1984;
 birth.month = 7;
 birth.day = 28;
 printf("%d, %d, %d\n",birth.year, birth.month, birth.day);
 // return 1820,28,28
 return 0;
}
</code>```

1984 is written in binary as 0111 1100 0000

7 is written in binary as 0110

28 is written in binary as 0001 1100

I understand that because of union, birth.year has the value of 0111 0001 1100 which is 1820. But I do not understand why does birth.month return as value 28.

答:
I think you've misunderstood the purpose of a union. If you want an object that stores a set of properties (e.g. d.year, d.month, d.day), you need a struct.

Unions, in short, let you put one of a number of different types within a single variable. Say for example that you're implementing a filesystem. Let's say you want a variable current_block that can refer to either a super block or a data block, defined by struct super_block and struct data_block respectively. Then you could do:

```<code>union block_generic{
    struct super_block;
    struct data_block;
}

union block_generic current_block;
</code>```

Now current_block can be either a super_block or a data_block.

EDIT: Just wanted to add a quick addendum about the actual usage of unions. Continuing the above example, to treat current_block as a super block, e.g., in order to access the filesystem's number of inodes, you would do current_block.super_block.n_inodes (what I mean to point out is that you don't give direct treatment to the union variable, you specify which "type hat," so to speak, it should wear.

ContentLicense: CC BY-SA 3.0

Body:
I'm getting into C and I experimented with union. My code is the following:

#include <stdio.h>

union date {
 int year  ;
 char month;
 char day  ;
 };

int main() {
 union date birth;
 birth.year = 1984;
 birth.month = 7;
 birth.day = 28;
 printf("%d, %d, %d\n",birth.year, birth.month, birth.day);
 // return 1820,28,28
 return 0;
}

1984 is written in binary as 0111 1100 0000

7 is written in binary as 0110

28 is written in binary as 0001 1100

I understand that because of union, birth.year has the value of 0111 0001 1100 which is 1820. But I do not understand why does birth.month return as value 28.

Body:
I think you've misunderstood the purpose of a union. If you want an object that stores a set of properties (e.g. d.year, d.month, d.day), you need a struct.

Unions, in short, let you put one of a number of different types within a single variable. Say for example that you're implementing a filesystem. Let's say you want a variable current_block that can refer to either a super block or a data block, defined by struct super_block and struct data_block respectively. Then you could do:

union block_generic{
    struct super_block;
    struct data_block;
}

union block_generic current_block;

Now current_block can be either a super_block or a data_block.

EDIT: Just wanted to add a quick addendum about the actual usage of unions. Continuing the above example, to treat current_block as a super block, e.g., in order to access the filesystem's number of inodes, you would do current_block.super_block.n_inodes (what I mean to point out is that you don't give direct treatment to the union variable, you specify which "type hat," so to speak, it should wear.


问:
Passing arrays to functions by their names in C
I'm declaring a global variable in my program:

```<code>double mat[3200][3200];
</code>```

when passing this array to fwrite() by using the variable's name as argument, I get stack overflow thrown at runtime.

```<code>fwrite(mat, sizeof(double), 3200*3200, fid);
</code>```

Why is that? Shouldn't the compiler replace the variable mat with a pointer to its first element?

I've read here and here, and still can't understand.

答:
A stack overflow error could be due to either an infinite recursion (unlikely in your example) or too much data passed on the stack (parameters). It seems your array is passed by copy, not by adress.

You can try to replace the call by

```<code>fwrite(&(mat[0][0]), sizeof(double), 3200*3200, fid);
</code>```

A static array is not a pointer.

ContentLicense: CC BY-SA 2.5

Body:
I'm declaring a global variable in my program:

double mat[3200][3200];

when passing this array to fwrite() by using the variable's name as argument, I get stack overflow thrown at runtime.

fwrite(mat, sizeof(double), 3200*3200, fid);

Why is that? Shouldn't the compiler replace the variable mat with a pointer to its first element?

I've read here and here, and still can't understand.

Body:
A stack overflow error could be due to either an infinite recursion (unlikely in your example) or too much data passed on the stack (parameters). It seems your array is passed by copy, not by adress.

You can try to replace the call by

fwrite(&(mat[0][0]), sizeof(double), 3200*3200, fid);

A static array is not a pointer.


问:
MySQL do where on more than one field
I want to do a WHERE on more than one field. And it also has to be in between two numbers. I think you can understand it more by looking at the code:

```<code>SELECT * FROM locations WHERE(lat BETWEEN 8 AND 100) AND WHERE(lng BETWEEN 1 AND 4)
</code>```

Thanks for any responses

答:
You are almost there, just that you don't need to use WHERE twice, e.g.:

```<code>SELECT *
FROM locations
WHERE lat BETWEEN 8 AND 100
AND lng BETWEEN 1 AND 4;
</code>```

Title: MySQL do where on more than one field

Body:
I want to do a WHERE on more than one field. And it also has to be in between two numbers. I think you can understand it more by looking at the code:

SELECT * FROM locations WHERE(lat BETWEEN 8 AND 100) AND WHERE(lng BETWEEN 1 AND 4)

Thanks for any responses

Body:
You are almost there, just that you don't need to use WHERE twice, e.g.:

SELECT *
FROM locations
WHERE lat BETWEEN 8 AND 100
AND lng BETWEEN 1 AND 4;


问:
How to submit object graph in a WebAPI action using Entity Framework
I'm developing a WebAPI v2 action method to persist updates to an object graph using Entity Framework 6 and I'm a little unsure I've got the right syntax. Project is my root type which contains a collection of Question's. The Project will already exist but the Post action may need to submit changes to the Project properties, changes to existing Question's and add new Question's.

The code I have is shown and commented below but the update requires a lot of work when I'd like to think there's a helper method that can do some of this for me:

```<code>[System.Web.Http.Route("{id:int}")]
public HttpResponseMessage Post(int id, [FromBody]Project project)
{
    // Validate the submitted project
    if (!ModelState.IsValid)
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);

    // Fetch the existing project. This is here to perform row-level
    // security check. The user will have logged on and this confirms the
    // organisation they work for. Behind the scenes I will compound the
    // query below to include a check for organisation id. This prevents
    // users submitted any project id and overwriting data that isn't theirs.
    // Would it make the pattern below better if this only executed a .Count()?
    // Would that mean the context would then be tracking the project before
    // the update?
    var existingProject = _context.Projects.Include("Questions").FirstOrDefault(p => p.ProjectId == id);
    if (existingProject == null)
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, ModelState);

    // Copy model updates to the project
    var projectEntry = _context.Entry(existingProject);
    projectEntry.CurrentValues.SetValues(project);

    // Now work out which questions are updates or additions
    foreach (var question in project.Questions)
    {
        // No id so must be an addition
        if (question.QuestionId == 0)
        {
            existingProject.Questions.Add(question);
        }
        else
        {
            // Fetch the existing question so we can copy values
            var existingQuestion = existingProject.Questions.FirstOrDefault(q => q.QuestionId == question.QuestionId);
            if (existingQuestion == null)
            {
                // In a single user system finding ourselves here should not
                // be possible. Ideally we'll need to do some concurrency
                // when other users make updates or have some record locking
                // mechanism.
                existingProject.Questions.Add(question);
            }
            else
            {
                var questionEntry = _context.Entry(existingQuestion);
                questionEntry.CurrentValues.SetValues(question);
            }
        }
    }

    _context.SaveChanges();

    return Request.CreateResponse(HttpStatusCode.Created, project);
}
</code>```

Update : I've also realised after submitting this that I'm not even dealing with deleting Question's yet which, looking at my solution above, will not currently be catered for so I would appreciate that being considered too.

答:
Looks like you're looking for Trackable-Entities, here its wiki headline:

Trackable Entities supports tracking changes to entities in an object graph, so that they can be sent to a web service and persisted in a single round trip and within a single transaction.  This functionality is provided as a set of NuGet packages.

The server-side NuGet packages provide an ApplyChanges extension method to Entity Framework's DbContext class, which traverses one or more object graphs, informing Entity Framework of each entity's change state.  After calling SaveChanges, you can then call AcceptChanges to set the state of all entities to Unchanged before returning them to the client.  There is also a LoadRelatedEntities method which you can call to populate reference properties on added entities.

The client-side packages provide a change-tracker for marking entities as Added, Modified or Deleted whenever they are inserted, modified or removed at any level in an object graph.  To start tracking changes, simply add one or more entities to a ChangeTrackingCollection and set the Tracking property to true.  When you want to persist changes, you can call GetChanges on the change tracker to get only changed items, so that unchanged entities need not be sent to the server, saving bandwidth and increasing performance.  Trackable Entities will correlate entities so that you can merge updated entities back into the original object graph by calling MergeChanges.  While you can certainly set TrackingState on entities manually, the change tracker is deployed as a portable class library, so you can use it from any .NET client, including desktop or mobile applications.

Another project to consider is Breeze#.

Body:
I'm developing a WebAPI v2 action method to persist updates to an object graph using Entity Framework 6 and I'm a little unsure I've got the right syntax. Project is my root type which contains a collection of Question's. The Project will already exist but the Post action may need to submit changes to the Project properties, changes to existing Question's and add new Question's.

The code I have is shown and commented below but the update requires a lot of work when I'd like to think there's a helper method that can do some of this for me:

[System.Web.Http.Route("{id:int}")]
public HttpResponseMessage Post(int id, [FromBody]Project project)
{
    // Validate the submitted project
    if (!ModelState.IsValid)
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);

    // Fetch the existing project. This is here to perform row-level
    // security check. The user will have logged on and this confirms the
    // organisation they work for. Behind the scenes I will compound the
    // query below to include a check for organisation id. This prevents
    // users submitted any project id and overwriting data that isn't theirs.
    // Would it make the pattern below better if this only executed a .Count()?
    // Would that mean the context would then be tracking the project before
    // the update?
    var existingProject = _context.Projects.Include("Questions").FirstOrDefault(p => p.ProjectId == id);
    if (existingProject == null)
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, ModelState);

    // Copy model updates to the project
    var projectEntry = _context.Entry(existingProject);
    projectEntry.CurrentValues.SetValues(project);

    // Now work out which questions are updates or additions
    foreach (var question in project.Questions)
    {
        // No id so must be an addition
        if (question.QuestionId == 0)
        {
            existingProject.Questions.Add(question);
        }
        else
        {
            // Fetch the existing question so we can copy values
            var existingQuestion = existingProject.Questions.FirstOrDefault(q => q.QuestionId == question.QuestionId);
            if (existingQuestion == null)
            {
                // In a single user system finding ourselves here should not
                // be possible. Ideally we'll need to do some concurrency
                // when other users make updates or have some record locking
                // mechanism.
                existingProject.Questions.Add(question);
            }
            else
            {
                var questionEntry = _context.Entry(existingQuestion);
                questionEntry.CurrentValues.SetValues(question);
            }
        }
    }

    _context.SaveChanges();

    return Request.CreateResponse(HttpStatusCode.Created, project);
}

Update : I've also realised after submitting this that I'm not even dealing with deleting Question's yet which, looking at my solution above, will not currently be catered for so I would appreciate that being considered too.


问:
Starting different activities from MainActivity
I'm new here and I think I have made a mistake in Java but I have no idea how to correct it. Most of the people with similar issue had much more complicated projects and I couldn't resolve my issue by looking at their code.

I want to use different buttons (9 of them) to start different activities, but when I started with adding the second, only the activity 1 (LeftArmActivity) popped up. Whatever I changed in the XML to call the proper method for HeadActivity to launch, only the LeftActivity launches. I've got a hint from other topics that it may be caused by overwriting of the intent, but I have no idea how to fix this. I tried to use getActivity() but it just crashed. Could you please help me with this?

@UPDATE

Okay, I used the switch recommended below, but now the app won't start at all :/

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

Context context = this;
Button LeftArmOpener = (Button) findViewById(R.id.LeftArmOpener);
Button HeadOpener = (Button) findViewById(R.id.HeadOpener);
Button RightArmOpener = (Button) findViewById(R.id.RightArmOpener);
Button CreditsOpener = (Button) findViewById(R.id.CreditsOpener);
Button TrunkOpener = (Button) findViewById(R.id.TrunkOpener);
Button NextOpener = (Button) findViewById(R.id.NextOpener);
Button RightLegOpener = (Button) findViewById(R.id.RightLegOpener);
Button ExitOpener = (Button) findViewById(R.id.ExitOpener);
Button LeftLegOpener = (Button) findViewById(R.id.LeftLegOpener);

protected View.OnClickListener mClick;

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

    mClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.RightArmOpener: {
                    Intent i1 = new Intent(context, LeftArmActivity.class);
                    startActivity(i1);
                    break;
                }
                case R.id.HeadOpener: {
                    Intent i2 = new Intent(context, HeadActivity.class);
                    startActivity(i2);
                    break;
                }
                case R.id.LeftArmOpener: {
                    Intent i3 = new Intent(context, LeftArmActivity.class);
                    startActivity(i3);
                    break;
                }
                case R.id.CreditsOpener: {
                    Intent i4 = new Intent(context, CreditsActivity.class);
                    startActivity(i4);
                    break;
                }
                case R.id.TrunkOpener: {
                    Intent i5 = new Intent(context, TrunkActivity.class);
                    startActivity(i5);
                    break;
                }
                case R.id.NextOpener: {
                    Intent i6 = new Intent(context, NextActivity.class);
                    startActivity(i6);
                    break;
                }
                case R.id.RightLegOpener: {
                    Intent i7 = new Intent(context, RightLegActivity.class);
                    startActivity(i7);
                    break;
                }
                case R.id.ExitOpener: {
                    Intent i8 = new Intent(context, ExitActivity.class);
                    startActivity(i8);
                    break;
                }
                case R.id.LeftLegOpener: {
                    Intent i9 = new Intent(context, LeftLegActivity.class);
                    startActivity(i9);
                    break;
                }
                //create this for all 9 buttons
            }

        }

    };

    LeftArmOpener.setOnClickListener(mClick);
    HeadOpener.setOnClickListener(mClick);
    RightArmOpener.setOnClickListener(mClick);
    CreditsOpener.setOnClickListener(mClick);
    TrunkOpener.setOnClickListener(mClick);
    NextOpener.setOnClickListener(mClick);
    RightLegOpener.setOnClickListener(mClick);
    ExitOpener.setOnClickListener(mClick);
    LeftLegOpener.setOnClickListener(mClick);

}
</code>```

}

答:
You said you have 9 buttons so i think u should use switch case in such scenarios see the following code:-

Here is how my Button looks in xml no android:onClick is used here

```<code>    <Button
    android:id="@+id/btn1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Button 1" />
</code>```

This part goes in Activity:-

```<code>    Context context = this;
    Button btn1 = (Button) findViewById(R.id.btn1);
    Button btn2 = (Button) findViewById(R.id.btn2);
    Button btn9 = (Button) findViewById(R.id.btn9);

    btn1.setOnClickListener(mClick);
    btn2.setOnClickListener(mClick);
    btn9.setOnClickListener(mClick);

View.OnClickListener mClick = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1: {
                Intent i1 = new Intent(context, First.class);
                startActivity(i1);
                break;
            }
            case R.id.btm2: {
                Intent i2 = new Intent(context, Second.class);
                startActivity(i2);
                break;
            }
            //create this for all 9 buttons
        }

    }
};
</code>```

Body:
I'm new here and I think I have made a mistake in Java but I have no idea how to correct it. Most of the people with similar issue had much more complicated projects and I couldn't resolve my issue by looking at their code.

I want to use different buttons (9 of them) to start different activities, but when I started with adding the second, only the activity 1 (LeftArmActivity) popped up. Whatever I changed in the XML to call the proper method for HeadActivity to launch, only the LeftActivity launches. I've got a hint from other topics that it may be caused by overwriting of the intent, but I have no idea how to fix this. I tried to use getActivity() but it just crashed. Could you please help me with this?

@UPDATE

Okay, I used the switch recommended below, but now the app won't start at all :/

 public class MainActivity extends AppCompatActivity {

Context context = this;
Button LeftArmOpener = (Button) findViewById(R.id.LeftArmOpener);
Button HeadOpener = (Button) findViewById(R.id.HeadOpener);
Button RightArmOpener = (Button) findViewById(R.id.RightArmOpener);
Button CreditsOpener = (Button) findViewById(R.id.CreditsOpener);
Button TrunkOpener = (Button) findViewById(R.id.TrunkOpener);
Button NextOpener = (Button) findViewById(R.id.NextOpener);
Button RightLegOpener = (Button) findViewById(R.id.RightLegOpener);
Button ExitOpener = (Button) findViewById(R.id.ExitOpener);
Button LeftLegOpener = (Button) findViewById(R.id.LeftLegOpener);

protected View.OnClickListener mClick;

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

    mClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.RightArmOpener: {
                    Intent i1 = new Intent(context, LeftArmActivity.class);
                    startActivity(i1);
                    break;
                }
                case R.id.HeadOpener: {
                    Intent i2 = new Intent(context, HeadActivity.class);
                    startActivity(i2);
                    break;
                }
                case R.id.LeftArmOpener: {
                    Intent i3 = new Intent(context, LeftArmActivity.class);
                    startActivity(i3);
                    break;
                }
                case R.id.CreditsOpener: {
                    Intent i4 = new Intent(context, CreditsActivity.class);
                    startActivity(i4);
                    break;
                }
                case R.id.TrunkOpener: {
                    Intent i5 = new Intent(context, TrunkActivity.class);
                    startActivity(i5);
                    break;
                }
                case R.id.NextOpener: {
                    Intent i6 = new Intent(context, NextActivity.class);
                    startActivity(i6);
                    break;
                }
                case R.id.RightLegOpener: {
                    Intent i7 = new Intent(context, RightLegActivity.class);
                    startActivity(i7);
                    break;
                }
                case R.id.ExitOpener: {
                    Intent i8 = new Intent(context, ExitActivity.class);
                    startActivity(i8);
                    break;
                }
                case R.id.LeftLegOpener: {
                    Intent i9 = new Intent(context, LeftLegActivity.class);
                    startActivity(i9);
                    break;
                }
                //create this for all 9 buttons
            }

        }

    };

    LeftArmOpener.setOnClickListener(mClick);
    HeadOpener.setOnClickListener(mClick);
    RightArmOpener.setOnClickListener(mClick);
    CreditsOpener.setOnClickListener(mClick);
    TrunkOpener.setOnClickListener(mClick);
    NextOpener.setOnClickListener(mClick);
    RightLegOpener.setOnClickListener(mClick);
    ExitOpener.setOnClickListener(mClick);
    LeftLegOpener.setOnClickListener(mClick);

}

}

Body:
You said you have 9 buttons so i think u should use switch case in such scenarios see the following code:-

Here is how my Button looks in xml no android:onClick is used here

    <Button
    android:id="@+id/btn1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Button 1" />

This part goes in Activity:-

    Context context = this;
    Button btn1 = (Button) findViewById(R.id.btn1);
    Button btn2 = (Button) findViewById(R.id.btn2);
    Button btn9 = (Button) findViewById(R.id.btn9);

    btn1.setOnClickListener(mClick);
    btn2.setOnClickListener(mClick);
    btn9.setOnClickListener(mClick);

View.OnClickListener mClick = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1: {
                Intent i1 = new Intent(context, First.class);
                startActivity(i1);
                break;
            }
            case R.id.btm2: {
                Intent i2 = new Intent(context, Second.class);
                startActivity(i2);
                break;
            }
            //create this for all 9 buttons
        }

    }
};


问:
Python - Bubble sort
Hi I reviewed other posts with bubble sort, but solution didn't work in my case:
So algorithm works until I repeat few times while loop. But how can I do this without using input? Here is my code so you know what I mean:</p>

```<code>x = [0, 0, 1, 3, 3, 2, 2, 1, 0, 4, 5]

h = None
flag = True

while flag == True:
    #flag = True
    for i in range(len(x) - 1):
        if x[i] > x[i + 1]:
    #       flag = False
            h = x[i]
            x[i] = x[i + 1]
            x[i + 1] = h
    print(x)

    #input = raw_input('Satisfied? ')
    #if input == 'q':
    #   break

print(x)
'''
we can replace variable h, with:
x[i] , x[i+1] = x[i+1], x[i]
'''
</code>```

答:
You can make use of the sorted function in python, and change your code to be:

```<code>while flag == True:
    for i in range(len(x) - 1):
        if x[i] > x[i + 1]:
            h = x[i]
            x[i] = x[i + 1]
            x[i + 1] = h

    if sorted(x) == x: #x is already sorted
        flag = False
</code>```

Edit: Alternate solution which doesn't use python's built in sort function:

```<code>while flag == True:
    flag = False
    for i in range(len(x) - 1):
        if x[i] > x[i + 1]:
            flag = True
            h = x[i]
            x[i] = x[i + 1]
            x[i + 1] = h
</code>```

Hope I helped!

Title: Python - Bubble sort

Body:
Hi I reviewed other posts with bubble sort, but solution didn't work in my case:
So algorithm works until I repeat few times while loop. But how can I do this without using input? Here is my code so you know what I mean:

x = [0, 0, 1, 3, 3, 2, 2, 1, 0, 4, 5]

h = None
flag = True

while flag == True:
    #flag = True
    for i in range(len(x) - 1):
        if x[i] > x[i + 1]:
    #       flag = False
            h = x[i]
            x[i] = x[i + 1]
            x[i + 1] = h
    print(x)

    #input = raw_input('Satisfied? ')
    #if input == 'q':
    #   break

print(x)
'''
we can replace variable h, with:
x[i] , x[i+1] = x[i+1], x[i]
'''

Body:
You can make use of the sorted function in python, and change your code to be:

while flag == True:
    for i in range(len(x) - 1):
        if x[i] > x[i + 1]:
            h = x[i]
            x[i] = x[i + 1]
            x[i + 1] = h

    if sorted(x) == x: #x is already sorted
        flag = False

Edit: Alternate solution which doesn't use python's built in sort function:

while flag == True:
    flag = False
    for i in range(len(x) - 1):
        if x[i] > x[i + 1]:
            flag = True
            h = x[i]
            x[i] = x[i + 1]
            x[i + 1] = h

Hope I helped!


问:
How the last line of following recursive program is working?
I was studying Linked List and then I found a code for reversing the Linked List recursively. Here is the C++ code.

```<code>void recursiveReverse(node*& head)
{
  node* first;
  node* rest;

/* checking for an empty list */
  if (head == NULL)
   return;

  first = head;
  rest  = first->next;

/* List has only one node */
  if (rest == NULL)
   return;

  recursiveReverse(rest);
  first->next->next  = first;
  first->next  = NULL;

/* fix the head pointer */
  head = rest;
}
</code>```

I understood the whole code except the last line. Because according to me, the rest pointer is also updated similarly as the first pointer during unwinding of the recursion and therefore, at the end of this code, the head will not point to the last node.

Here's my interpretation of the following code.

Let's take a Linked List 1 -> 2 -> 3.

Initially, first will store the address of the head node and rest
will contain the address of the node 2.

Now, since rest is not NULL, therefore, recursiveReverse(rest) will be called.

Now, first will point to node 2 and rest will point to node 3.

Again, rest is not NULL, therefore, recursiveReverse(rest) will be called.

Now, first will point to node 3 and rest will contain NULL.

After that, the recursion will start unwinding and first will be back to node 2 and the rest will be back to node 3.

Now, the statement first -> next -> next = first; will cause the next part of node 3 to point to node 2 and the Linked List will become 1 -> 2 <- 3. The next part of node 2 will contain NULL and since head = rest, therefore, head will also point to last node as the rest pointer.

After that, first will point to node 1 and the statement first -> next -> next = first; will cause the next part of node 2 to point to node 1 and the Linked List will become 1 <- 2 <- 3. The next part of the node 1 will contain NULL and the statement head = rest will cause the head to point to node 2 and not the node 3 since, the rest (which is first -> next) is currently at node 2.

Can anyone please explain where I am wrong in interpreting this code?

答:
We beginners should help each other.:)

In my opinion it is not easy to understand how the function works for such beginners as we.

So it is better to figure out its work using schemes.

If the list either does not contain nodes or contains only one node then there is nothing to reverse.

This code snippet corresponds to this conclusion.

```<code>/* checking for an empty list */
  if (head == NULL)
   return;

  first = head;
  rest  = first->next;

/* List has only one node */
  if (rest == NULL)
   return;
</code>```

Now let's assume that the list contains exactly two nodes. In this case it looks like

```<code>--------    ----------    ----------------
| head | -> |   A  |B| -> |   B  |nullptr|
--------    ----------    ----------------
</code>```

This list is split into the following parts the following way

```<code>--------    ----------
| head | -> |   A  |B|
--------    ----------

--------    ----------
| first| -> |   A  |B|
--------    ----------

--------    ----------------
| rest | -> |   B  |nullptr|
--------    ----------------
</code>```

This code snippet corresponds to this conclusion

```<code>first = head;
rest  = first->next;
</code>```

Now the function calls itself recursively

```<code>recursiveReverse(rest);
</code>```

In fact it is called for this new list

```<code>--------    ----------------
| rest | -> |   B  |nullptr|
--------    ----------------
</code>```

as this new list contains only one node then the function just returns.

As the original list must be reversed then the head must contain the value of rest that is the head must point to the node "B"

This code snippet corresponds to this conclusion

```<code>head = rest;
</code>```

However in this case we will get

```<code>--------    ----------------
| head | -> |   B  |nullptr|
--------    ----------------
</code>```

But this list contains only one node "B". So before executing this statement

```<code>head = rest;
</code>```

we need to append the list with the node "A".

As we have that the pointer first points to the node "A"

```<code>--------    ----------
| first| -> |   A  |B|
--------    ----------
</code>```

then we can do the following

```<code>first->next->next  = first;
</code>```

that results in

```<code>--------     ----------    -----------
| first | -> |   A  |B| -> |   B  | A|
--------     ----------    -----------
</code>```

that is on the other hand we have

```<code>--------    ----------    -----------
| rest | -> |   B  |A| -> |   A  | B|
--------    ----------    -----------
</code>```

and then after this statement

```<code>first->next  = NULL;
</code>```

we will get

```<code>--------     ----------------  | -----------
| first | -> |   A  |nullptr|  | |   B  | A|-----------
--------     ----------------  | -----------          |
                                     ^                V
--------                             |             -----------------
| rest | ----------------------------              |   A  | nullptr|
--------                                           -----------------
</code>```

Now it is indeed time to call the statement

```<code>head = rest;
</code>```

and we will get

```<code>--------     ----------------  | -----------
| first | -> |   A  |nullptr|  | |   B  | A|-----------
--------     ----------------  | -----------          |
                                     ^                V
--------                             |             -----------------
| head | ----------------------------              |   A  | nullptr|
--------                                           -----------------
</code>```

That is the list is reversed.

If the list contains more than two nodes then after splitting the original list the pointer first will point to the first node of the original list that has to be the last node in the reversed list. In turn this first node will point to the next node that in the reversed list will be the last node.

Using this code snippet

```<code>first->next->next  = first;
first->next  = NULL;
</code>```

we can place it after the last node in the reversed list. And all we need to do is to set the head to the value stored in the pointer rest because the pointer rest is the head of the reversed list to which the node pointed to by the pointer first is appended.

```<code>head = rest;
</code>```

That is all.

Here is a demonstrative program

```<code>#include <iostream>

struct node
{
    int value;
    node *next;
};

void push( node * &head, int value )
{
    head = new node { value, head };
}

std::ostream & out( node * const &head, std::ostream &os = std::cout )
{
    for ( node *current = head; current != nullptr; current = current->next )
    {
        os << current->value << ' ';
    }

    return os;
}

void recursiveReverse( node * &head )
{
    if ( head != nullptr && head->next != nullptr )
    {
        node *first = head;
        node *rest  = head->next;

        recursiveReverse( rest );

        first->next->next  = first;
        first->next  = nullptr;

        head = rest;
    }
}

int main()
{
    node *head = nullptr;

    const int N = 10;

    for ( int value = 0; value < N; value++ )
    {
        push( head, value );
    }

    out( head ) << std::endl;

    recursiveReverse( head );

    out( head ) << std::endl;

    return 0;
}
</code>```

Its output is

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

Body:
I was studying Linked List and then I found a code for reversing the Linked List recursively. Here is the C++ code.

void recursiveReverse(node*& head)
{
  node* first;
  node* rest;

/* checking for an empty list */
  if (head == NULL)
   return;

  first = head;
  rest  = first->next;

/* List has only one node */
  if (rest == NULL)
   return;

  recursiveReverse(rest);
  first->next->next  = first;
  first->next  = NULL;

/* fix the head pointer */
  head = rest;
}

I understood the whole code except the last line. Because according to me, the rest pointer is also updated similarly as the first pointer during unwinding of the recursion and therefore, at the end of this code, the head will not point to the last node.

Here's my interpretation of the following code.

Let's take a Linked List 1 -> 2 -> 3.

Initially, first will store the address of the head node and rest
will contain the address of the node 2.

Now, since rest is not NULL, therefore, recursiveReverse(rest) will be called.

Now, first will point to node 2 and rest will point to node 3.

Again, rest is not NULL, therefore, recursiveReverse(rest) will be called.

Now, first will point to node 3 and rest will contain NULL.

After that, the recursion will start unwinding and first will be back to node 2 and the rest will be back to node 3.

Now, the statement first -> next -> next = first; will cause the next part of node 3 to point to node 2 and the Linked List will become 1 -> 2 <- 3. The next part of node 2 will contain NULL and since head = rest, therefore, head will also point to last node as the rest pointer.

After that, first will point to node 1 and the statement first -> next -> next = first; will cause the next part of node 2 to point to node 1 and the Linked List will become 1 <- 2 <- 3. The next part of the node 1 will contain NULL and the statement head = rest will cause the head to point to node 2 and not the node 3 since, the rest (which is first -> next) is currently at node 2.

Can anyone please explain where I am wrong in interpreting this code?

Body:
We beginners should help each other.:)

In my opinion it is not easy to understand how the function works for such beginners as we.

So it is better to figure out its work using schemes.

If the list either does not contain nodes or contains only one node then there is nothing to reverse.

This code snippet corresponds to this conclusion.

/* checking for an empty list */
  if (head == NULL)
   return;

  first = head;
  rest  = first->next;

/* List has only one node */
  if (rest == NULL)
   return;

Now let's assume that the list contains exactly two nodes. In this case it looks like

--------    ----------    ----------------
| head | -> |   A  |B| -> |   B  |nullptr|
--------    ----------    ----------------

This list is split into the following parts the following way

--------    ----------
| head | -> |   A  |B|
--------    ----------

--------    ----------
| first| -> |   A  |B|
--------    ----------

--------    ----------------
| rest | -> |   B  |nullptr|
--------    ----------------

This code snippet corresponds to this conclusion

first = head;
rest  = first->next;

Now the function calls itself recursively

recursiveReverse(rest);

In fact it is called for this new list

--------    ----------------
| rest | -> |   B  |nullptr|
--------    ----------------

as this new list contains only one node then the function just returns.

As the original list must be reversed then the head must contain the value of rest that is the head must point to the node "B"

This code snippet corresponds to this conclusion

head = rest;

However in this case we will get

--------    ----------------
| head | -> |   B  |nullptr|
--------    ----------------

But this list contains only one node "B". So before executing this statement

head = rest;

we need to append the list with the node "A".

As we have that the pointer first points to the node "A"

--------    ----------
| first| -> |   A  |B|
--------    ----------

then we can do the following

first->next->next  = first;

that results in

--------     ----------    -----------
| first | -> |   A  |B| -> |   B  | A|
--------     ----------    -----------

that is on the other hand we have

--------    ----------    -----------
| rest | -> |   B  |A| -> |   A  | B|
--------    ----------    -----------

and then after this statement

first->next  = NULL;

we will get

--------     ----------------  | -----------
| first | -> |   A  |nullptr|  | |   B  | A|-----------
--------     ----------------  | -----------          |
                                     ^                V
--------                             |             -----------------
| rest | ----------------------------              |   A  | nullptr|
--------                                           -----------------

Now it is indeed time to call the statement

head = rest;

and we will get

--------     ----------------  | -----------
| first | -> |   A  |nullptr|  | |   B  | A|-----------
--------     ----------------  | -----------          |
                                     ^                V
--------                             |             -----------------
| head | ----------------------------              |   A  | nullptr|
--------                                           -----------------

That is the list is reversed.

If the list contains more than two nodes then after splitting the original list the pointer first will point to the first node of the original list that has to be the last node in the reversed list. In turn this first node will point to the next node that in the reversed list will be the last node.

Using this code snippet

first->next->next  = first;
first->next  = NULL;

we can place it after the last node in the reversed list. And all we need to do is to set the head to the value stored in the pointer rest because the pointer rest is the head of the reversed list to which the node pointed to by the pointer first is appended.

head = rest;

That is all.

Here is a demonstrative program

#include <iostream>

struct node
{
    int value;
    node *next;
};

void push( node * &head, int value )
{
    head = new node { value, head };
}

std::ostream & out( node * const &head, std::ostream &os = std::cout )
{
    for ( node *current = head; current != nullptr; current = current->next )
    {
        os << current->value << ' ';
    }

    return os;
}

void recursiveReverse( node * &head )
{
    if ( head != nullptr && head->next != nullptr )
    {
        node *first = head;
        node *rest  = head->next;

        recursiveReverse( rest );

        first->next->next  = first;
        first->next  = nullptr;

        head = rest;
    }
}

int main()
{
    node *head = nullptr;

    const int N = 10;

    for ( int value = 0; value < N; value++ )
    {
        push( head, value );
    }

    out( head ) << std::endl;

    recursiveReverse( head );

    out( head ) << std::endl;

    return 0;
}

Its output is

9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9


问:
Ordering a <li> element using 'like'?
I have a list of data returned by a javascript query (code shown below). This is returned by Github so one of the fields shows the dominant language used in the project. Can I make a sorted list of the items with their own headers, returned by identifying all the unique primary languages used in my repo?</p>

```<code>function outputPageContent() {
   if (repositories.length == 0) {
      outhtml = outhtml + '<p>No repos!</p></div>';
   } else {
      outhtml = outhtml + '<p><strong>Project List:</strong></p> <ul>';
      $.each(repositories, function(index) {
         outhtml = outhtml + '<li id="' + repositories[index].language + index + '"><a href="' + repositories[index].html_url + '" target="_blank">' + repositories[index].name + '</a></li>';
      });
      outhtml = outhtml + '</ul></div>';
   }
   $('#ghapidata').html(outhtml);
}
</code>```

答:
Just sort before create your html.

```<code>repositories.sort(function(a, b){
    if(a.name < b.name) return -1;
    if(a.name > b.name) return 1;
    return 0;
})
</code>```

Sort function can get a compare function also. This anonymous function that defines an alternative sort order. You can change the comparison indexes of your array.

Full Code

```<code>function outputPageContent() {
   if (repositories.length == 0) {
      outhtml = outhtml + '<p>No repos!</p></div>';
   } else {
      outhtml = outhtml + '<p><strong>Project List:</strong></p> <ul>';
      repositories.sort(function(a, b){
        if(a.name < b.name) return -1;
        if(a.name > b.name) return 1;
        return 0;
      })
      $.each(repositories, function(index) {
         outhtml = outhtml + '<li id="' + repositories[index].language + index + '"><a href="' + repositories[index].html_url + '" target="_blank">' + repositories[index].name + '</a></li>';
      });
      outhtml = outhtml + '</ul></div>';
   }
   $('#ghapidata').html(outhtml);
}
</code>```

Alternative Sort Method

Also you can use more fluent another compare function.

```<code>repositories.sort(function(a, b){
    return a.name.localeCompare(b.name);
})
</code>```

Title: Ordering a <li> element using 'like'?

Body:
I have a list of data returned by a javascript query (code shown below). This is returned by Github so one of the fields shows the dominant language used in the project. Can I make a sorted list of the items with their own headers, returned by identifying all the unique primary languages used in my repo?

function outputPageContent() {
   if (repositories.length == 0) {
      outhtml = outhtml + '
No repos!

';
   } else {
      outhtml = outhtml + '
Project List:

';
      $.each(repositories, function(index) {
         outhtml = outhtml + '
' + repositories[index].name + '
';
      });
      outhtml = outhtml + '

';
   }
   $('#ghapidata').html(outhtml);
}

Body:
Just sort before create your html.

repositories.sort(function(a, b){
    if(a.name < b.name) return -1;
    if(a.name > b.name) return 1;
    return 0;
})

Sort function can get a compare function also. This anonymous function that defines an alternative sort order. You can change the comparison indexes of your array.

Full Code

function outputPageContent() {
   if (repositories.length == 0) {
      outhtml = outhtml + '<p>No repos!</p></div>';
   } else {
      outhtml = outhtml + '<p><strong>Project List:</strong></p> <ul>';
      repositories.sort(function(a, b){
        if(a.name < b.name) return -1;
        if(a.name > b.name) return 1;
        return 0;
      })
      $.each(repositories, function(index) {
         outhtml = outhtml + '<li id="' + repositories[index].language + index + '"><a href="' + repositories[index].html_url + '" target="_blank">' + repositories[index].name + '</a></li>';
      });
      outhtml = outhtml + '</ul></div>';
   }
   $('#ghapidata').html(outhtml);
}

Alternative Sort Method

Also you can use more fluent another compare function.

repositories.sort(function(a, b){
    return a.name.localeCompare(b.name);
})


问:
Running a process in a separate thread so rest of Java FX application is usable?
I am currently creating a Java application with a UI created using Java FX. My application's interface is divided into three separate tabs. On the first tab, I have a lot of buttons that launch other applications. My goal is for the user to launch these applications in a certain order, so the succeeding buttons are disabled out until the previous application's process has finished, then they are enabled. I have accomplished this by using the lines

```<code>Process p = Runtime.getRuntime().exec(application);
p.waitFor();
</code>```

Then the controller enables the next button in the interface. My problem arises when the launched application is running. Due to my application waiting for the process to end, task manager shows my Java application as not responding, and you are unable to navigate to the other tabs. Of course when the launched application has finished, my application functions normally.

I was thinking that it's due to the main thread being blocked as it's waiting on a process to finish. Would the best solution be to run this process on a separate thread so the rest of the application is usable while waiting on a launched process to finish?

答:
I was thinking that it's due to the main thread being blocked as it's waiting on a process to finish.

This is correct.

Is it possible to run this process on a seperate thread so the rest of the application is usable while waiting on a launched process to finish?

Yes, of course. The simplest thing to do is just to launch this on a separate thread:

```<code>Process p = Runtime.getRuntime().exec(application);
new Thread(p::waitFor).start();
</code>```

However, you probably need a little more that that: e.g. to be notified when that new thread finishes, etc. JavaFX provides a concurrency API that has callbacks for the lifecycle of the tasks you execute. These callbacks are executed back on the FX Application Thread, so it is safe to update the UI in the callbacks (you cannot update the UI from a background thread).

So you can do something like

```<code>Task<Void> executeAppTask = new Task<Void>() {
    @Override
    protected Void call() throws Exception {
        Process p = Runtime.getRuntime().exec(application);
        p.waitFor();
        return null;
    }
};

executeAppTask.setOnSucceeded(e -> {
    /* code to execute when task completes normally */
});

executeAppTask.setOnFailed(e -> {
    Throwable problem = executeAppTask.getException();
    /* code to execute if task throws exception */
});

executeAppTask.setOnCancelled(e -> {
    /* task was cancelled */
});

Thread thread = new Thread(executeAppTask);
thread.start();
</code>```

Note that the setOnSucceeded(), setOnFailed(), and setOnCancelled() handlers are executed on the FX Application Thread, so, again, it is safe to update the UI in those handlers. Also note that calling executeAppTask.cancel() will interrupt the thread running the task, if necessary, which will properly interrupt the waitFor() method. Thus you will (more or less) immediately invoke the setOnCancelled handler by calling executeAppTask.cancel(). If there is code in the call() method executed after a call to a blocking method, such as waitFor(), it should probably catch the interrupted exception and check the isCancelled() flag, exiting gracefully if the task has been cancelled.

See the Task API docs for many more examples.

Body:
I am currently creating a Java application with a UI created using Java FX. My application's interface is divided into three separate tabs. On the first tab, I have a lot of buttons that launch other applications. My goal is for the user to launch these applications in a certain order, so the succeeding buttons are disabled out until the previous application's process has finished, then they are enabled. I have accomplished this by using the lines

Process p = Runtime.getRuntime().exec(application);
p.waitFor();

Then the controller enables the next button in the interface. My problem arises when the launched application is running. Due to my application waiting for the process to end, task manager shows my Java application as not responding, and you are unable to navigate to the other tabs. Of course when the launched application has finished, my application functions normally.

I was thinking that it's due to the main thread being blocked as it's waiting on a process to finish. Would the best solution be to run this process on a separate thread so the rest of the application is usable while waiting on a launched process to finish?

Body:
I was thinking that it's due to the main thread being blocked as it's waiting on a process to finish.

This is correct.

Is it possible to run this process on a seperate thread so the rest of the application is usable while waiting on a launched process to finish?

Yes, of course. The simplest thing to do is just to launch this on a separate thread:

Process p = Runtime.getRuntime().exec(application);
new Thread(p::waitFor).start();

However, you probably need a little more that that: e.g. to be notified when that new thread finishes, etc. JavaFX provides a concurrency API that has callbacks for the lifecycle of the tasks you execute. These callbacks are executed back on the FX Application Thread, so it is safe to update the UI in the callbacks (you cannot update the UI from a background thread).

So you can do something like

Task<Void> executeAppTask = new Task<Void>() {
    @Override
    protected Void call() throws Exception {
        Process p = Runtime.getRuntime().exec(application);
        p.waitFor();
        return null;
    }
};

executeAppTask.setOnSucceeded(e -> {
    /* code to execute when task completes normally */
});

executeAppTask.setOnFailed(e -> {
    Throwable problem = executeAppTask.getException();
    /* code to execute if task throws exception */
});

executeAppTask.setOnCancelled(e -> {
    /* task was cancelled */
});

Thread thread = new Thread(executeAppTask);
thread.start();

Note that the setOnSucceeded(), setOnFailed(), and setOnCancelled() handlers are executed on the FX Application Thread, so, again, it is safe to update the UI in those handlers. Also note that calling executeAppTask.cancel() will interrupt the thread running the task, if necessary, which will properly interrupt the waitFor() method. Thus you will (more or less) immediately invoke the setOnCancelled handler by calling executeAppTask.cancel(). If there is code in the call() method executed after a call to a blocking method, such as waitFor(), it should probably catch the interrupted exception and check the isCancelled() flag, exiting gracefully if the task has been cancelled.

See the Task API docs for many more examples.

ContentLicense: CC BY-SA 4.0


答:
A union is a special data type available in C that allows to store different data types in the same memory location.

That said, you must use one variable at a time.

http://www.tutorialspoint.com/cprogramming/c_unions.htm

Title: Regarding union and multiple integer values

Body:
I'm getting into C and I experimented with union. My code is the following:

#include <stdio.h>

union date {
 int year  ;
 char month;
 char day  ;
 };

int main() {
 union date birth;
 birth.year = 1984;
 birth.month = 7;
 birth.day = 28;
 printf("%d, %d, %d\n",birth.year, birth.month, birth.day);
 // return 1820,28,28
 return 0;
}

1984 is written in binary as 0111 1100 0000

7 is written in binary as 0110

28 is written in binary as 0001 1100

I understand that because of union, birth.year has the value of 0111 0001 1100 which is 1820. But I do not understand why does birth.month return as value 28.


问:
How to connect to Oracle with Perl using LDAP?
I will be needing to connect to an Oracle server on a system that only supports LDAP for name lookup, rather than TNSNAMES.ora. Is this possible with perl? I am quite sure that I can install the Net::LDAP module and parse the connection information myself, but I was looking for a standard way.</p>

答: It should use whatever is defined in the sqlnet.ora of the client install.  Perl shouldn't have to worry about the naming method.  </p>


问:
Error with create tables in sqlite3
I am learning sqlite3 in python3. I have added 4 columns in my table using the syntax

```<code>c.execute("CREATE table raman(ATOMIC NUMBER INT, SYMBOL TEXT, ROW INT , COLUMN INT)")
</code>```

and I want to insert values for them  so I am writing

```<code>c.execute("INSERT INTO raman VALUES(1,'H',1,'1')");
</code>```

After this if I print the table its not showing me the inserted values. I am using this command to print        print c.execute("SELECT * FROM SQLITE_ master type='table'").fetchall()

答:
The complete (minimal) sequence is this.

```<code>>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute("CREATE table raman(ATOMIC NUMBER INT, SYMBOL TEXT, ROW INT , COLUMN INT)")
<sqlite3.Cursor object at 0x000000000296E490>
>>> c.execute("INSERT INTO raman VALUES(1,'H',1,'1')");
<sqlite3.Cursor object at 0x000000000296E490>
>>> conn.commit()
>>> for row in c.execute('SELECT * FROM raman'):
...     row
...
(1, 'H', 1, 1)
</code>```

Until you issue the commit the values won't be (or won't necessarily be) present in the table.

Title: Error with create tables in sqlite3

Body:
I am learning sqlite3 in python3. I have added 4 columns in my table using the syntax

c.execute("CREATE table raman(ATOMIC NUMBER INT, SYMBOL TEXT, ROW INT , COLUMN INT)")

and I want to insert values for them  so I am writing

c.execute("INSERT INTO raman VALUES(1,'H',1,'1')");

After this if I print the table its not showing me the inserted values. I am using this command to print        print c.execute("SELECT * FROM SQLITE_ master type='table'").fetchall()

Body:
The complete (minimal) sequence is this.

>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute("CREATE table raman(ATOMIC NUMBER INT, SYMBOL TEXT, ROW INT , COLUMN INT)")
<sqlite3.Cursor object at 0x000000000296E490>
>>> c.execute("INSERT INTO raman VALUES(1,'H',1,'1')");
<sqlite3.Cursor object at 0x000000000296E490>
>>> conn.commit()
>>> for row in c.execute('SELECT * FROM raman'):
...     row
...
(1, 'H', 1, 1)

Until you issue the commit the values won't be (or won't necessarily be) present in the table.


问:
How to execute an external program as part of an SQL query?
I am trying to figure out how to embed a call to an external program in a SQL query. The idea is that as the SQL query executes, it would be able to call an external program, passing along records from a database, and receiving output that could then be used by that SQL query.

The reason that I want to do this, and that I cannot consider alternative approaches, is that I have been tasked with manually re-creating some database benchmarks in Python using SQLite and the SQLAlchemy library (specifically these benchmarks: https://amplab.cs.berkeley.edu/benchmark/).

One of the SQL queries described there (Query 4) begins with the following SQL statement:

```<code>CREATE TABLE url_counts_partial AS
  SELECT TRANSFORM (line)
    USING "python /root/url_count.py" as (sourcePage, destPage, cnt)
  FROM documents;
</code>```

Here is their description of Query 4:

This query calls an external Python function which extracts and aggregates URL information from a web crawl dataset. It then aggregates a total count per URL.

The table "documents" contains a single column called "line" which represents individual lines of HTML. The "url_count.py" program simply parses lines from sys.stdin and prints lines of tab-separated information (you can see url_count.py here: https://github.com/amplab/benchmark/blob/master/runner/udf/url_count.py).

I attempted to run the following:

```<code>from sqlalchemy import create_engine
engine = create_engine('sqlite:///myDatabase.db')

result = engine.execute("""SELECT TRANSFORM (line)
             USING 'python /root/url_count.py' as (sourcePage, destPage, cnt)
             FROM documents"""")
</code>```

Every time I try running this, however, I get an exception with a complaint at the bottom about a syntax error:

```<code>sqlalchemy.exc.OperationalError: (OperationalError) near "USING": syntax error
</code>```

I have tried tweaking the syntax in every way I can think of. I have tried moving url_count.py to the local directory. I have tried executing the full statement instead (i.e. adding back in "CREATE TABLE url_counts_partial AS"). I have tried running simplified versions of it against toy databases. I have also tried replacing the call to a python program with calls to simple bash commands. Nothing seems to work. Nor can I seem to find any online documentation for the keywords TRANSFORM or USING.

Am I just making a silly error somewhere? Or if not, is there an easier/more correct way to execute this command (while still staying faithful to the original query)? Failing that, even just knowing where to find the man pages for TRANSFORM or USING would be very helpful. I have not had any problems with any of their other queries, so I don't know why this one should turn out to be such a headache.

答:
SQLite has no such USING clause to call an external program.

The nearest mechanism would be a table-valued function, but this is not exposed by the Python sqlite3 module.

The easiest way to do this would be execute that program manually, and convert its output into INSERT commands.

Body:
I am trying to figure out how to embed a call to an external program in a SQL query. The idea is that as the SQL query executes, it would be able to call an external program, passing along records from a database, and receiving output that could then be used by that SQL query.

The reason that I want to do this, and that I cannot consider alternative approaches, is that I have been tasked with manually re-creating some database benchmarks in Python using SQLite and the SQLAlchemy library (specifically these benchmarks: https://amplab.cs.berkeley.edu/benchmark/).

One of the SQL queries described there (Query 4) begins with the following SQL statement:

CREATE TABLE url_counts_partial AS
  SELECT TRANSFORM (line)
    USING "python /root/url_count.py" as (sourcePage, destPage, cnt)
  FROM documents;

Here is their description of Query 4:

This query calls an external Python function which extracts and aggregates URL information from a web crawl dataset. It then aggregates a total count per URL.

The table "documents" contains a single column called "line" which represents individual lines of HTML. The "url_count.py" program simply parses lines from sys.stdin and prints lines of tab-separated information (you can see url_count.py here: https://github.com/amplab/benchmark/blob/master/runner/udf/url_count.py).

I attempted to run the following:

from sqlalchemy import create_engine
engine = create_engine('sqlite:///myDatabase.db')

result = engine.execute("""SELECT TRANSFORM (line)
             USING 'python /root/url_count.py' as (sourcePage, destPage, cnt)
             FROM documents"""")

Every time I try running this, however, I get an exception with a complaint at the bottom about a syntax error:

sqlalchemy.exc.OperationalError: (OperationalError) near "USING": syntax error

I have tried tweaking the syntax in every way I can think of. I have tried moving url_count.py to the local directory. I have tried executing the full statement instead (i.e. adding back in "CREATE TABLE url_counts_partial AS"). I have tried running simplified versions of it against toy databases. I have also tried replacing the call to a python program with calls to simple bash commands. Nothing seems to work. Nor can I seem to find any online documentation for the keywords TRANSFORM or USING.

Am I just making a silly error somewhere? Or if not, is there an easier/more correct way to execute this command (while still staying faithful to the original query)? Failing that, even just knowing where to find the man pages for TRANSFORM or USING would be very helpful. I have not had any problems with any of their other queries, so I don't know why this one should turn out to be such a headache.


答:
Is the array being created on the stack? For instance, are you creating the array like this?

```<code>void foo()
{
  double mat[3200][3200];

  // ... other stuff

  fwrite(mat, sizeof(double), 3200*3200, fid);
}
</code>```

If so, are you sure that it is fwrite and not the array declaration itself that is causing the stack overflow? The array occupies 3200*3200*8 = 81920000 bytes (about 78 MiB), probably a little too big for a stack allocation. Try malloc'ing the array instead.

Title: Passing arrays to functions by their names in C

Body:
I'm declaring a global variable in my program:

double mat[3200][3200];

when passing this array to fwrite() by using the variable's name as argument, I get stack overflow thrown at runtime.

fwrite(mat, sizeof(double), 3200*3200, fid);

Why is that? Shouldn't the compiler replace the variable mat with a pointer to its first element?

I've read here and here, and still can't understand.

Body:
Is the array being created on the stack? For instance, are you creating the array like this?

void foo()
{
  double mat[3200][3200];

  // ... other stuff

  fwrite(mat, sizeof(double), 3200*3200, fid);
}

If so, are you sure that it is fwrite and not the array declaration itself that is causing the stack overflow? The array occupies 3200*3200*8 = 81920000 bytes (about 78 MiB), probably a little too big for a stack allocation. Try malloc'ing the array instead.


问:
Arithmetic shift by $signal give different result in conditional expression and always block
I'm writing ALU for MIPS.

I used to write it as a sequential logic (or a always block? I don't know why but c must be a reg so I guess it's a sequential logic?)

It seems to be combinational logic

```<code>always @* begin
    case (op)
        4'b0000: c = mux_a + mux_b;
        4'b0001: c = mux_a - mux_b;
        4'b0010: c = mux_b << mux_a[4:0];
        4'b0011: c = mux_b >> mux_a[4:0];
        4'b0100: c = $signed(mux_b) >>> mux_a[4:0];
        4'b0101: c = mux_a & mux_b;
        4'b0110: c = mux_a | mux_b;
        4'b0111: c = mux_a ^ mux_b;
        4'b1000: c = ~(mux_a | mux_b);
        4'b1001: c = (mux_a < mux_b) ? 32'b1 : 32'b0; // sltu
        4'b1010: c = ($signed(mux_a) < $signed(mux_b)) ? 32'b1 : 32'b0; // slt
        4'b1011: c = mux_a + mux_b - 4;
        default: c = 0;
    endcase
end
</code>```

And it works well, 4'b0100: c = $signed(mux_b) >>> mux_a[4:0] can get correct output. However due to some reasons I decided to use a combinational logic conditional expression.

```<code>assign c =  (op == 4'b0000) ? (mux_a + mux_b) :
            (op == 4'b0001) ? (mux_a - mux_b) :
            (op == 4'b0010) ? (mux_b << mux_a[4:0]) :
            (op == 4'b0011) ? (mux_b >> mux_a[4:0]) :
            (op == 4'b0100) ? ($signed(mux_b) >>> mux_a[4:0]) :
            (op == 4'b0101) ? (mux_a & mux_b) :
            (op == 4'b0110) ? (mux_a | mux_b) :
            (op == 4'b0111) ? (mux_a ^ mux_b) :
            (op == 4'b1000) ? (~(mux_a | mux_b)) :
            (op == 4'b1001) ? ((mux_a < mux_b) ? 32'b1 : 32'b0) :
            (op == 4'b1010) ? (($signed(mux_a) < $signed(mux_b)) ? 32'b1 : 32'b0) :
            (op == 4'b1011) ? (mux_a + mux_b - 4) :
            0;
</code>```

Which is almost the same except c is a wire.

And I run this code and it tells me that, 4294967280 (FFFFFFF0) >>> 8 = 33554431 (1FFFFFF) which is ridiculous.

```<code>PC=        388, Fetched 00000000000100011001101000000011.
  Decoder done. alu=4294967280.
  ALUOP=0100 ALUMASK=10 Calc Result=  33554431
  rs=         0 rt=4294967280
  aluflag = 0000
  Written(0000) 01ffffff to RegAddr:19
</code>```

But if I use (op == 4'b0100) ? ({ {31{mux_b[32]}}, mux_b} >> mux_a[4:0]) : instead, I can get correct result.

Can anyone tell me the reason? Following is how these variable defined (use 33 bits for overflow flags)

```<code>input [31:0] a;
input [31:0] b;
input [31:0] imm1;
input [31:0] imm0;
input [3:0] op;
input [1:0] mask;

output [31:0] result;
output [3:0] flags;

wire [31:0] _mux_a;
wire [31:0] _mux_b;

wire [32:0] mux_a;
wire [32:0] mux_b;
wire [32:0] c;

assign _mux_a = mask[1] ? imm1 : a;
assign _mux_b = mask[0] ? imm0 : b;
assign mux_a = {_mux_a[31], _mux_a};
assign mux_b = {_mux_b[31], _mux_b};
assign result = c[31:0];

//zf of uf
assign flags = {c[31], result == 0,  c[32:31] == 2'b01,  c[32:31] == 2'b10};
</code>```

答:
It is a bug in iverilog. Something about combining $signed and the conditional operator ?:. It does not matter if you are using continuous assignment (assign statement) or an always block.

When mux_b[32] is one, $signed(mux_b) >>> mux_a[4:0] will give the correct output while (1'b1) ? ($signed(mux_b) >>> mux_a[4:0]) : 33'h0 will give the wrong output.

If you want, you can file a bug here and here

A work around is to separate the operations. Example:

```<code>assign op4 = $signed(mux_b) >>> mux_a[4:0];
assign c = (op == 4'b0000) ...
           (op == 4'b0100) ? op4 :
           (op == 4'b0101) ...
</code>```

Or (op == 4'b0100) ? ({ {31{mux_b[32]}}, mux_b} >> mux_a[4:0]) : as already pointed out in the question.

FYI: From my experience the conditional operator ?: often synthesizes to an explicit 2:1 mux even when a 4:1 or other mux type is more ideal. Your experience may differ. In general, I recommend using case statement for any muxing greater that 3:1.

Body:
I'm writing ALU for MIPS.

I used to write it as a sequential logic (or a always block? I don't know why but c must be a reg so I guess it's a sequential logic?)

It seems to be combinational logic

always @* begin
    case (op)
        4'b0000: c = mux_a + mux_b;
        4'b0001: c = mux_a - mux_b;
        4'b0010: c = mux_b << mux_a[4:0];
        4'b0011: c = mux_b >> mux_a[4:0];
        4'b0100: c = $signed(mux_b) >>> mux_a[4:0];
        4'b0101: c = mux_a & mux_b;
        4'b0110: c = mux_a | mux_b;
        4'b0111: c = mux_a ^ mux_b;
        4'b1000: c = ~(mux_a | mux_b);
        4'b1001: c = (mux_a < mux_b) ? 32'b1 : 32'b0; // sltu
        4'b1010: c = ($signed(mux_a) < $signed(mux_b)) ? 32'b1 : 32'b0; // slt
        4'b1011: c = mux_a + mux_b - 4;
        default: c = 0;
    endcase
end

And it works well, 4'b0100: c = $signed(mux_b) >>> mux_a[4:0] can get correct output. However due to some reasons I decided to use a combinational logic conditional expression.

assign c =  (op == 4'b0000) ? (mux_a + mux_b) :
            (op == 4'b0001) ? (mux_a - mux_b) :
            (op == 4'b0010) ? (mux_b << mux_a[4:0]) :
            (op == 4'b0011) ? (mux_b >> mux_a[4:0]) :
            (op == 4'b0100) ? ($signed(mux_b) >>> mux_a[4:0]) :
            (op == 4'b0101) ? (mux_a & mux_b) :
            (op == 4'b0110) ? (mux_a | mux_b) :
            (op == 4'b0111) ? (mux_a ^ mux_b) :
            (op == 4'b1000) ? (~(mux_a | mux_b)) :
            (op == 4'b1001) ? ((mux_a < mux_b) ? 32'b1 : 32'b0) :
            (op == 4'b1010) ? (($signed(mux_a) < $signed(mux_b)) ? 32'b1 : 32'b0) :
            (op == 4'b1011) ? (mux_a + mux_b - 4) :
            0;

Which is almost the same except c is a wire.

And I run this code and it tells me that, 4294967280 (FFFFFFF0) >>> 8 = 33554431 (1FFFFFF) which is ridiculous.

PC=        388, Fetched 00000000000100011001101000000011.
  Decoder done. alu=4294967280.
  ALUOP=0100 ALUMASK=10 Calc Result=  33554431
  rs=         0 rt=4294967280
  aluflag = 0000
  Written(0000) 01ffffff to RegAddr:19

But if I use (op == 4'b0100) ? ({ {31{mux_b[32]}}, mux_b} >> mux_a[4:0]) : instead, I can get correct result.

Can anyone tell me the reason? Following is how these variable defined (use 33 bits for overflow flags)

input [31:0] a;
input [31:0] b;
input [31:0] imm1;
input [31:0] imm0;
input [3:0] op;
input [1:0] mask;

output [31:0] result;
output [3:0] flags;

wire [31:0] _mux_a;
wire [31:0] _mux_b;

wire [32:0] mux_a;
wire [32:0] mux_b;
wire [32:0] c;

assign _mux_a = mask[1] ? imm1 : a;
assign _mux_b = mask[0] ? imm0 : b;
assign mux_a = {_mux_a[31], _mux_a};
assign mux_b = {_mux_b[31], _mux_b};
assign result = c[31:0];

//zf of uf
assign flags = {c[31], result == 0,  c[32:31] == 2'b01,  c[32:31] == 2'b10};

Body:
It is a bug in iverilog. Something about combining $signed and the conditional operator ?:. It does not matter if you are using continuous assignment (assign statement) or an always block.

When mux_b[32] is one, $signed(mux_b) >>> mux_a[4:0] will give the correct output while (1'b1) ? ($signed(mux_b) >>> mux_a[4:0]) : 33'h0 will give the wrong output.

If you want, you can file a bug here and here

A work around is to separate the operations. Example:

assign op4 = $signed(mux_b) >>> mux_a[4:0];
assign c = (op == 4'b0000) ...
           (op == 4'b0100) ? op4 :
           (op == 4'b0101) ...

Or (op == 4'b0100) ? ({ {31{mux_b[32]}}, mux_b} >> mux_a[4:0]) : as already pointed out in the question.

FYI: From my experience the conditional operator ?: often synthesizes to an explicit 2:1 mux even when a 4:1 or other mux type is more ideal. Your experience may differ. In general, I recommend using case statement for any muxing greater that 3:1.


答:
Quoting C11, chapter §6.7.2.1, (emphasis mine)

The size of a union is sufficient to contain the largest of its members. The value of at
  most one of the members can be stored in a union object at any time. A pointer to a
  union object, suitably converted, points to each of its members (or if a member is a bitfield,
  then to the unit in which it resides), and vice versa.

So, the basis of your expectation is wrong. You cannot have values for all the members of an union at the same time, you can have only one.

Also, from chapter §6.5.2.3, Footnote 95,

If the member used to read the contents of a union object is not the same as the member last used to
  store a value in the object, the appropriate part of the object representation of the value is re-interpreted
  as an object representation in the new type as described in 6.2.6 (a process sometimes called ‘‘type
  punning’’). This might be a trap representation.

Here, the last assigned value, day happens to be of the same size of that of month, so when you try to read day, it returns the value of that of the month.


问:
Elastic Beanstalk Docker container running Node application exits early
I have an ElasticBeanstalk environment with docker that deploys a node application running restify. When we deploy new versions of the application we see intermittent failures with the error:

Command failed on instance. Return code: 1 Output: nginx: [emerg] no host in upstream ":8080"

When looking through the logs we see that the container exits with exit 0 meaning the application is returning that it has exited successfully.

Dockerfile:

```<code>FROM node:alpine
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY .npmrc .npmrc
COPY package.json /usr/src/app/
RUN npm install
RUN rm -f .npmrc

COPY . /usr/src/app

EXPOSE 8080 CMD ["npm", "start"]
</code>```

答:
TL;DR: CMD should launch the long running process.

CMD npm start would launch the application through a gulp task that spawned a process to start the node application server.

Once the application process was spawned the gulp task would complete. Once gulp completed, the process would report to docker that it completed successfully and so the container would exit. To fix this I changed the docker file CMD to :

CMD ["npm", "run", "start-node"]

start-node runs the commands node dist/app.js

So now the process launched by CMD is the application server instead of the process that spawned a child-process that would start the application.

Body:
I have an ElasticBeanstalk environment with docker that deploys a node application running restify. When we deploy new versions of the application we see intermittent failures with the error:

Command failed on instance. Return code: 1 Output: nginx: [emerg] no host in upstream ":8080"

When looking through the logs we see that the container exits with exit 0 meaning the application is returning that it has exited successfully.

Dockerfile:

FROM node:alpine
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY .npmrc .npmrc
COPY package.json /usr/src/app/
RUN npm install
RUN rm -f .npmrc

COPY . /usr/src/app

EXPOSE 8080 CMD ["npm", "start"]


问:
Indexing arrays with enums in C#
I have a lot of fixed-size collections of numbers where each entry can be accessed with a constant. Naturally this seems to point to arrays and enums:

```<code>enum StatType {
    Foo = 0,
    Bar
    // ...
}

float[] stats = new float[...];
stats[StatType.Foo] = 1.23f;
</code>```

The problem with this is of course that you cannot use an enum to index an array without a cast (though the compiled IL is using plain ints). So you have to write this all over the place:

```<code>stats[(int)StatType.foo] = 1.23f;
</code>```

I have tried to find ways to use the same easy syntax without casting but haven't found a perfect solution yet. Using a dictionary seems to be out of the question since I found it to be around 320 times slower than an array. I also tried to write a generic class for an array with enums as index:

```<code>public sealed class EnumArray<T>
{
    private T[] array;
    public EnumArray(int size)
    {
        array = new T[size];
    }
    // slow!
    public T this[Enum idx]
    {
        get { return array[(int)(object)idx]; }
        set { array[(int)(object)idx] = value; }
    }
}
</code>```

or even a variant with a second generic parameter specifying the enum. This comes quite close to what I want but the problem is that you cannot just cast an unspecific enum (be it from a generic parameter or the boxed type Enum) to int. Instead you have to first box it with a cast to object and then cast it back. This works, but is quite slow. I found that the generated IL for the indexer looks something like this:

```<code>.method public hidebysig specialname instance !T get_Item(!E idx) cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldfld !0[] EnumArray`2<!T, !E>::array
    L_0006: ldarg.1
    L_0007: box !E
    L_000c: unbox.any int32
    L_0011: ldelem.any !T
    L_0016: ret
}
</code>```

As you can see there are unnecessary box and unbox instructions there. If you strip them from the binary the code works just fine and is just a tad slower than pure array access.

Is there any way to easily overcome this problem? Or maybe even better ways?
I think it would also be possible to tag such indexer methods with a custom attribute and strip those two instructions post-compile. What would be a suitable library for that? Maybe Mono.Cecil?

Of course there's always the possibility to drop enums and use constants like this:

```<code>static class StatType {
    public const int Foo = 0;
    public const int Bar = 1;
    public const int End = 2;
}
</code>```

which may be the fastest way since you can directly access the array.

答:
I suspect you may be able to make it a bit faster by compiling a delegate to do the conversion for you, such that it doesn't require boxing and unboxing. An expression tree may well be the simplest way of doing that if you're using .NET 3.5. (You'd use that in your EnumArray example.)

Personally I'd be very tempted to use your const int solution. It's not like .NET provides enum value validation anyway by default - i.e. your callers could always cast int.MaxValue to your enum type, and you'd get an ArrayIndexException (or whatever). So, given the relative lack of protection / type safety you're already getting, the constant value answer is appealing.

Hopefully Marc Gravell will be along in a minute to flesh out the compiled conversion delegate idea though...

Title: Indexing arrays with enums in C#

Body:
I have a lot of fixed-size collections of numbers where each entry can be accessed with a constant. Naturally this seems to point to arrays and enums:

enum StatType {
    Foo = 0,
    Bar
    // ...
}

float[] stats = new float[...];
stats[StatType.Foo] = 1.23f;

The problem with this is of course that you cannot use an enum to index an array without a cast (though the compiled IL is using plain ints). So you have to write this all over the place:

stats[(int)StatType.foo] = 1.23f;

I have tried to find ways to use the same easy syntax without casting but haven't found a perfect solution yet. Using a dictionary seems to be out of the question since I found it to be around 320 times slower than an array. I also tried to write a generic class for an array with enums as index:

public sealed class EnumArray<T>
{
    private T[] array;
    public EnumArray(int size)
    {
        array = new T[size];
    }
    // slow!
    public T this[Enum idx]
    {
        get { return array[(int)(object)idx]; }
        set { array[(int)(object)idx] = value; }
    }
}

or even a variant with a second generic parameter specifying the enum. This comes quite close to what I want but the problem is that you cannot just cast an unspecific enum (be it from a generic parameter or the boxed type Enum) to int. Instead you have to first box it with a cast to object and then cast it back. This works, but is quite slow. I found that the generated IL for the indexer looks something like this:

.method public hidebysig specialname instance !T get_Item(!E idx) cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldfld !0[] EnumArray`2<!T, !E>::array
    L_0006: ldarg.1
    L_0007: box !E
    L_000c: unbox.any int32
    L_0011: ldelem.any !T
    L_0016: ret
}

As you can see there are unnecessary box and unbox instructions there. If you strip them from the binary the code works just fine and is just a tad slower than pure array access.

Is there any way to easily overcome this problem? Or maybe even better ways?
I think it would also be possible to tag such indexer methods with a custom attribute and strip those two instructions post-compile. What would be a suitable library for that? Maybe Mono.Cecil?

Of course there's always the possibility to drop enums and use constants like this:

static class StatType {
    public const int Foo = 0;
    public const int Bar = 1;
    public const int End = 2;
}

which may be the fastest way since you can directly access the array.

OwnerDisplayName: Jon Skeet


问:
captcha or not?
i hate captcha, do you think there is a better solution </p>

答:
I solved this in a cute way a couple of years ago.

I had an "email me" form on a small business website that I wanted to be maximally accessible; spam bots found it and started overwhelming the legitimate messages.  From reading the server logs, I learned that bots were submitting the form without re-fetching it first -- somebody had cached my form and was simply sending a POST whenever they had some garbage for me to read.  A hidden form input would help for a few days, but then some bot's owner would figure out the right input, cache it, and the deluge would begin again.

I didn't have any backend where I could add session information to the form, and didn't want to add any.  Instead, between the "Type your message here" box and the hidden element, I inserted the output of a script that writes

There will be a short delay before you may submit the form.  If you

have been typing in your information, the delay may already have

ended.

4 ...

The garbage block is randomly generated to make it hard to compress.  I experimented with how long the blocks of garbage needed to be.  When I got the form size up to about 200K, the spam messages stopped.

This is actually not a lot of extra data, about like adding a few extra images to the page.  Even for a hypothetical customer on dialup, the delay between rendering the text box and rendering the submit button is shorter than the time it would probably take to actually compose a message.

Title: captcha or not?

Body:
I solved this in a cute way a couple of years ago.

I had an "email me" form on a small business website that I wanted to be maximally accessible; spam bots found it and started overwhelming the legitimate messages.  From reading the server logs, I learned that bots were submitting the form without re-fetching it first -- somebody had cached my form and was simply sending a POST whenever they had some garbage for me to read.  A hidden form input would help for a few days, but then some bot's owner would figure out the right input, cache it, and the deluge would begin again.

I didn't have any backend where I could add session information to the form, and didn't want to add any.  Instead, between the "Type your message here" box and the hidden element, I inserted the output of a script that writes

  <!-- instructions for spam robots: we are a waste of your money, go away, thanks -->

<div class="float-left" style="font-size: x-small;">

There will be a short delay before you may submit the form.  If you

have been typing in your information, the delay may already have

ended.

<br/><span>

4 ...

</span><span>

<!--

d92cbd14985295ac27929a6db7891a90ec4173a8358dcadab134cc589ce2de54

1468365bd33b520754ddb8223252e7e6e7584ddb956ef1bb28628e27cfea86c6

-->

The garbage block is randomly generated to make it hard to compress.  I experimented with how long the blocks of garbage needed to be.  When I got the form size up to about 200K, the spam messages stopped.

This is actually not a lot of extra data, about like adding a few extra images to the page.  Even for a hypothetical customer on dialup, the delay between rendering the text box and rendering the submit button is shorter than the time it would probably take to actually compose a message.


问:
How to query search numbers in php mysql
I need a search query.
Age value 10 - 15 , 20 - 25 , 17 - 19 , 12 - 59 , 2 - 19 , 18 - 40 , 10 - 20

I send 10 - 25 and I want to get results by matching the numbers

```<code><?php
  $Age1 = 10;
  $Age2 = 25;

  $Age = $Age1." - ".$Age2;

  $stmt = mysqli_query($con,"SELECT * FROM job_post_p1 where Age LIKE '%" . $Age .  "%'");

?>
</code>```

Thanks to All

答: $stmt = mysqli_query($con,"SELECT * FROM job_post_p1 where Age BETWEEN 10 AND 25");

Body:
I need a search query.
Age value 10 - 15 , 20 - 25 , 17 - 19 , 12 - 59 , 2 - 19 , 18 - 40 , 10 - 20

I send 10 - 25 and I want to get results by matching the numbers

<?php
  $Age1 = 10;
  $Age2 = 25;

  $Age = $Age1." - ".$Age2;

  $stmt = mysqli_query($con,"SELECT * FROM job_post_p1 where Age LIKE '%" . $Age .  "%'");

?>

Thanks to All


问:
Autoscaled web service running on EC2: use Auto Scaling Launch Config with custom AMI or use ECS?
It seems to me that there are two alternate ways of having an autoscaled web service running on EC2 instances behind an ELB:

1) create an Auto Scaling Launch Config that specifies the image id of my custom AMI (and the instance type to use). Then, when the Auto Scaling trigger is triggered, it will simply spin up new EC2 instances using that AMI.

2) Use ELB and ECS instead as ECS seems to have its own Auto Scaling feature.

In what circumstances is it better to use ECS?

答:
The two options are not mutually exclusive. To answer your last question first, you use ECS when you run containerized applications. You can scale these applications using the Service AutoScaling service in ECS. This will help you bring up additional containers when you're running short of resources to attend incoming requests.

This is different from scaling EC2 instances with a Launch Configuration. You'll need additional instances when you run out of resources in order to spin up new containers in your ECS cluster. By the way, you should always use a Launch Configuration in order bring new EC2 instances within an AutoScaling group bound to your ECS cluster, since it makes everything a lot easier. See for example this tutorial.

As for the ELB, in ECS you actually are better off using ALB. In containerized applications, you need to map their exposed ports to random ports in the host machine. This makes the registration with the load balance a lot more complicated. However, ALB is integrated with ECS so that, whenever you launch a new task, the ECS Service running the task requests a registration of the task as a target for the ALB (see this link for a more detailed explanation). It takes care of everything on your behalf.