问:
Dynamic array of Structs, delet elements
I am trying to create a database program of students where you should be able to add/modify and delete students. I have managed to get the add function working, and also the modify function but the delete function gives me some problems. my code seems to crash when im trying to delete a student from the database, can anyone tell me where the problem lies?

Here's my code:

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

/* TODO: Avoid global variables. */

struct student {
    char name[60];
    long long personalNumber;
    char gender[6];
    char studyProgram[60];
    char email[30];
    int age;
};

struct student *pointer = NULL;
int numberofstudents = 0;

void modify()
{
    long long persnr;
    long long comp;
    int match = 0;
    printf("Please enter the personal number that you wish to modify: \n");
    scanf("%lld", &persnr);
    getchar();

    for(int i = 0; i <= numberofstudents; i++)
    {
        comp = ((pointer+i)->personalNumber);
        printf("%lld\n", ((pointer+i)->personalNumber));
        printf("%lld\n", comp);

        printf("Inne");
        if (pointer[i].personalNumber == persnr && match == 0)
        {
            printf("Enter name, personalnumber, gender, studyprogram, email and age in this order\n");
            scanf("%s%lld%s%s%s%d", (pointer+i)->name, &(pointer+i)->personalNumber, (pointer+i)->gender, (pointer+i)->studyProgram, (pointer+i)->email, &(pointer+i)->age);
            match = 1;
            getchar();
        }
       if (match == 0)
       {
           printf("Could not find person");
       }

    }
}

void deletestudent()
{
    long long persnr;
    long long comp;
    int match = 0;
    printf("Please enter the personal number that you wish to delete: \n");
    scanf("%lld", &persnr);
    getchar();

    struct student *temporary = malloc((numberofstudents - 1) * sizeof(struct student));

    for(int i = 0; i <= numberofstudents; i++)
    {
        if (pointer[i].personalNumber == persnr && match == 0)
        {
            match = 1;
        }
        else if (match == 1){
            temporary[i-1] = pointer[i];
        }
        else
        {
            temporary[i] = pointer[i];
        }

       if (match == 0)
       {
           printf("Could not find person");
       }

    }
    free(pointer);
    pointer = temporary;

    }

void add(){

        if (numberofstudents > 0)
        {
            pointer = (struct student*) realloc(pointer, (numberofstudents+1) * sizeof(struct student));

            printf("Lyckades allokeringen!\n\n");
        }

        printf("Enter name, personalnumber, gender, studyprogram, email and age in this order\n");
        scanf("%s%lld%s%s%s%d", (pointer+numberofstudents)->name, &(pointer+numberofstudents)->personalNumber, (pointer+numberofstudents)->gender, (pointer+numberofstudents)->studyProgram, (pointer+numberofstudents)->email, &(pointer+numberofstudents)->age);
        getchar();
        printf("Visar data:\n");

        for(int i = 0; i <= numberofstudents; ++i)
        {
            printf("%s\t%lld\t%s\t%s\t%s\t%d\n", (pointer+i)->name, (pointer+i)->personalNumber, (pointer+i)->gender, (pointer+i)->studyProgram, (pointer+i)->email, (pointer+i)->age);
        }
        numberofstudents = numberofstudents+1;
    }

int main(void)
{
    pointer = (struct student*) malloc(2 * sizeof(struct student));

    if (pointer == NULL)
{
    printf("pointer NULL");
    exit(1);
}

    int run = 1;
    int choice;

    while (run == 1)
    {
        printf("Please enter an option listed below\n1.ADD\n2.Modify\n3.Delete\n4.Search\n5.Save\n6.Load\n7.Exit");
        scanf("%d", &choice);
        getchar();

        switch(choice) {

   case 1 :
      add();
      break;

   case 2 :
      modify();
      break;
   case 3 :
      deletestudent();

   case 7 :
      exit(0);
      break;

    default :

      break;
}

    }

    return 0;
}
</code>```

答:
As mentioned in a comment, this:

```<code>for(int i = 0; i <= numberofstudents; i++)
</code>```

is a huge warning sign. In C, such a loop should typically have i < numberofstudents in it, assuming numberofstudents is the actual length of the array.

Using <= rather than < makes the loop go one step too far, thus indexing outside the array and causing undefined behavior.

Writing outside heap-allocated memory and then trying to free() it is a good way to provoke crashes, since there's a chance you're stepping on the heap allocator's data structures (in practice; in theory all that happens is that you get undefined behavior and thus anything can happen).

Body:
I am trying to create a database program of students where you should be able to add/modify and delete students. I have managed to get the add function working, and also the modify function but the delete function gives me some problems. my code seems to crash when im trying to delete a student from the database, can anyone tell me where the problem lies?

Here's my code:

    #include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* TODO: Avoid global variables. */

struct student {
    char name[60];
    long long personalNumber;
    char gender[6];
    char studyProgram[60];
    char email[30];
    int age;
};

struct student *pointer = NULL;
int numberofstudents = 0;

void modify()
{
    long long persnr;
    long long comp;
    int match = 0;
    printf("Please enter the personal number that you wish to modify: \n");
    scanf("%lld", &persnr);
    getchar();

    for(int i = 0; i <= numberofstudents; i++)
    {
        comp = ((pointer+i)->personalNumber);
        printf("%lld\n", ((pointer+i)->personalNumber));
        printf("%lld\n", comp);

        printf("Inne");
        if (pointer[i].personalNumber == persnr && match == 0)
        {
            printf("Enter name, personalnumber, gender, studyprogram, email and age in this order\n");
            scanf("%s%lld%s%s%s%d", (pointer+i)->name, &(pointer+i)->personalNumber, (pointer+i)->gender, (pointer+i)->studyProgram, (pointer+i)->email, &(pointer+i)->age);
            match = 1;
            getchar();
        }
       if (match == 0)
       {
           printf("Could not find person");
       }

    }
}

void deletestudent()
{
    long long persnr;
    long long comp;
    int match = 0;
    printf("Please enter the personal number that you wish to delete: \n");
    scanf("%lld", &persnr);
    getchar();

    struct student *temporary = malloc((numberofstudents - 1) * sizeof(struct student));

    for(int i = 0; i <= numberofstudents; i++)
    {
        if (pointer[i].personalNumber == persnr && match == 0)
        {
            match = 1;
        }
        else if (match == 1){
            temporary[i-1] = pointer[i];
        }
        else
        {
            temporary[i] = pointer[i];
        }

       if (match == 0)
       {
           printf("Could not find person");
       }

    }
    free(pointer);
    pointer = temporary;

    }

void add(){

        if (numberofstudents > 0)
        {
            pointer = (struct student*) realloc(pointer, (numberofstudents+1) * sizeof(struct student));

            printf("Lyckades allokeringen!\n\n");
        }

        printf("Enter name, personalnumber, gender, studyprogram, email and age in this order\n");
        scanf("%s%lld%s%s%s%d", (pointer+numberofstudents)->name, &(pointer+numberofstudents)->personalNumber, (pointer+numberofstudents)->gender, (pointer+numberofstudents)->studyProgram, (pointer+numberofstudents)->email, &(pointer+numberofstudents)->age);
        getchar();
        printf("Visar data:\n");

        for(int i = 0; i <= numberofstudents; ++i)
        {
            printf("%s\t%lld\t%s\t%s\t%s\t%d\n", (pointer+i)->name, (pointer+i)->personalNumber, (pointer+i)->gender, (pointer+i)->studyProgram, (pointer+i)->email, (pointer+i)->age);
        }
        numberofstudents = numberofstudents+1;
    }

int main(void)
{
    pointer = (struct student*) malloc(2 * sizeof(struct student));

    if (pointer == NULL)
{
    printf("pointer NULL");
    exit(1);
}

    int run = 1;
    int choice;

    while (run == 1)
    {
        printf("Please enter an option listed below\n1.ADD\n2.Modify\n3.Delete\n4.Search\n5.Save\n6.Load\n7.Exit");
        scanf("%d", &choice);
        getchar();

        switch(choice) {

   case 1 :
      add();
      break;

   case 2 :
      modify();
      break;
   case 3 :
      deletestudent();

   case 7 :
      exit(0);
      break;

    default :

      break;
}

    }

    return 0;
}

Body:
As mentioned in a comment, this:

for(int i = 0; i <= numberofstudents; i++)

is a huge warning sign. In C, such a loop should typically have i < numberofstudents in it, assuming numberofstudents is the actual length of the array.

Using <= rather than < makes the loop go one step too far, thus indexing outside the array and causing undefined behavior.

Writing outside heap-allocated memory and then trying to free() it is a good way to provoke crashes, since there's a chance you're stepping on the heap allocator's data structures (in practice; in theory all that happens is that you get undefined behavior and thus anything can happen).


来源: stackexchange

问:
How to add mapviews in listview? Android
I want to display multiple maps in my layout.

In my fragment I have a list view, in the list view item I have a mapView

```<code>    <com.google.android.gms.maps.MapView
                android:id="@+id/map_view"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" />
</code>```

In the adapter file, in my get view method I do :

```<code>   holder.mapView.getMapAsync(new OnMapReadyCallback() {

        @Override
        public void onMapReady(GoogleMap googleMap) {
            LatLng sydney = new LatLng(-33.852, 151.211);
            googleMap.addMarker(new MarkerOptions().position(sydney)
                    .title("Marker in Sydney"));
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
            holder.mapView.onResume();
        }
    });
</code>```

But nothing shows up.

I have created a google maps API key, and added the following to my manifest.

```<code>    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="my api key, not restricted"/>
</code>```

And I have added this dependency in the griddle file:

```<code>   compile 'com.google.android.gms:play-services-maps:10.2.1'
</code>```

Do you know why there is no map showing?

答:
Go to :
file - new - google - Google Maps Activity and Understand the things.

Add this in your xml

```<code>tools:context="yourpackage.YourActivityName"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to display multiple maps in my layout.

In my fragment I have a list view, in the list view item I have a mapView

    <com.google.android.gms.maps.MapView
                android:id="@+id/map_view"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" />

In the adapter file, in my get view method I do :

   holder.mapView.getMapAsync(new OnMapReadyCallback() {

        @Override
        public void onMapReady(GoogleMap googleMap) {
            LatLng sydney = new LatLng(-33.852, 151.211);
            googleMap.addMarker(new MarkerOptions().position(sydney)
                    .title("Marker in Sydney"));
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
            holder.mapView.onResume();
        }
    });

But nothing shows up.

I have created a google maps API key, and added the following to my manifest.

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="my api key, not restricted"/>

And I have added this dependency in the griddle file:

   compile 'com.google.android.gms:play-services-maps:10.2.1'

Do you know why there is no map showing?

Body:
Go to :
file - new - google - Google Maps Activity and Understand the things.

Add this in your xml

tools:context="yourpackage.YourActivityName"


问:
openstack CRITICAL keystonemiddleware.auth_token [-] Unable to validate
I'm installing Openstack Newton on Ubuntu 16.04 manually using the install documentation:
https://docs.openstack.org/newton/install-guide-ubuntu/glance-install.html

I missed a few bits in glance-registry.conf before populating the image service database.
I then went back and fixed everything, populated DB again (sudo su -s /bin/sh -c "glance-manage db_sync" glance)
Restarted service, loaded admin creds and tried creating Cirros image but keep getting the following errors:

```<code>user1@controller:~$ openstack image create "cirros" --file cirros-0.3.4-x86_64-disk.img --disk-format qcow2 --container-format bare --public
503 Service Unavailable
The server is currently unavailable. Please try again at a later time.
    (HTTP 503)
</code>```

glance-registry.log seems fine:
(Note not entire log)

```<code>2017-03-29 11:33:39.073 2084 INFO glance.common.wsgi [-] Starting 6 workers
2017-03-29 11:33:39.083 2084 INFO glance.common.wsgi [-] Started child 2119
2017-03-29 11:33:39.084 2119 INFO eventlet.wsgi.server [-] (2119) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.086 2084 INFO glance.common.wsgi [-] Started child 2120
2017-03-29 11:33:39.087 2120 INFO eventlet.wsgi.server [-] (2120) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.090 2084 INFO glance.common.wsgi [-] Started child 2121
2017-03-29 11:33:39.091 2121 INFO eventlet.wsgi.server [-] (2121) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.093 2084 INFO glance.common.wsgi [-] Started child 2122
2017-03-29 11:33:39.094 2122 INFO eventlet.wsgi.server [-] (2122) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.096 2084 INFO glance.common.wsgi [-] Started child 2123
2017-03-29 11:33:39.097 2123 INFO eventlet.wsgi.server [-] (2123) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.100 2084 INFO glance.common.wsgi [-] Started child 2124
2017-03-29 11:33:39.101 2124 INFO eventlet.wsgi.server [-] (2124) wsgi starting up on http://0.0.0.0:9191
</code>```

glance-api.log has some errors:
(Note not entire log)

```<code>2017-03-29 11:33:39.326 2088 INFO glance.common.wsgi [-] Started child 2127
2017-03-29 11:33:39.327 2127 INFO eventlet.wsgi.server [-] (2127) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:33:39.330 2088 INFO glance.common.wsgi [-] Started child 2128
2017-03-29 11:33:39.330 2128 INFO eventlet.wsgi.server [-] (2128) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:33:39.334 2088 INFO glance.common.wsgi [-] Started child 2129
2017-03-29 11:33:39.334 2129 INFO eventlet.wsgi.server [-] (2129) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:33:39.338 2088 INFO glance.common.wsgi [-] Started child 2130
2017-03-29 11:33:39.339 2130 INFO eventlet.wsgi.server [-] (2130) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:36:44.200 2126 WARNING keystonemiddleware.auth_token [-] Identity response: {"error": {"message": "The request you have made requires authentication.", "code": 401, "title": "Unauthorized"}}
2017-03-29 11:36:44.322 2126 WARNING keystonemiddleware.auth_token [-] Identity response: {"error": {"message": "The request you have made requires authentication.", "code": 401, "title": "Unauthorized"}}
2017-03-29 11:36:44.323 2126 CRITICAL keystonemiddleware.auth_token [-] Unable to validate token: Identity server rejected authorization necessary to fetch token data
2017-03-29 11:36:44.326 2126 INFO eventlet.wsgi.server [-] 192.168.10.11 - - [29/Mar/2017 11:36:44] "GET /v2/schemas/image HTTP/1.1" 503 259 2.551519
</code>```

admin-openrc

```<code>export OS_PROJECT_DOMAIN_NAME=Default
export OS_USER_DOMAIN_NAME=Default
export OS_PROJECT_NAME=admin
export OS_USERNAME=admin
export OS_PASSWORD=PASSWORDHERE
export OS_AUTH_URL=http://controller:35357/v3
export OS_IDENTITY_API_VERSION=3
export OS_IMAGE_API_VERSION=2
</code>```

Any suggestions?

/var/log/apache2/error.log

```<code>[Wed Mar 29 09:09:24.843764 2017] [wsgi:warn] [pid 1689:tid 139998635640704] mod_wsgi: Compiled for Python/2.7.11.
[Wed Mar 29 09:09:24.852363 2017] [wsgi:warn] [pid 1689:tid 139998635640704] mod_wsgi: Runtime using Python/2.7.12.
[Wed Mar 29 09:09:24.855349 2017] [mpm_event:notice] [pid 1689:tid 139998635640704] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations
[Wed Mar 29 09:09:24.855369 2017] [core:notice] [pid 1689:tid 139998635640704] AH00094: Command line: '/usr/sbin/apache2'
[Wed Mar 29 10:20:52.529214 2017] [mpm_event:notice] [pid 1689:tid 139998635640704] AH00491: caught SIGTERM, shutting down
[Wed Mar 29 10:22:50.037927 2017] [wsgi:warn] [pid 1571:tid 140332865791872] mod_wsgi: Compiled for Python/2.7.11.
[Wed Mar 29 10:22:50.068187 2017] [wsgi:warn] [pid 1571:tid 140332865791872] mod_wsgi: Runtime using Python/2.7.12.
[Wed Mar 29 10:22:50.070975 2017] [mpm_event:notice] [pid 1571:tid 140332865791872] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations
[Wed Mar 29 10:22:50.071001 2017] [core:notice] [pid 1571:tid 140332865791872] AH00094: Command line: '/usr/sbin/apache2'
[Wed Mar 29 11:31:31.911160 2017] [mpm_event:notice] [pid 1571:tid 140332865791872] AH00491: caught SIGTERM, shutting down
[Wed Mar 29 11:33:34.967332 2017] [wsgi:warn] [pid 1559:tid 139850139666304] mod_wsgi: Compiled for Python/2.7.11.
[Wed Mar 29 11:33:34.979608 2017] [wsgi:warn] [pid 1559:tid 139850139666304] mod_wsgi: Runtime using Python/2.7.12.
[Wed Mar 29 11:33:34.982567 2017] [mpm_event:notice] [pid 1559:tid 139850139666304] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations
[Wed Mar 29 11:33:34.982589 2017] [core:notice] [pid 1559:tid 139850139666304] AH00094: Command line: '/usr/sbin/apache2'
[Wed Mar 29 12:03:56.366665 2017] [mpm_event:notice] [pid 1559:tid 139850139666304] AH00491: caught SIGTERM, shutting down
[Thu Mar 30 13:10:43.749039 2017] [wsgi:warn] [pid 1682:tid 139702919534464] mod_wsgi: Compiled for Python/2.7.11.
[Thu Mar 30 13:10:43.764797 2017] [wsgi:warn] [pid 1682:tid 139702919534464] mod_wsgi: Runtime using Python/2.7.12.
[Thu Mar 30 13:10:43.768481 2017] [mpm_event:notice] [pid 1682:tid 139702919534464] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations
[Thu Mar 30 13:10:43.768511 2017] [core:notice] [pid 1682:tid 139702919534464] AH00094: Command line: '/usr/sbin/apache2'
</code>```

/var/log/glance/glance-api.log

```<code>2017-03-29 11:33:39.326 2088 INFO glance.common.wsgi [-] Started child 2127
2017-03-29 11:33:39.327 2127 INFO eventlet.wsgi.server [-] (2127) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:33:39.330 2088 INFO glance.common.wsgi [-] Started child 2128
2017-03-29 11:33:39.330 2128 INFO eventlet.wsgi.server [-] (2128) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:33:39.334 2088 INFO glance.common.wsgi [-] Started child 2129
2017-03-29 11:33:39.334 2129 INFO eventlet.wsgi.server [-] (2129) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:33:39.338 2088 INFO glance.common.wsgi [-] Started child 2130
2017-03-29 11:33:39.339 2130 INFO eventlet.wsgi.server [-] (2130) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:36:44.200 2126 WARNING keystonemiddleware.auth_token [-] Identity response: {"error": {"message": "The request you have made requires authentication.", "code": 401, "title": "Unauthorized"}}
2017-03-29 11:36:44.322 2126 WARNING keystonemiddleware.auth_token [-] Identity response: {"error": {"message": "The request you have made requires authentication.", "code": 401, "title": "Unauthorized"}}
2017-03-29 11:36:44.323 2126 CRITICAL keystonemiddleware.auth_token [-] Unable to validate token: Identity server rejected authorization necessary to fetch token data
2017-03-29 11:36:44.326 2126 INFO eventlet.wsgi.server [-] 192.168.10.11 - - [29/Mar/2017 11:36:44] "GET /v2/schemas/image HTTP/1.1" 503 259 2.551519
</code>```

/var/log/glance/glance-registry.log

```<code>2017-03-29 11:33:39.073 2084 INFO glance.common.wsgi [-] Starting 6 workers
2017-03-29 11:33:39.083 2084 INFO glance.common.wsgi [-] Started child 2119
2017-03-29 11:33:39.084 2119 INFO eventlet.wsgi.server [-] (2119) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.086 2084 INFO glance.common.wsgi [-] Started child 2120
2017-03-29 11:33:39.087 2120 INFO eventlet.wsgi.server [-] (2120) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.090 2084 INFO glance.common.wsgi [-] Started child 2121
2017-03-29 11:33:39.091 2121 INFO eventlet.wsgi.server [-] (2121) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.093 2084 INFO glance.common.wsgi [-] Started child 2122
2017-03-29 11:33:39.094 2122 INFO eventlet.wsgi.server [-] (2122) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.096 2084 INFO glance.common.wsgi [-] Started child 2123
2017-03-29 11:33:39.097 2123 INFO eventlet.wsgi.server [-] (2123) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.100 2084 INFO glance.common.wsgi [-] Started child 2124
2017-03-29 11:33:39.101 2124 INFO eventlet.wsgi.server [-] (2124) wsgi starting up on http://0.0.0.0:9191
</code>```

答:
Below error may indicate that your glance is missing keystone credentials, in your glance config file you should have:

```<code>[keystone_authtoken]
admin_user=glance
admin_password=___SOME_SECRET_PASSWORD_GOES_HERE___
admin_tenant_name=service
</code>```

2017-03-29 11:36:44.200 2126 WARNING keystonemiddleware.auth_token [-]
  Identity response: {"error": {"message": "The request you have made
  requires authentication.", "code": 401, "title": "Unauthorized"}}
  2017-03-29 11:36:44.322 2126 WARNING keystonemiddleware.auth_token [-]
  Identity response: {"error": {"message": "The request you have made
  requires authentication.", "code": 401, "title": "Unauthorized"}}
  2017-03-29 11:36:44.323 2126 CRITICAL keystonemiddleware.auth_token
  [-] Unable to validate token: Identity server rejected authorization
  necessary to fetch token data

Body:
I'm installing Openstack Newton on Ubuntu 16.04 manually using the install documentation:
https://docs.openstack.org/newton/install-guide-ubuntu/glance-install.html

I missed a few bits in glance-registry.conf before populating the image service database.
I then went back and fixed everything, populated DB again (sudo su -s /bin/sh -c "glance-manage db_sync" glance)
Restarted service, loaded admin creds and tried creating Cirros image but keep getting the following errors:

user1@controller:~$ openstack image create "cirros" --file cirros-0.3.4-x86_64-disk.img --disk-format qcow2 --container-format bare --public
503 Service Unavailable
The server is currently unavailable. Please try again at a later time.
    (HTTP 503)

glance-registry.log seems fine:
(Note not entire log)

2017-03-29 11:33:39.073 2084 INFO glance.common.wsgi [-] Starting 6 workers
2017-03-29 11:33:39.083 2084 INFO glance.common.wsgi [-] Started child 2119
2017-03-29 11:33:39.084 2119 INFO eventlet.wsgi.server [-] (2119) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.086 2084 INFO glance.common.wsgi [-] Started child 2120
2017-03-29 11:33:39.087 2120 INFO eventlet.wsgi.server [-] (2120) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.090 2084 INFO glance.common.wsgi [-] Started child 2121
2017-03-29 11:33:39.091 2121 INFO eventlet.wsgi.server [-] (2121) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.093 2084 INFO glance.common.wsgi [-] Started child 2122
2017-03-29 11:33:39.094 2122 INFO eventlet.wsgi.server [-] (2122) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.096 2084 INFO glance.common.wsgi [-] Started child 2123
2017-03-29 11:33:39.097 2123 INFO eventlet.wsgi.server [-] (2123) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.100 2084 INFO glance.common.wsgi [-] Started child 2124
2017-03-29 11:33:39.101 2124 INFO eventlet.wsgi.server [-] (2124) wsgi starting up on http://0.0.0.0:9191

glance-api.log has some errors:
(Note not entire log)

2017-03-29 11:33:39.326 2088 INFO glance.common.wsgi [-] Started child 2127
2017-03-29 11:33:39.327 2127 INFO eventlet.wsgi.server [-] (2127) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:33:39.330 2088 INFO glance.common.wsgi [-] Started child 2128
2017-03-29 11:33:39.330 2128 INFO eventlet.wsgi.server [-] (2128) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:33:39.334 2088 INFO glance.common.wsgi [-] Started child 2129
2017-03-29 11:33:39.334 2129 INFO eventlet.wsgi.server [-] (2129) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:33:39.338 2088 INFO glance.common.wsgi [-] Started child 2130
2017-03-29 11:33:39.339 2130 INFO eventlet.wsgi.server [-] (2130) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:36:44.200 2126 WARNING keystonemiddleware.auth_token [-] Identity response: {"error": {"message": "The request you have made requires authentication.", "code": 401, "title": "Unauthorized"}}
2017-03-29 11:36:44.322 2126 WARNING keystonemiddleware.auth_token [-] Identity response: {"error": {"message": "The request you have made requires authentication.", "code": 401, "title": "Unauthorized"}}
2017-03-29 11:36:44.323 2126 CRITICAL keystonemiddleware.auth_token [-] Unable to validate token: Identity server rejected authorization necessary to fetch token data
2017-03-29 11:36:44.326 2126 INFO eventlet.wsgi.server [-] 192.168.10.11 - - [29/Mar/2017 11:36:44] "GET /v2/schemas/image HTTP/1.1" 503 259 2.551519

admin-openrc

export OS_PROJECT_DOMAIN_NAME=Default
export OS_USER_DOMAIN_NAME=Default
export OS_PROJECT_NAME=admin
export OS_USERNAME=admin
export OS_PASSWORD=PASSWORDHERE
export OS_AUTH_URL=http://controller:35357/v3
export OS_IDENTITY_API_VERSION=3
export OS_IMAGE_API_VERSION=2

Any suggestions?

/var/log/apache2/error.log

[Wed Mar 29 09:09:24.843764 2017] [wsgi:warn] [pid 1689:tid 139998635640704] mod_wsgi: Compiled for Python/2.7.11.
[Wed Mar 29 09:09:24.852363 2017] [wsgi:warn] [pid 1689:tid 139998635640704] mod_wsgi: Runtime using Python/2.7.12.
[Wed Mar 29 09:09:24.855349 2017] [mpm_event:notice] [pid 1689:tid 139998635640704] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations
[Wed Mar 29 09:09:24.855369 2017] [core:notice] [pid 1689:tid 139998635640704] AH00094: Command line: '/usr/sbin/apache2'
[Wed Mar 29 10:20:52.529214 2017] [mpm_event:notice] [pid 1689:tid 139998635640704] AH00491: caught SIGTERM, shutting down
[Wed Mar 29 10:22:50.037927 2017] [wsgi:warn] [pid 1571:tid 140332865791872] mod_wsgi: Compiled for Python/2.7.11.
[Wed Mar 29 10:22:50.068187 2017] [wsgi:warn] [pid 1571:tid 140332865791872] mod_wsgi: Runtime using Python/2.7.12.
[Wed Mar 29 10:22:50.070975 2017] [mpm_event:notice] [pid 1571:tid 140332865791872] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations
[Wed Mar 29 10:22:50.071001 2017] [core:notice] [pid 1571:tid 140332865791872] AH00094: Command line: '/usr/sbin/apache2'
[Wed Mar 29 11:31:31.911160 2017] [mpm_event:notice] [pid 1571:tid 140332865791872] AH00491: caught SIGTERM, shutting down
[Wed Mar 29 11:33:34.967332 2017] [wsgi:warn] [pid 1559:tid 139850139666304] mod_wsgi: Compiled for Python/2.7.11.
[Wed Mar 29 11:33:34.979608 2017] [wsgi:warn] [pid 1559:tid 139850139666304] mod_wsgi: Runtime using Python/2.7.12.
[Wed Mar 29 11:33:34.982567 2017] [mpm_event:notice] [pid 1559:tid 139850139666304] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations
[Wed Mar 29 11:33:34.982589 2017] [core:notice] [pid 1559:tid 139850139666304] AH00094: Command line: '/usr/sbin/apache2'
[Wed Mar 29 12:03:56.366665 2017] [mpm_event:notice] [pid 1559:tid 139850139666304] AH00491: caught SIGTERM, shutting down
[Thu Mar 30 13:10:43.749039 2017] [wsgi:warn] [pid 1682:tid 139702919534464] mod_wsgi: Compiled for Python/2.7.11.
[Thu Mar 30 13:10:43.764797 2017] [wsgi:warn] [pid 1682:tid 139702919534464] mod_wsgi: Runtime using Python/2.7.12.
[Thu Mar 30 13:10:43.768481 2017] [mpm_event:notice] [pid 1682:tid 139702919534464] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations
[Thu Mar 30 13:10:43.768511 2017] [core:notice] [pid 1682:tid 139702919534464] AH00094: Command line: '/usr/sbin/apache2'

/var/log/glance/glance-api.log

2017-03-29 11:33:39.326 2088 INFO glance.common.wsgi [-] Started child 2127
2017-03-29 11:33:39.327 2127 INFO eventlet.wsgi.server [-] (2127) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:33:39.330 2088 INFO glance.common.wsgi [-] Started child 2128
2017-03-29 11:33:39.330 2128 INFO eventlet.wsgi.server [-] (2128) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:33:39.334 2088 INFO glance.common.wsgi [-] Started child 2129
2017-03-29 11:33:39.334 2129 INFO eventlet.wsgi.server [-] (2129) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:33:39.338 2088 INFO glance.common.wsgi [-] Started child 2130
2017-03-29 11:33:39.339 2130 INFO eventlet.wsgi.server [-] (2130) wsgi starting up on http://0.0.0.0:9292
2017-03-29 11:36:44.200 2126 WARNING keystonemiddleware.auth_token [-] Identity response: {"error": {"message": "The request you have made requires authentication.", "code": 401, "title": "Unauthorized"}}
2017-03-29 11:36:44.322 2126 WARNING keystonemiddleware.auth_token [-] Identity response: {"error": {"message": "The request you have made requires authentication.", "code": 401, "title": "Unauthorized"}}
2017-03-29 11:36:44.323 2126 CRITICAL keystonemiddleware.auth_token [-] Unable to validate token: Identity server rejected authorization necessary to fetch token data
2017-03-29 11:36:44.326 2126 INFO eventlet.wsgi.server [-] 192.168.10.11 - - [29/Mar/2017 11:36:44] "GET /v2/schemas/image HTTP/1.1" 503 259 2.551519

/var/log/glance/glance-registry.log

2017-03-29 11:33:39.073 2084 INFO glance.common.wsgi [-] Starting 6 workers
2017-03-29 11:33:39.083 2084 INFO glance.common.wsgi [-] Started child 2119
2017-03-29 11:33:39.084 2119 INFO eventlet.wsgi.server [-] (2119) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.086 2084 INFO glance.common.wsgi [-] Started child 2120
2017-03-29 11:33:39.087 2120 INFO eventlet.wsgi.server [-] (2120) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.090 2084 INFO glance.common.wsgi [-] Started child 2121
2017-03-29 11:33:39.091 2121 INFO eventlet.wsgi.server [-] (2121) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.093 2084 INFO glance.common.wsgi [-] Started child 2122
2017-03-29 11:33:39.094 2122 INFO eventlet.wsgi.server [-] (2122) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.096 2084 INFO glance.common.wsgi [-] Started child 2123
2017-03-29 11:33:39.097 2123 INFO eventlet.wsgi.server [-] (2123) wsgi starting up on http://0.0.0.0:9191
2017-03-29 11:33:39.100 2084 INFO glance.common.wsgi [-] Started child 2124
2017-03-29 11:33:39.101 2124 INFO eventlet.wsgi.server [-] (2124) wsgi starting up on http://0.0.0.0:9191

Body:
Below error may indicate that your glance is missing keystone credentials, in your glance config file you should have:

[keystone_authtoken]
admin_user=glance
admin_password=___SOME_SECRET_PASSWORD_GOES_HERE___
admin_tenant_name=service

2017-03-29 11:36:44.200 2126 WARNING keystonemiddleware.auth_token [-]
  Identity response: {"error": {"message": "The request you have made
  requires authentication.", "code": 401, "title": "Unauthorized"}}
  2017-03-29 11:36:44.322 2126 WARNING keystonemiddleware.auth_token [-]
  Identity response: {"error": {"message": "The request you have made
  requires authentication.", "code": 401, "title": "Unauthorized"}}
  2017-03-29 11:36:44.323 2126 CRITICAL keystonemiddleware.auth_token
  [-] Unable to validate token: Identity server rejected authorization
  necessary to fetch token data


问:
Add field in checkout prestashop 1.7
I need some help with my checkout in prestashop 1.7
In the first step I want to delete "social title" and the box the says "får erbjudanden från våra partners" in English -> (Receive offers from our partners).
Se the attached picture step 1.

In the second step I want to change "Adresskomplement" in English -> (Address Complement) to Portkod (swedish) which means (gate access).
And also the other field to Övrigt or meddelande till Onlinesnacks.
There is also a little box at the end of step 2 which I want to delete.
Se the attached picture step 2.

and my last issue is in step 4. I want to delete the marked box on the picture step 4.

STEP 1

STEP 2

STEP 4

答:
In order to remove Title, find and comment this block in /classes/form/CustomerFormatter.php</p>

```<code>$genderField = (new FormField)
    ->setName('id_gender')
    ->setType('radio-buttons')
    ->setLabel(
        $this->translator->trans(
            'Social title', [], 'Shop.Forms.Labels'
        )
    )
;
foreach (Gender::getGenders($this->language->id) as $gender) {
    $genderField->addAvailableValue($gender->id, $gender->name);
}
$format[$genderField->getName()] = $genderField;
</code>```

Title: Add field in checkout prestashop 1.7

Body:
In order to remove Title, find and comment this block in /classes/form/CustomerFormatter.php

$genderField = (new FormField)
    ->setName('id_gender')
    ->setType('radio-buttons')
    ->setLabel(
        $this->translator->trans(
            'Social title', [], 'Shop.Forms.Labels'
        )
    )
;
foreach (Gender::getGenders($this->language->id) as $gender) {
    $genderField->addAvailableValue($gender->id, $gender->name);
}
$format[$genderField->getName()] = $genderField;


问:
Aggregate Data Based on Rows Python
I have a data set that looks like this:

```<code>      Date          | ID |  Task |   Description
2016-01-06 00:00:00 | 1  |  010  |   This is text
2016-01-06 00:10:00 | 1  |  020  |   This is text
2016-01-06 00:20:00 | 1  |  010  |   This is text
2016-01-06 01:00:00 | 1  |  020  |   This is text
2016-01-06 01:10:00 | 1  |  030  |   This is text
2016-02-06 00:00:00 | 2  |  010  |   This is text
2016-02-06 00:10:00 | 2  |  020  |   This is text
2016-02-06 00:20:00 | 2  |  010  |   This is text
2016-02-06 01:00:00 | 2  |  020  |   This is text
2016-02-06 01:01:00 | 2  |  030  |   This is text
</code>```

Task 020usually occurs after task 010 which means that when Task 020 starts means that task 010 ends, same applies for Task 020, if it comes before any other Task it means that it has stopped.

I need to group by Task calculating the average duration, total sum and count of each type of task in each ID, so I am looking for something like this:

```<code>ID  | Task | Average | Sum | Count
1   |  010 |   25    | 50  |  2
1   |  020 |   10    | 20  |  2
etc |  etc |   etc   | etc |  etc
</code>```

There are more IDs but I only care about 010  and 020, so whatever number is returned from them is acceptable.

Can someone help me on how to do this in Python?

ContentLicense: CC BY-SA 4.0

Title: Aggregate Data Based on Rows Python

Body:
I have a data set that looks like this:

      Date          | ID |  Task |   Description
2016-01-06 00:00:00 | 1  |  010  |   This is text
2016-01-06 00:10:00 | 1  |  020  |   This is text
2016-01-06 00:20:00 | 1  |  010  |   This is text
2016-01-06 01:00:00 | 1  |  020  |   This is text
2016-01-06 01:10:00 | 1  |  030  |   This is text
2016-02-06 00:00:00 | 2  |  010  |   This is text
2016-02-06 00:10:00 | 2  |  020  |   This is text
2016-02-06 00:20:00 | 2  |  010  |   This is text
2016-02-06 01:00:00 | 2  |  020  |   This is text
2016-02-06 01:01:00 | 2  |  030  |   This is text

Task 020usually occurs after task 010 which means that when Task 020 starts means that task 010 ends, same applies for Task 020, if it comes before any other Task it means that it has stopped.

I need to group by Task calculating the average duration, total sum and count of each type of task in each ID, so I am looking for something like this:

ID  | Task | Average | Sum | Count
1   |  010 |   25    | 50  |  2
1   |  020 |   10    | 20  |  2
etc |  etc |   etc   | etc |  etc

There are more IDs but I only care about 010  and 020, so whatever number is returned from them is acceptable.

Can someone help me on how to do this in Python?

Body:
It seems you need agg with groupby, but in sample not numeric column so col was added:

print (df)
                  Date  ID Task   Description      col
0  2016-01-06 00:00:00   1  010  This is text        1
1  2016-01-06 00:10:00   1  020  This is text        2
2  2016-01-06 00:20:00   1  010  This is text        6
3  2016-01-06 01:00:00   1  020  This is text        1
4  2016-01-06 01:10:00   1  030  This is text        3
5  2016-02-06 00:00:00   2  010  This is text        1
6  2016-02-06 00:10:00   2  020  This is text        8
7  2016-02-06 00:20:00   2  010  This is text        9
8  2016-02-06 01:00:00   2  020  This is text        1

df = df.groupby(['ID','Task'])['col'].agg(['sum','size', 'mean']).reset_index()
print (df)
   ID Task  sum  size  mean
0   1  010    7     2   3.5
1   1  020    3     2   1.5
2   1  030    3     1   3.0
3   2  010   10     2   5.0
4   2  020    9     2   4.5

If need aggreagte datetime, id is a bit complicated, because need timedeltas:

df.Date = pd.to_timedelta(df.Date).dt.total_seconds()
df = df.groupby(['ID','Task'])['Date']
       .agg(['sum','size', 'mean']).astype(np.int64).reset_index()
df['sum'] = pd.to_timedelta(df['sum'])
df['mean'] = pd.to_timedelta(df['mean'])
print (df)
   ID Task             sum  size            mean
0   1  010 00:00:02.904078     2 00:00:01.452039
1   1  020 00:00:02.904081     2 00:00:01.452040
2   1  030 00:00:01.452042     1 00:00:01.452042
3   2  010 00:00:02.909434     2 00:00:01.454717
4   2  020 00:00:02.909437     2 00:00:01.454718

For finding difference in column date:

print (df.Date.dtypes)
object

#if dtype of column is not datetime, first convert
df.Date = pd.to_datetime(df.Date )
print (df.Date.diff())
0                NaT
1    0 days 00:10:00
2    0 days 00:10:00
3    0 days 00:40:00
4    0 days 00:10:00
5   30 days 22:50:00
6    0 days 00:10:00
7    0 days 00:10:00
8    0 days 00:40:00
9    0 days 00:01:00
Name: Date, dtype: timedelta64[ns]


问:
How to make post request in CURL with Perfect
I have set up a Perfect server and I have written all my API but I'm stuck at the CURL, I don't know how do I set headers I have never worked before with CURL.

I am setting up a payment gateway and I want to set authorization headers and send body data but I dont know how to.

From example http://perfect.org/docs/cURL.html

```<code>let curlObject = CURL(url: "http://www.perfect.org")

curlObject.perform {
    code, header, body in

    print("Request error code \(code)")
    print("Response: \(curlObject.responseCode)")
    print("Header: \(header)")
    print("Body: \(body)")
}
</code>```

I referred this but got no help how to do?

https://curl.haxx.se/libcurl/c/

答:
UnsafeMutableRawPointer will be probably killed when you go async. This will work fine:</p>

```<code>import cURL
import PerfectCURL

public class CurlHTTPRequest {

    public static func post(url: String, header: String, body: String, callback: @escaping (String)->Void) {

        let byteArray:[UInt8] = Array(body.utf8)

        let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: byteArray.count)
        pointer.initialize(from: byteArray, count: byteArray.count)

        let curlObject = CURL(url: url)
        curlObject.setOption(CURLOPT_POST, int: 1)
        curlObject.setOption(CURLOPT_HTTPHEADER, s: header)
        curlObject.setOption(CURLOPT_SSL_VERIFYPEER, int: 0)
        curlObject.setOption(CURLOPT_POSTFIELDS, v: pointer)
        curlObject.setOption(CURLOPT_POSTFIELDSIZE, int: byteArray.count)

        curlObject.perform { (code, header, body) in

            curlObject.close()

            callback("Code: \(code)\n Header: \(String(bytes: header, encoding: .utf8) ?? "")\n Body: \(String(bytes: body, encoding: .utf8) ?? "")")

        }
    }
}
</code>```

Body:
I have set up a Perfect server and I have written all my API but I'm stuck at the CURL, I don't know how do I set headers I have never worked before with CURL.

I am setting up a payment gateway and I want to set authorization headers and send body data but I dont know how to.

From example http://perfect.org/docs/cURL.html

let curlObject = CURL(url: "http://www.perfect.org")

curlObject.perform {
    code, header, body in

    print("Request error code \(code)")
    print("Response: \(curlObject.responseCode)")
    print("Header: \(header)")
    print("Body: \(body)")
}

I referred this but got no help how to do?

https://curl.haxx.se/libcurl/c/

Body:
UnsafeMutableRawPointer will be probably killed when you go async. This will work fine:

import cURL
import PerfectCURL

public class CurlHTTPRequest {

    public static func post(url: String, header: String, body: String, callback: @escaping (String)->Void) {

        let byteArray:[UInt8] = Array(body.utf8)

        let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: byteArray.count)
        pointer.initialize(from: byteArray, count: byteArray.count)

        let curlObject = CURL(url: url)
        curlObject.setOption(CURLOPT_POST, int: 1)
        curlObject.setOption(CURLOPT_HTTPHEADER, s: header)
        curlObject.setOption(CURLOPT_SSL_VERIFYPEER, int: 0)
        curlObject.setOption(CURLOPT_POSTFIELDS, v: pointer)
        curlObject.setOption(CURLOPT_POSTFIELDSIZE, int: byteArray.count)

        curlObject.perform { (code, header, body) in

            curlObject.close()

            callback("Code: \(code)\n Header: \(String(bytes: header, encoding: .utf8) ?? "")\n Body: \(String(bytes: body, encoding: .utf8) ?? "")")

        }
    }
}


问:
ng-disabled on anchor inside

How can I disable drop down menu item that uses ui-router and looks like this?

```<code> <ul class="dropdown-menu">
    <li><a ui-sref="state.random">A random state</a></li>
</ul>
</code>```

obviously this doesn't work:

```<code><li ng-disabled="true"><a ui-sref="state.random">A random state</a></li>
</code>```

nor this:

```<code><li><a ui-sref="state.random" ng-disabled="true">A random state</a></li>
</code>```

答:
Disabling might not work here. You may have to use a ternary operator with ui-sref. As I assume disabling would be conditional. The disabled style effect can be introduced with CSS.

$scope.someValue = false;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><li>A random state</li></code>```

Title: ng-disabled on anchor inside <li>

Body:
How can I disable drop down menu item that uses ui-router and looks like this?

A random state

obviously this doesn't work:

A random state

nor this:

A random state

Body:
Disabling might not work here. You may have to use a ternary operator with ui-sref. As I assume disabling would be conditional. The disabled style effect can be introduced with CSS.

$scope.someValue = false;

<li><a ui-sref={{someValue ? 'state.random' : ''}}>A random state</a></li>


问:
Remove object from 2D Array- Processing
I'm creating a simple space invaders game. I'm looking to delete one of the invaders once they are hit by a bullet. The invaders are made up of a 2D array of images and I've tested the collision between the image and the bullet (in an ArrayList) and that works fine. So the game detects a collision, the next step is to delete the correct object that has been hit. I'm a little confused as to  how to correctly correspond where the bullet hits to which object it has hit in the 2D array, and then deleting it from the Array and carrying on with the game.

Below is how I created the invader array in setup()

  for(int i=0; i<2; i++){
    for(int j=0; j<4; j++){
        invArray[j][i]= new Taxi(taxiX, taxiY);
        taxiX= taxiX+ 100;
    }
    taxiX=20;
    taxiY= taxiY+ 140;
  }
```

<p>I then filled the 2D Array with images in draw()</p>

<pre class="lang-java prettyprint-override"><code> for(int i=0; i<2; i++){
      for(int j=0; j<4; j++){
        invArray[j][i].update();
        if(invArray[j][i].y>=600){
           invArray[j][i].y= 0;
           invArray[j][i].render();
        }
      }
    }
</code>```

答:
You're using arrays which are fixed size.
In theory you might be able to use array helper functions like shorten() and expand(), but you really got watch your counters and array structure.
In practice, for a beginner, I would say this is error prone.

It might be simpler(but hackier) to set the array element of the hit invader to null,
then simply check if the invader is not null before test collisions/rendering/etc.

e.g. in draw():

```<code>for(int i=0; i<2; i++){
      for(int j=0; j<4; j++){
        if(invArray[j][i] != null){
           invArray[j][i].update();
           if(invArray[j][i].y>=600){
              invArray[j][i].y= 0;
              invArray[j][i].render();
           }
         }
      }
    }
</code>```

Another option is to use an ArrayList which has a dynamic size.
e.g.

```<code>ArrayList<Taxi> invaders = new ArrayList<Taxi>();
</code>```

In setup you'd do something similar:

```<code>for(int i=0; i<2; i++){
    for(int j=0; j<4; j++){
        invaders.add(new Taxi(taxiX, taxiY));
        taxiX= taxiX+ 100;
    }
    taxiX=20;
    taxiY= taxiY+ 140;
  }
</code>```

then in draw():

```<code>for(int i = 0 ; i < invaders.size(); i++){
    Taxi t = invaders.get(i);
    t.update();
    if(t.y>=600){
       t.y= 0;
       t.render();
    }
    /*
    if(YOUR_HIT_CONDITION_HERE){
        invaders.remove(t);
    }
    */
}
</code>```

It's a bit tricky to go back and forth between 1D and 2D arrays/indexing at the beginning, but it's not that bad once you get the hand of it.

To convert from 2D x,y to 1D index:

int index = x + y * width;

(where x,y are you counters and width is the width of your grid (number of columns)).

The other way around, 1D index to 2D x,y:

int x = index % width;
 int y = index / width;

Title: Remove object from 2D Array- Processing

Body:
I'm creating a simple space invaders game. I'm looking to delete one of the invaders once they are hit by a bullet. The invaders are made up of a 2D array of images and I've tested the collision between the image and the bullet (in an ArrayList) and that works fine. So the game detects a collision, the next step is to delete the correct object that has been hit. I'm a little confused as to  how to correctly correspond where the bullet hits to which object it has hit in the 2D array, and then deleting it from the Array and carrying on with the game.

Below is how I created the invader array in setup()

  for(int i=0; i<2; i++){
    for(int j=0; j<4; j++){
        invArray[j][i]= new Taxi(taxiX, taxiY);
        taxiX= taxiX+ 100;
    }
    taxiX=20;
    taxiY= taxiY+ 140;
  }

I then filled the 2D Array with images in draw()

 for(int i=0; i<2; i++){
      for(int j=0; j<4; j++){
        invArray[j][i].update();
        if(invArray[j][i].y>=600){
           invArray[j][i].y= 0;
           invArray[j][i].render();
        }
      }
    }

Body:
You're using arrays which are fixed size.
In theory you might be able to use array helper functions like shorten() and expand(), but you really got watch your counters and array structure.
In practice, for a beginner, I would say this is error prone.

It might be simpler(but hackier) to set the array element of the hit invader to null,
then simply check if the invader is not null before test collisions/rendering/etc.

e.g. in draw():

for(int i=0; i<2; i++){
      for(int j=0; j<4; j++){
        if(invArray[j][i] != null){
           invArray[j][i].update();
           if(invArray[j][i].y>=600){
              invArray[j][i].y= 0;
              invArray[j][i].render();
           }
         }
      }
    }

Another option is to use an ArrayList which has a dynamic size.
e.g.

ArrayList<Taxi> invaders = new ArrayList<Taxi>();

In setup you'd do something similar:

for(int i=0; i<2; i++){
    for(int j=0; j<4; j++){
        invaders.add(new Taxi(taxiX, taxiY));
        taxiX= taxiX+ 100;
    }
    taxiX=20;
    taxiY= taxiY+ 140;
  }

then in draw():

for(int i = 0 ; i < invaders.size(); i++){
    Taxi t = invaders.get(i);
    t.update();
    if(t.y>=600){
       t.y= 0;
       t.render();
    }
    /*
    if(YOUR_HIT_CONDITION_HERE){
        invaders.remove(t);
    }
    */
}

It's a bit tricky to go back and forth between 1D and 2D arrays/indexing at the beginning, but it's not that bad once you get the hand of it.

To convert from 2D x,y to 1D index:

int index = x + y * width;

(where x,y are you counters and width is the width of your grid (number of columns)).

The other way around, 1D index to 2D x,y:

int x = index % width;
 int y = index / width;


问:
keep the selected parent menu open when a child menu is selected in Js accordian menu
when the page loads , one of the submenu of accordian is selected , so it should open the parent menu of the selected submenu  .

you can see in fiddle the 1st submenu of 1st parent menu is selcted but when it loads , it does not expand the 1st parent menu .

objective is to load menu 2  as esxpanded as the submenu 1 is already selected

check out this fiddle
https://jsfiddle.net/shaswatatripathy/ucgff65k/8/

--------------HTML--------------

```<code><ul id="accordion" class="accordion">
                         <li>
                            <div class="link">Menu 2</div>
                            <ul class="submenu">
                                <li class="active" ><a href="#">submenu1</a></li>
                                <li><a href="#">submenu1</a></li>
                                <li><a href="#">submenu1</a></li>
                            </ul>
                        </li>
                        <li>
                            <div class="link">Menu 3</div>
                            <ul class="submenu">
                                <li><a href="#">submenu1</a></li>
                                <li><a href="#">submenu1</a></li>
                                <li><a href="#">submenu1</a></li>
                            </ul>
                        </li>
                        </ul>
</code>```

答:
You can check the state of the sub items and open/show list if the one of the list item is active.

```<code>    if ($('#accordion .submenu li.active').length > 0 ) {
        $($('#accordion .submenu li.active')[0]).parent().show();
    }
</code>```

https://jsfiddle.net/xwfp6cy1/

Body:
when the page loads , one of the submenu of accordian is selected , so it should open the parent menu of the selected submenu  .

you can see in fiddle the 1st submenu of 1st parent menu is selcted but when it loads , it does not expand the 1st parent menu .

objective is to load menu 2  as esxpanded as the submenu 1 is already selected

check out this fiddle
https://jsfiddle.net/shaswatatripathy/ucgff65k/8/

--------------HTML--------------

Menu 2

submenu1

submenu1

submenu1

Menu 3

submenu1

submenu1

submenu1

Body:
You can check the state of the sub items and open/show list if the one of the list item is active.

    if ($('#accordion .submenu li.active').length > 0 ) {
        $($('#accordion .submenu li.active')[0]).parent().show();
    }

https://jsfiddle.net/xwfp6cy1/


问:
Extract lines corresponding to the minimum value in the last column
I need help with extracting all the lines from the file that has minimum number in the last column, i.e 7 in in this case.

The sample file is as below:

File-1.txt

```<code>VALID_PATH :  [102, 80, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 81, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 56, 23, 125, 111]  7
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 111] 8
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 111]  8
VALID_PATH :  [102, 80, 112, 109, 23, 125, 110, 111]    8
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 111] 9
VALID_PATH :  [102, 80, 127, 88, 112, 109, 23, 125, 111]    9
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 110, 111]    9
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 110, 111] 9
VALID_PATH :  [102, 80, 127, 6, 112, 37, 109, 23, 125, 111] 10
VALID_PATH :  [102, 80, 127, 6, 112, 37, 56, 23, 125, 111]  10
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 110, 111]    10
</code>```

Here, I want to extract all the lines that have 7, which is the least value (minimum value) in the last column and save the output into another file File-2.txt by only extracting the values enclosed in [], as shown below.

File-2.txt

```<code>102, 80, 112, 109, 23, 125, 111
102, 81, 112, 109, 23, 125, 111
102, 112, 37, 109, 23, 125, 111
102, 112, 37, 56, 23, 125, 111
</code>```

I could use awk to get the least value as "7" from the last column using the code as below:

```<code>awk 'BEGIN{getline;min=max=$NF}
NF{
    max=(max>$NF)?max:$NF
    min=(min>$NF)?$NF:min
}
END{print min,max}' File-1.txt
</code>```

and to print only the values in square brackets [] buy using the awk code as below:

```<code>awk 'NR > 1 {print $1}' RS='[' FS=']' File-1.txt
</code>```

but, I am stuck in assigning the least value obtained from first awk script, i.e. 7 in this case to extract the corresponding numbers enclosed in [], as shown in File-2.txt.

Any help in resolving this problem will be appreciated.

答:
read once (ex: for streaming/piped info) with minimum memory use</p>

```<code>awk -F'[][]' '
   # init counter
   NR == 1 { m = $3 + 1 }

   # add or replace content into the buffer if counter is lower or equal
   $3 <= m { b = ( $3 == m ? b "\n" : "" ) $2; m = $3 }

   # at the end, print buffer
   END { print b }
   ' YourFile
</code>```

Body:
I need help with extracting all the lines from the file that has minimum number in the last column, i.e 7 in in this case.

The sample file is as below:

File-1.txt

VALID_PATH :  [102, 80, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 81, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 56, 23, 125, 111]  7
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 111] 8
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 111]  8
VALID_PATH :  [102, 80, 112, 109, 23, 125, 110, 111]    8
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 111] 9
VALID_PATH :  [102, 80, 127, 88, 112, 109, 23, 125, 111]    9
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 110, 111]    9
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 110, 111] 9
VALID_PATH :  [102, 80, 127, 6, 112, 37, 109, 23, 125, 111] 10
VALID_PATH :  [102, 80, 127, 6, 112, 37, 56, 23, 125, 111]  10
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 110, 111]    10

Here, I want to extract all the lines that have 7, which is the least value (minimum value) in the last column and save the output into another file File-2.txt by only extracting the values enclosed in [], as shown below.

File-2.txt

102, 80, 112, 109, 23, 125, 111
102, 81, 112, 109, 23, 125, 111
102, 112, 37, 109, 23, 125, 111
102, 112, 37, 56, 23, 125, 111

I could use awk to get the least value as "7" from the last column using the code as below:

awk 'BEGIN{getline;min=max=$NF}
NF{
    max=(max>$NF)?max:$NF
    min=(min>$NF)?$NF:min
}
END{print min,max}' File-1.txt

and to print only the values in square brackets [] buy using the awk code as below:

awk 'NR > 1 {print $1}' RS='[' FS=']' File-1.txt

but, I am stuck in assigning the least value obtained from first awk script, i.e. 7 in this case to extract the corresponding numbers enclosed in [], as shown in File-2.txt.

Any help in resolving this problem will be appreciated.

Body:
read once (ex: for streaming/piped info) with minimum memory use

awk -F'[][]' '
   # init counter
   NR == 1 { m = $3 + 1 }

   # add or replace content into the buffer if counter is lower or equal
   $3 <= m { b = ( $3 == m ? b "\n" : "" ) $2; m = $3 }

   # at the end, print buffer
   END { print b }
   ' YourFile


问:
React Router always redirect me to a different url
I'm new to React and React Router. I'm using React Router v4 and following a tutorial based on previous versions - but I made it work (using some stuff found on SO and some stuff on the react router v4 docs).

There is one thing though that is bothering me.

I have a url http://localhost:3000/#/bugs, which basically loads a list of all my bugs. But I also have possible urls like http://localhost:3000/#/bugs?priority=low&status=open which loads a specific set of urls.

The urls themselves work and do the job as expected.

The werid thing is that whenever I type http://localhost:3000/#/bugs?priority=low&status=open (or any params), the component do their jobs but the URL address bar shows http://localhost:3000/#/bugs (although the rendering shows everything related to priority and status shown).

Somehow, the URL location bar is changed but I don't understand why.

Here is my App.js

import React from 'react';
import ReactDOM from 'react-dom';
import {BugList} from './BugList';
import {Redirect} from 'react-router';
import {HashRouter as Router, Route} from 'react-router-dom';

const NoMatch = React.createClass({
    render : function (){
        return(

This path does not exist

        );
    }
});

ReactDOM.render(
    (
        <Router>

                <Route path='/bugs' component={BugList}/>
                <Route path='/bugs/priority/:priority' component={BugList}/>
                <Redirect from='/' to="/bugs" />
                <Route path="*" component={NoMatch} />

        </Router>
    ),
    document.getElementById('main')
);
```

<p>Thanks in advance.</p>

<p><strong>EDIT 12th of April</strong>. Despite of the precious help of someone below, this is still not solved. I tried using Switch inside a Router but it doesn't work at all (nothing is shown). So the problem is still happening, and this is the current state of my App.js, using react-15.5.3, react-dom-15.5.3, react-router-4.0.0 and react-router-dom-4.0.0....</p>

<pre class="lang-jsx prettyprint-override"><code>import React from 'react';
import ReactDOM from 'react-dom';
import {BugList} from './BugList';
import BugEdit from './BugEdit';
import {Redirect} from 'react-router';
import {HashRouter as Router, Route} from 'react-router-dom';

const NoMatch = React.createClass({
    render : function (){
        return(
            <h2>This path does not exist</h2>
        );
    }
});

ReactDOM.render(
    (
        <Router>
            <div>
                <Redirect from='/' to="/bugs" />
                <Route path='/bugs' component={BugList}/>
                <Route path='/bug/:id' component={BugEdit}/>
                <Route path="*" component={NoMatch} />
            </div>
        </Router>
    ),
    document.getElementById('main')
);
</code>```

答:
The problem is that even if you enter the URL with query this URL matches Redirect path (since it's just / any URL matches this pattern) so the redirection to /bugs occurs. You have to use Switch (remember to import it) to render only the first <Route> or <Redirect> that matches the URL:

```<code><Router>
     <Switch>
        <Route path='/bugs' component={BugList}/>
        <Redirect from='/' to="/bugs" />
        ...
   </Switch>
</Router>
</code>```

The problem occured only on page load and not on re-entering the URL because your routing is based on hashes and the browser doesn't reload page when only hash part changes.

Please note that Redirect component in React-Router v4 performs redirection only when it's rendered - it doesn't set up permanent redirection rule so in your case redirection works only on page load. If you'd like your app to always redirect given URL you'd have to define Route for URL you'd like to redirect from and render Redirect:

```<code><Route path='/oldUrl' render={() => (
    <Redirect to="newUrl" />
)}/>
</code>```

Furthermore, React-Router v4 is quite different from v3 so I don't recommend using v3 tutorials - it doesn't make sense.

Body:
I'm new to React and React Router. I'm using React Router v4 and following a tutorial based on previous versions - but I made it work (using some stuff found on SO and some stuff on the react router v4 docs).

There is one thing though that is bothering me.

I have a url http://localhost:3000/#/bugs, which basically loads a list of all my bugs. But I also have possible urls like http://localhost:3000/#/bugs?priority=low&status=open which loads a specific set of urls.

The urls themselves work and do the job as expected.

The werid thing is that whenever I type http://localhost:3000/#/bugs?priority=low&status=open (or any params), the component do their jobs but the URL address bar shows http://localhost:3000/#/bugs (although the rendering shows everything related to priority and status shown).

Somehow, the URL location bar is changed but I don't understand why.

Here is my App.js

import React from 'react';
import ReactDOM from 'react-dom';
import {BugList} from './BugList';
import {Redirect} from 'react-router';
import {HashRouter as Router, Route} from 'react-router-dom';

const NoMatch = React.createClass({
    render : function (){
        return(

This path does not exist

        );
    }
});

ReactDOM.render(
    (
        <Router>

                <Route path='/bugs' component={BugList}/>
                <Route path='/bugs/priority/:priority' component={BugList}/>
                <Redirect from='/' to="/bugs" />
                <Route path="*" component={NoMatch} />

        </Router>
    ),
    document.getElementById('main')
);

Thanks in advance.

EDIT 12th of April. Despite of the precious help of someone below, this is still not solved. I tried using Switch inside a Router but it doesn't work at all (nothing is shown). So the problem is still happening, and this is the current state of my App.js, using react-15.5.3, react-dom-15.5.3, react-router-4.0.0 and react-router-dom-4.0.0....

import React from 'react';
import ReactDOM from 'react-dom';
import {BugList} from './BugList';
import BugEdit from './BugEdit';
import {Redirect} from 'react-router';
import {HashRouter as Router, Route} from 'react-router-dom';

const NoMatch = React.createClass({
    render : function (){
        return(

This path does not exist

        );
    }
});

ReactDOM.render(
    (
        <Router>

                <Redirect from='/' to="/bugs" />
                <Route path='/bugs' component={BugList}/>
                <Route path='/bug/:id' component={BugEdit}/>
                <Route path="*" component={NoMatch} />

        </Router>
    ),
    document.getElementById('main')
);

Body:
The problem is that even if you enter the URL with query this URL matches Redirect path (since it's just / any URL matches this pattern) so the redirection to /bugs occurs. You have to use Switch (remember to import it) to render only the first <Route> or <Redirect> that matches the URL:

<Router>
     <Switch>
        <Route path='/bugs' component={BugList}/>
        <Redirect from='/' to="/bugs" />
        ...
   </Switch>
</Router>

The problem occured only on page load and not on re-entering the URL because your routing is based on hashes and the browser doesn't reload page when only hash part changes.

Please note that Redirect component in React-Router v4 performs redirection only when it's rendered - it doesn't set up permanent redirection rule so in your case redirection works only on page load. If you'd like your app to always redirect given URL you'd have to define Route for URL you'd like to redirect from and render Redirect:

<Route path='/oldUrl' render={() => (
    <Redirect to="newUrl" />
)}/>

Furthermore, React-Router v4 is quite different from v3 so I don't recommend using v3 tutorials - it doesn't make sense.


问:
Best way to not run rufus-scheduler when starting a rails console
I use rufus-scheduler to run some periodic tasks, but they are extremely annoying to have in the rails console when I just want to test things.  Is there an easy way to stop all rufus-scheduler tasks when starting a console automatically?

In the code that starts the scheduler if i can check that i am just in a rails console I can not run them, or if there is a way to run some callbacks when the console starts I can also shut them down there.

Thanks

答:
As per the revised documentation for rufus-scheduler here:

If you don't want rufus-scheduler to kick in when running the Ruby on
  Rails console or invoking a rake task, you can wrap your initializer
  in a conditional:

```<code>unless defined?(Rails::Console) || File.split($0).last == 'rake'
  # your code here
end
</code>```

Body:
As per the revised documentation for rufus-scheduler here:

If you don't want rufus-scheduler to kick in when running the Ruby on
  Rails console or invoking a rake task, you can wrap your initializer
  in a conditional:

unless defined?(Rails::Console) || File.split($0).last == 'rake'
  # your code here
end


问:
Screen Overlay Detected but no solution in StackOverFlow worked for me
My problem is similar to Android "Screen Overlay Detected" message if user is trying to grant a permission when a notification is showing

But non of the solutions listed below work for me, I disabled all other apps that access overlay, but still no positive response same error.

What should I do to solve this.

Is this my development app error OR android system error? OR any other?

答:
Finally I found solution ,

Just install Install Button Unlocker from HERE

and follow the instructions mentioned in that application description.


问:
how to reduce 0(n) for finding the first instance of pairs that sum specific value
I am doing a codewars problem, the instructions are as follows: Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.

The solution works, but it is too slow for long arrays, how would someone do this without using two for loops? I have been trying to reduce the time complexity, but I am at a loss at how to accomplish this when I need to look at all possible pairs.

```<code>function sumPairs(ints, s){
    var lowestIdx1 = Infinity;
    var lowestIdx2 = Infinity;

    for (var i = 0; i < ints.length-1; i++) {
        var cur = ints[i]
        for (var k = i+1; k < ints.length; k++) {
            var next = ints[k]
            if(cur + next === s){
                if(i <= lowestIdx1 && k <= lowestIdx1 || i <= lowestIdx2 && k <=lowestIdx2){
                    lowestIdx1 = i
                    lowestIdx2 = k
                }
            }
        }
    }
    if(lowestIdx1 !== Infinity){
        return [ints[lowestIdx1], ints[lowestIdx2]]
    }
}
</code>```

To be more clear on the problem here are some sample input outputs:

```<code>sum_pairs([11, 3, 7, 5],         10)
#              ^--^      3 + 7 = 10
== [3, 7]

sum_pairs([4, 3, 2, 3, 4],         6)
#          ^-----^         4 + 2 = 6, indices: 0, 2 *
#             ^-----^      3 + 3 = 6, indices: 1, 3
#                ^-----^   2 + 4 = 6, indices: 2, 4
#  * entire pair is earlier, and therefore is the correct answer
== [4, 2]

sum_pairs([0, 0, -2, 3], 2)
#  there are no pairs of values that can be added to produce 2.
== undefined
</code>```

答:
You could use some speeding mechanisms, like

single loop,

hash table for visited values

variable a for element array[i]

Long list of Sum of Pairs on Codewars needs 153 ms.

var sum_pairs = function (array, s) {
    var a, i,
        hash = Object.create(null);

    for (i = 0; i < array.length; i++) {
        a = array[i];
        if (hash[s - a]) {
            return [s - a, a];
        }
        if (!hash[a]) {
            hash[a] = true;
        }
    }
};

console.log(sum_pairs([11, 3, 7, 5], 10));        // [3, 7]
console.log(sum_pairs([4, 3, 2, 3, 4], 6));       // [4, 2]
console.log(sum_pairs([0, 0, -2, 3], 2));         // undefined
console.log(sum_pairs([10, 5, 2, 3, 7, 5], 10));  // [3, 7]
console.log(sum_pairs([1, 2, 3, 4, 1, 0], 2));    // [1, 1]
console.log(sum_pairs([1, -2, 3, 0, -6, 1], -6)); // [0, -6]
console.log(sum_pairs([0, 2, 0], 0));             // [0, 0]
console.log(sum_pairs([5, 9, 13, -3], 10));       // [13, -3]```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I am doing a codewars problem, the instructions are as follows: Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.

The solution works, but it is too slow for long arrays, how would someone do this without using two for loops? I have been trying to reduce the time complexity, but I am at a loss at how to accomplish this when I need to look at all possible pairs.

function sumPairs(ints, s){
    var lowestIdx1 = Infinity;
    var lowestIdx2 = Infinity;

    for (var i = 0; i < ints.length-1; i++) {
        var cur = ints[i]
        for (var k = i+1; k < ints.length; k++) {
            var next = ints[k]
            if(cur + next === s){
                if(i <= lowestIdx1 && k <= lowestIdx1 || i <= lowestIdx2 && k <=lowestIdx2){
                    lowestIdx1 = i
                    lowestIdx2 = k
                }
            }
        }
    }
    if(lowestIdx1 !== Infinity){
        return [ints[lowestIdx1], ints[lowestIdx2]]
    }
}

To be more clear on the problem here are some sample input outputs:

sum_pairs([11, 3, 7, 5],         10)
#              ^--^      3 + 7 = 10
== [3, 7]

sum_pairs([4, 3, 2, 3, 4],         6)
#          ^-----^         4 + 2 = 6, indices: 0, 2 *
#             ^-----^      3 + 3 = 6, indices: 1, 3
#                ^-----^   2 + 4 = 6, indices: 2, 4
#  * entire pair is earlier, and therefore is the correct answer
== [4, 2]

sum_pairs([0, 0, -2, 3], 2)
#  there are no pairs of values that can be added to produce 2.
== undefined

Body:
You could use some speeding mechanisms, like

single loop,

hash table for visited values

variable a for element array[i]

Long list of Sum of Pairs on Codewars needs 153 ms.

var sum_pairs = function (array, s) {
    var a, i,
        hash = Object.create(null);

    for (i = 0; i < array.length; i++) {
        a = array[i];
        if (hash[s - a]) {
            return [s - a, a];
        }
        if (!hash[a]) {
            hash[a] = true;
        }
    }
};

console.log(sum_pairs([11, 3, 7, 5], 10));        // [3, 7]
console.log(sum_pairs([4, 3, 2, 3, 4], 6));       // [4, 2]
console.log(sum_pairs([0, 0, -2, 3], 2));         // undefined
console.log(sum_pairs([10, 5, 2, 3, 7, 5], 10));  // [3, 7]
console.log(sum_pairs([1, 2, 3, 4, 1, 0], 2));    // [1, 1]
console.log(sum_pairs([1, -2, 3, 0, -6, 1], -6)); // [0, -6]
console.log(sum_pairs([0, 2, 0], 0));             // [0, 0]
console.log(sum_pairs([5, 9, 13, -3], 10));       // [13, -3]

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to read one row at a time from excel file using aspose in java
I have an excel file with 1000's of rows and I want read each row at a time in Java using aspose API's. I want to convert each row into a String array. Can anyone help me with this?

```<code>Worksheet worksheet = workbook.getWorksheets().get(0);
Cells cells = worksheet.getCells();
</code>```

答:
```<code>Cells cells = worksheet.getCells();
Range range = cells.getMaxDisplayRange();
int totalColumns = range.getColumnCount();
int totalRows = range.getRowCount();
RowCollection rows = cells.getRows();

for (int i = 1; i < rows.getCount(); i++) {
    for (int j = 0; j < totalColumns; j++) {
        System.out.print(cells.get(i, j).getValue() + "\t");
    }
    System.out.println("");
}
</code>```

Body:
I have an excel file with 1000's of rows and I want read each row at a time in Java using aspose API's. I want to convert each row into a String array. Can anyone help me with this?

Worksheet worksheet = workbook.getWorksheets().get(0);
Cells cells = worksheet.getCells();


问:
Diamond Square improper implementation
Hello Stack Community,

I thought long and hard about posting this seeing as I did not want to attract yet another "duplicate" thread. However I have run out of ideas and do not know of any forums or other stacks where I could post this to get some help.

I wrote this application as a fun project in an attempt to generate some height-maps. However whenever I try to generate more than one height-map at a time all my duplicates appear as either black voids or if the MAP_SIZE variable is low enough white voids. (Example, 16 && 33 create white voids, 1025 creates black)

My output folder appears as follows: low value vrs higher value

Why is this? Is it simply a mathematical fluke that I am missing at 3:15 am?
I wrote the printMap specifically for the function of checking the values of the map data and while they are within ranges that would designate them to be black/white. I see no reason for this to exist continuously after the first iteration.

Just for fun I printed 44 more maps, and after the first one they all were black, MAP_SIZE was set at 1025. Feel free to check this out yourselves.

I created my diamond square algorithm based off my readings from here: http://www.gameprogrammer.com/fractal.html#heightmaps

And my greyWriteImage from a older stack overflow thread about simplex noise maps.

EDIT
Thanks to  I was able to solve my problem, turns out it was just a simple fact that for each new map you attempted to create using the populateMap function I forgot to reset avgOffset to 1. Essentially the problem was you were dividing the avgOffset continuously by 2 getting smaller and smaller results, which always which would always be cast a certain way.

Below I have included my completed source code for anyone who would like to work with my algorithm and output. Have fun.

```<code>import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import java.util.concurrent.ThreadLocalRandom;

public class generateHeightMap {

    // https://stackoverflow.com/questions/43179809/diamond-square-improper-implementation

    private static final Random RAND = new Random();
    // Size of map to generate, must be a value of (2^n+1), ie. 33, 65, 129
    // 257,1025 are fun values
    private static final int MAP_SIZE = 1025;
    // initial seed for corners of map
    private static final double SEED = ThreadLocalRandom.current().nextInt(0, 1 + 1);
    // average offset of data between points
    private static double avgOffSetInit = 1;

    private static final String PATH = "C:\\Users\\bcm27\\Desktop\\grayScale_export";
    private static String fileName = "\\grayscale_map00.PNG";

    public generateHeightMap(int howManyMaps) {
        System.out.printf("Seed: %s\nMap Size: %s\nAverage Offset: %s\n",
                SEED, MAP_SIZE, avgOffSetInit);
        System.out.println("-------------------------------------------");

        for(int i = 1; i <= howManyMaps; i++){ // how many maps to generate

            double[][] map = populateMap(new double[MAP_SIZE][MAP_SIZE]);
            //printMap(map);
            generateHeightMap.greyWriteImage(map);
            fileName = "\\grayscale_map0" + i + ".PNG";

            System.out.println("Output: " + PATH + fileName);
        }
    }
    /*************************************************************************************
     * @param requires a 2d map array of 0-1 values, and a valid file path
     * @post creates a image file saved to path + file_name
     ************************************************************************************/
    private static void greyWriteImage(double[][] data) {
        BufferedImage image =
                new BufferedImage(data.length, data[0].length, BufferedImage.TYPE_INT_RGB);

        for (int y = 0; y < data[0].length; y++)
        {
            for (int x = 0; x < data.length; x++)
            {// for each element in the data

                if (data[x][y]>1){
                    // tells the image whether its white
                    data[x][y]=1;
                }
                if (data[x][y]<0){
                    // tells the image whether its black
                    data[x][y]=0;
                }
                Color col = // RBG colors
                        new Color((float)data[x][y],
                                (float)data[x][y],
                                (float)data[x][y]);
                // sets the image pixel color equal to the RGB value
                image.setRGB(x, y, col.getRGB());
            }
        }

        try {
            // retrieve image
            File outputfile = new File( PATH + fileName);
            outputfile.createNewFile();
            ImageIO.write(image, "png", outputfile);

        } catch (IOException e) {
            throw new RuntimeException("I didn't handle this very well. ERROR:\n" + e);
        }
    }

    /****************************************************************************
     * @param requires map double[MAPSIZE][MAPSIZE]
     * @return returns populated map
     *
     * [1] Taking a square of four points, generate a random value at the square
     *     midpoint, where the two diagonals meet. The midpoint value is calcul-
     *     ated by averaging the four corner values, plus a random amount. This
     *     gives you diamonds when you have multiple squares arranged in a grid.
     *
     * [2] Taking each diamond of four points, generate a random value at the
     *     center of the diamond. Calculate the midpoint value by averaging the
     *     corner values, plus a random amount generated in the same range as
     *     used for the diamond step. This gives you squares again.
     *
     *     '*' equals a new value
     *     '=' equals a old value
     *
     *     * - - - *     = - - - =   = - * - =   = - = - =   = * = * =
     *     - - - - -     - - - - -   - - - - -   - * - * -   * = * = *
     *     - - - - -     - - * - -   * - = - *   = - = - =   = * = * =
     *     - - - - -     - - - - -   - - - - -   - * - * -   * = * = *
     *     * - - - *     = - - - =   = - * - =   = - = - =   = * = * =
     *         A             B           C           D           E
     *
     *     A: Seed corners
     *     B: Randomized center value
     *     C: Diamond step
     *     D: Repeated square step
     *     E: Inner diamond step
     *
     *     Rinse and repeat C->D->E until data map is filled
     *
     ***************************************************************************/
    private static double[][] populateMap(double[][] map) {

        // assures us we have a fresh map each time
        double avgOffSet = avgOffSetInit;

        // assigns the corners of the map values to SEED
        map[0][0] =
        map[0][MAP_SIZE-1] =
        map[MAP_SIZE-1][0] =
        map[MAP_SIZE-1][MAP_SIZE-1] = SEED;

        // square and diamond loop start
        for(int sideLength = MAP_SIZE-1; sideLength >= 2; sideLength /=2,avgOffSet/= 2.0) {

            int halfSide = sideLength / 2;
            double avgOfPoints;

            /********************************************************************
             *           [1]            SQUARE FRACTAL             [1]
             *********************************************************************/
            // loops through x & y values of the height map
            for(int x = 0; x < MAP_SIZE-1; x += sideLength) {
                for(int y = 0; y <MAP_SIZE-1; y += sideLength) {

                    avgOfPoints = map[x][y] +                 //top left point
                            map[x + sideLength][y] +            //top right point
                            map[x][y + sideLength] +            //lower left point
                            map[x + sideLength][y + sideLength];//lower right point

                    // average of surrounding points
                    avgOfPoints /= 4.0;

                    // random value of 2*offset subtracted
                    // by offset for range of +/- the average
                    map[x+halfSide][y+halfSide] = avgOfPoints +
                            (RAND.nextDouble()*2*avgOffSet) - avgOffSet;
                }
            }

            /********************************************************************
             *          [2]            DIAMOND FRACTAL           [2]
             *********************************************************************/
            for(int x=0; x < MAP_SIZE-1; x += halfSide) {
                for(int y = (x + halfSide) % sideLength; y < MAP_SIZE-1;

                        y += sideLength) {
                    avgOfPoints =
                            map[(x - halfSide + MAP_SIZE) % MAP_SIZE][y] +//left of center
                            map[(x + halfSide) % MAP_SIZE][y] +           //right of center
                            map[x][(y + halfSide) % MAP_SIZE] +           //below center
                            map[x][(y - halfSide + MAP_SIZE) % MAP_SIZE]; //above center

                    // average of surrounding values
                    avgOfPoints /= 4.0;

                    // in range of +/- offset
                    avgOfPoints += (RAND.nextDouble()*2*avgOffSet) - avgOffSet;

                    //update value for center of diamond
                    map[x][y] = avgOfPoints;

                    // comment out for non wrapping values
                    if(x == 0)  map[MAP_SIZE-1][y] = avgOfPoints;
                    if(y == 0)  map[x][MAP_SIZE-1] = avgOfPoints;

                } // end y
            } // end x
        } // end of diamond
        return map;
    } // end of populateMap

    /*************************************************************************************
     * @param requires a 2d map array to print the values of at +/-0.00
     ************************************************************************************/
    @SuppressWarnings("unused")
    private static void printMap(double[][] map) {
        System.out.println("---------------------------------------------");

        for (int x = 0; x < map.length; x++) {
            for (int y = 0; y < map[x].length; y++) {
                System.out.printf("%+.2f ", map[x][y] );
            }
            System.out.println();
        }
    }

} // end of class
</code>```

答:
Is it possible that avgOffSet must be initialized before creating each map (start of populateMap)?

It is being divided by 2 but never reset to 1. I suppose each map is independent, that is, does not depend on the previous one, so there is no reason to not reset the variable. But I do not know that algorithm and have no time to learn it... [:-|

```<code>private static double[][] populateMap(double[][] map) {

    avgOffSet = 1;  // missing this one

    map[0][0] = ...
</code>```

if this is correct I would suggest that avgOffset should be a variable; eventually create a field avgOffsetInitial with the initial value (instead of the current field).

Title: Diamond Square improper implementation

Body:
Hello Stack Community,

I thought long and hard about posting this seeing as I did not want to attract yet another "duplicate" thread. However I have run out of ideas and do not know of any forums or other stacks where I could post this to get some help.

I wrote this application as a fun project in an attempt to generate some height-maps. However whenever I try to generate more than one height-map at a time all my duplicates appear as either black voids or if the MAP_SIZE variable is low enough white voids. (Example, 16 && 33 create white voids, 1025 creates black)

My output folder appears as follows: low value vrs higher value

Why is this? Is it simply a mathematical fluke that I am missing at 3:15 am?
I wrote the printMap specifically for the function of checking the values of the map data and while they are within ranges that would designate them to be black/white. I see no reason for this to exist continuously after the first iteration.

Just for fun I printed 44 more maps, and after the first one they all were black, MAP_SIZE was set at 1025. Feel free to check this out yourselves.

I created my diamond square algorithm based off my readings from here: http://www.gameprogrammer.com/fractal.html#heightmaps

And my greyWriteImage from a older stack overflow thread about simplex noise maps.

EDIT
Thanks to  I was able to solve my problem, turns out it was just a simple fact that for each new map you attempted to create using the populateMap function I forgot to reset avgOffset to 1. Essentially the problem was you were dividing the avgOffset continuously by 2 getting smaller and smaller results, which always which would always be cast a certain way.

Below I have included my completed source code for anyone who would like to work with my algorithm and output. Have fun.

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import java.util.concurrent.ThreadLocalRandom;

public class generateHeightMap {

    // https://stackoverflow.com/questions/43179809/diamond-square-improper-implementation

    private static final Random RAND = new Random();
    // Size of map to generate, must be a value of (2^n+1), ie. 33, 65, 129
    // 257,1025 are fun values
    private static final int MAP_SIZE = 1025;
    // initial seed for corners of map
    private static final double SEED = ThreadLocalRandom.current().nextInt(0, 1 + 1);
    // average offset of data between points
    private static double avgOffSetInit = 1;

    private static final String PATH = "C:\\Users\\bcm27\\Desktop\\grayScale_export";
    private static String fileName = "\\grayscale_map00.PNG";

    public generateHeightMap(int howManyMaps) {
        System.out.printf("Seed: %s\nMap Size: %s\nAverage Offset: %s\n",
                SEED, MAP_SIZE, avgOffSetInit);
        System.out.println("-------------------------------------------");

        for(int i = 1; i <= howManyMaps; i++){ // how many maps to generate

            double[][] map = populateMap(new double[MAP_SIZE][MAP_SIZE]);
            //printMap(map);
            generateHeightMap.greyWriteImage(map);
            fileName = "\\grayscale_map0" + i + ".PNG";

            System.out.println("Output: " + PATH + fileName);
        }
    }
    /*************************************************************************************
     * @param requires a 2d map array of 0-1 values, and a valid file path
     * @post creates a image file saved to path + file_name
     ************************************************************************************/
    private static void greyWriteImage(double[][] data) {
        BufferedImage image =
                new BufferedImage(data.length, data[0].length, BufferedImage.TYPE_INT_RGB);

        for (int y = 0; y < data[0].length; y++)
        {
            for (int x = 0; x < data.length; x++)
            {// for each element in the data

                if (data[x][y]>1){
                    // tells the image whether its white
                    data[x][y]=1;
                }
                if (data[x][y]<0){
                    // tells the image whether its black
                    data[x][y]=0;
                }
                Color col = // RBG colors
                        new Color((float)data[x][y],
                                (float)data[x][y],
                                (float)data[x][y]);
                // sets the image pixel color equal to the RGB value
                image.setRGB(x, y, col.getRGB());
            }
        }

        try {
            // retrieve image
            File outputfile = new File( PATH + fileName);
            outputfile.createNewFile();
            ImageIO.write(image, "png", outputfile);

        } catch (IOException e) {
            throw new RuntimeException("I didn't handle this very well. ERROR:\n" + e);
        }
    }

    /****************************************************************************
     * @param requires map double[MAPSIZE][MAPSIZE]
     * @return returns populated map
     *
     * [1] Taking a square of four points, generate a random value at the square
     *     midpoint, where the two diagonals meet. The midpoint value is calcul-
     *     ated by averaging the four corner values, plus a random amount. This
     *     gives you diamonds when you have multiple squares arranged in a grid.
     *
     * [2] Taking each diamond of four points, generate a random value at the
     *     center of the diamond. Calculate the midpoint value by averaging the
     *     corner values, plus a random amount generated in the same range as
     *     used for the diamond step. This gives you squares again.
     *
     *     '*' equals a new value
     *     '=' equals a old value
     *
     *     * - - - *     = - - - =   = - * - =   = - = - =   = * = * =
     *     - - - - -     - - - - -   - - - - -   - * - * -   * = * = *
     *     - - - - -     - - * - -   * - = - *   = - = - =   = * = * =
     *     - - - - -     - - - - -   - - - - -   - * - * -   * = * = *
     *     * - - - *     = - - - =   = - * - =   = - = - =   = * = * =
     *         A             B           C           D           E
     *
     *     A: Seed corners
     *     B: Randomized center value
     *     C: Diamond step
     *     D: Repeated square step
     *     E: Inner diamond step
     *
     *     Rinse and repeat C->D->E until data map is filled
     *
     ***************************************************************************/
    private static double[][] populateMap(double[][] map) {

        // assures us we have a fresh map each time
        double avgOffSet = avgOffSetInit;

        // assigns the corners of the map values to SEED
        map[0][0] =
        map[0][MAP_SIZE-1] =
        map[MAP_SIZE-1][0] =
        map[MAP_SIZE-1][MAP_SIZE-1] = SEED;

        // square and diamond loop start
        for(int sideLength = MAP_SIZE-1; sideLength >= 2; sideLength /=2,avgOffSet/= 2.0) {

            int halfSide = sideLength / 2;
            double avgOfPoints;

            /********************************************************************
             *           [1]            SQUARE FRACTAL             [1]
             *********************************************************************/
            // loops through x & y values of the height map
            for(int x = 0; x < MAP_SIZE-1; x += sideLength) {
                for(int y = 0; y <MAP_SIZE-1; y += sideLength) {

                    avgOfPoints = map[x][y] +                 //top left point
                            map[x + sideLength][y] +            //top right point
                            map[x][y + sideLength] +            //lower left point
                            map[x + sideLength][y + sideLength];//lower right point

                    // average of surrounding points
                    avgOfPoints /= 4.0;

                    // random value of 2*offset subtracted
                    // by offset for range of +/- the average
                    map[x+halfSide][y+halfSide] = avgOfPoints +
                            (RAND.nextDouble()*2*avgOffSet) - avgOffSet;
                }
            }

            /********************************************************************
             *          [2]            DIAMOND FRACTAL           [2]
             *********************************************************************/
            for(int x=0; x < MAP_SIZE-1; x += halfSide) {
                for(int y = (x + halfSide) % sideLength; y < MAP_SIZE-1;

                        y += sideLength) {
                    avgOfPoints =
                            map[(x - halfSide + MAP_SIZE) % MAP_SIZE][y] +//left of center
                            map[(x + halfSide) % MAP_SIZE][y] +           //right of center
                            map[x][(y + halfSide) % MAP_SIZE] +           //below center
                            map[x][(y - halfSide + MAP_SIZE) % MAP_SIZE]; //above center

                    // average of surrounding values
                    avgOfPoints /= 4.0;

                    // in range of +/- offset
                    avgOfPoints += (RAND.nextDouble()*2*avgOffSet) - avgOffSet;

                    //update value for center of diamond
                    map[x][y] = avgOfPoints;

                    // comment out for non wrapping values
                    if(x == 0)  map[MAP_SIZE-1][y] = avgOfPoints;
                    if(y == 0)  map[x][MAP_SIZE-1] = avgOfPoints;

                } // end y
            } // end x
        } // end of diamond
        return map;
    } // end of populateMap

    /*************************************************************************************
     * @param requires a 2d map array to print the values of at +/-0.00
     ************************************************************************************/
    @SuppressWarnings("unused")
    private static void printMap(double[][] map) {
        System.out.println("---------------------------------------------");

        for (int x = 0; x < map.length; x++) {
            for (int y = 0; y < map[x].length; y++) {
                System.out.printf("%+.2f ", map[x][y] );
            }
            System.out.println();
        }
    }

} // end of class

Body:
Is it possible that avgOffSet must be initialized before creating each map (start of populateMap)?

It is being divided by 2 but never reset to 1. I suppose each map is independent, that is, does not depend on the previous one, so there is no reason to not reset the variable. But I do not know that algorithm and have no time to learn it... [:-|

private static double[][] populateMap(double[][] map) {

    avgOffSet = 1;  // missing this one

    map[0][0] = ...

if this is correct I would suggest that avgOffset should be a variable; eventually create a field avgOffsetInitial with the initial value (instead of the current field).


问:
Problems with message passing queue linux
I'm writing simple message passing exercise and have sent a message from one process to the next. It's the battleship game.

However other process keeps waiting on the message.

Code is http://pastebin.com/Lc5xxXdu

Sample input:

First 4x4 board is initalized for both players (e.g.):

```<code>oooo
----
oooo
----
</code>```

Then target coordinates are entere (e.g. 0 0). This process sends message to other one (using message_t, long pid is in place of mtype in kernel code).

But it's not working for some unknown reason.
Quick translations:

```<code>Cekam poruku %pid --> Waiting for message
Saljem poruku %pid --> Sending message with following pid (mtype for kernel) set
Ispali na polje --> Nice query where to shoot next
</code>```

答: Found solution. I accidentally had pointer to pointer instead of only one level of pointers. It got to issue I was having.</p>

Body:
I'm writing simple message passing exercise and have sent a message from one process to the next. It's the battleship game.

However other process keeps waiting on the message.

Code is http://pastebin.com/Lc5xxXdu

Sample input:

First 4x4 board is initalized for both players (e.g.):

oooo
----
oooo
----

Then target coordinates are entere (e.g. 0 0). This process sends message to other one (using message_t, long pid is in place of mtype in kernel code).

But it's not working for some unknown reason.
Quick translations:

Cekam poruku %pid --> Waiting for message
Saljem poruku %pid --> Sending message with following pid (mtype for kernel) set
Ispali na polje --> Nice query where to shoot next


问:
How to print 0 to 9 digits without using any digit in our code?
Recently, I found a problem on hackerearth that is how to print 726 without any digits. This is the link to question :https://www.hackerearth.com/challenge/college/r1/golf/726/

I have solved this with this:

```<code>#include <stdio.h>
main()
{
    printf("%d",('\e'*'\e')-('\r'-'\n'));

}
</code>```

but since I found this question interesting, I would love to print every single digit without use of any digit. So, I want to print 0 to 9 all in a new line without using any digit with the help of unicodes. How could I do that?

答:
```<code>#include <stdio.h>
void main()
{
  char ch='/';
  while(ch!=':')
  {
      if(isdigit(ch))
      {
        printf("%c\n ",ch);
      }
      ch++;
   }
}
</code>```

Body:
Recently, I found a problem on hackerearth that is how to print 726 without any digits. This is the link to question :https://www.hackerearth.com/challenge/college/r1/golf/726/

I have solved this with this:

#include <stdio.h>
main()
{
    printf("%d",('\e'*'\e')-('\r'-'\n'));

}

but since I found this question interesting, I would love to print every single digit without use of any digit. So, I want to print 0 to 9 all in a new line without using any digit with the help of unicodes. How could I do that?