问:
How to protect a client side JavaScript variable?
Using the following function to check the existence of a given URL. The code is executed on the client side (browser), is there a way (if at all possible) to protect the url variable from being altered with the browser debugger while keeping the function on the client side?

Note that the url variable is generated by the server and set on the JS script (client side)

```<code>function UrlExists(url, callback)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url);
    http.onreadystatechange = function() {
        if (this.readyState == this.DONE) {
            callback(this.status != 404);
        }
    };
    http.send();
}
</code>```

Function source.

答:
While different methods to obfuscate js exist like https://obfuscator.io this does not guarantee any true additional security (but this can make the code not easy to read/debug).

Any thing that is handled on the client side (on the browser js engine), can be altered on the client side with the debugger or with other methods.


来源: stackexchange

问:
Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile for heroku
Hello guys I do not know why but I am getting this strange error on deployment. I have been spending three hours on this but can not get it to work. It has successfully worked before many times and even work once in the three hours deploying a new app. I do not know why I am getting this error on heroku and only heroku.

Gemfile:

Heroku Error:

database.yml:

If anyone have any suggestions, I am all ears!

答:
@petertran98 SQLite is a bad fit for running on Heroku. See the official link by heroku SQLite on Heroku and they recommend using Postgres.

To replace SQLite with Postgres, you need to do the folowwing.

Step - 1: Replace gem 'sqlite3' with gem 'pg' in your Gemfile.

Step - 2: Replace adapter: sqlite3 with adapter: postgresql in your database.yml.

Now try running the deployment. It should do the trick. If you still face some issue then you might need to do 1 of following things on the basis of what error you see.

Either you need to manually add Postgres if that does no gets created automatically with deployment script.

```<code>heroku addons:create heroku-postgresql
</code>```

or if you still see the SQLite error then you might need to delete Gemfile.lock file and run bundle install command again.

ContentLicense: CC BY-SA 4.0

Body:
@petertran98 SQLite is a bad fit for running on Heroku. See the official link by heroku SQLite on Heroku and they recommend using Postgres.

To replace SQLite with Postgres, you need to do the folowwing.

Step - 1: Replace gem 'sqlite3' with gem 'pg' in your Gemfile.

Step - 2: Replace adapter: sqlite3 with adapter: postgresql in your database.yml.

Now try running the deployment. It should do the trick. If you still face some issue then you might need to do 1 of following things on the basis of what error you see.

Either you need to manually add Postgres if that does no gets created automatically with deployment script.

heroku addons:create heroku-postgresql

or if you still see the SQLite error then you might need to delete Gemfile.lock file and run bundle install command again.


问:
with Strings in c
I try to do interpolation search with the data from the struct. For example I give as input the time 2014-02-13T18:50:00 and I want interpolation search return the temp 4.0 and the hum 75 but something doesn't work.
I think the problem appears when calculate mid with (High-Low)*(In-Low) but I don't understand why this happen.

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

#define SIZE 11
struct metrhseis{
char time[21];
int temp;
int hum;

};
long long int string_To_long(const char  arr[]);
void interpolation_search(struct metrhseis  arr[], char * in);
int main(){

char in[25];
int inI;
int j;
struct  metrhseis s[SIZE];

strcpy(s[0].time, "2014-02-13T06:20:00");
s[0].temp=3.0;
s[0].hum=93;
strcpy(s[1].time, "2014-02-13T13:50:00");
s[1].temp=7.0;
s[1].hum=66;
strcpy(s[2].time, "2014-02-13T06:00:00");
s[2].temp=2;
s[2].hum=91;
strcpy(s[3].time, "2014-02-13T03:00:00");
s[3].temp=3;
s[3].hum=84;
strcpy(s[4].time, "2014-02-13T13:00:00");
s[4].temp=6;
s[4].hum=62;
strcpy(s[5].time, "2014-02-13T18:50:00");
s[5].temp=4.0;
s[5].hum=75;
strcpy(s[6].time, "2014-02-13T13:20:00");
s[6].temp=6.0;
s[6].hum=70;
strcpy(s[7].time, "2014-02-13T15:00:00");
s[7].temp=6;
s[7].hum=56;
strcpy(s[8].time, "2014-02-13T08:50:00");
s[8].temp=4.0;
s[8].hum=87;
strcpy(s[9].time, "2014-02-13T21:50:00");
s[9].temp=4.0;
s[9].hum=75;
strcpy(s[10].time, "2014-02-13T08:00:00");
s[10].temp=3;
s[10].hum=88;

 int i;

  for (i = 0; i < SIZE; i++)
     printf("%s\n%d\n%d\n", s[i].time,  s[i].temp,s[i].hum);

printf("Date:");
scanf("%s",in);
interpolation_search(s, in);

}
 void interpolation_search(struct metrhseis  arr[], char * in){
  long long int High,Low,In;
  long long int mid,low,high;
  low=0;
  high =SIZE - 1 ;
  High = string_To_long(arr[high].time);
  Low = string_To_long(arr[low].time);
  In = string_To_long(in);

  while(low<=high  ){
  High= string_To_long(arr[high].time);
  Low= string_To_long(arr[low].time);

  mid =low+(high-low)/(High-Low)*(In-Low);

  if(strcmp(arr[mid].time,in)>0){
  high=mid-1;
  }
  else if(strcmp(arr[mid].time,in)<0){
  low=mid+1;

 }
 else
 printf("Time: %s Temperatura: %d Hum: %d",arr[mid].time ,arr[mid].temp,arr[mid].hum);
 break;
}

printf("Time: %s Temperatura: %d Hum: %d", in,arr[mid].temp,arr[mid].hum);
}
long long string_To_long(const char arr[]) {
long long int n = 0;
for (int i = 0; arr[i] != '\0'; i++) {
    char c = arr[i];
    if (c >= '0' && c <= '9')
        n = n * 10 + (c - '0');
}
return n;
}
</code>```

答:
Use an ordered list
Then compute ratio between two time and finally display temp and hum

For 2014-02-13T13:40:00 get

Time: 20140213134000 Temperatura: 6.666667 Hum: 67.333336

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

struct metrhseis{
    long long int time;
    int temp;
    int hum;

    struct metrhseis *next;
};

long long int string_To_long(const char  arr[]);
void interpolation_search(struct metrhseis  *list, const char * in);
void add_metrhseis(struct metrhseis **list, const char *time, int temp, int hum);
void list_delete(struct metrhseis **list);
void list_print(struct metrhseis *list);

int main(){

    char in[25];
    struct  metrhseis *list = NULL;

    add_metrhseis(&list, "2014-02-13T06:20:00", 3.0, 93);
    add_metrhseis(&list, "2014-02-13T13:50:00", 7.0, 66);
    add_metrhseis(&list, "2014-02-13T06:00:00", 2, 91);
    add_metrhseis(&list, "2014-02-13T03:00:00", 3, 84);
    add_metrhseis(&list, "2014-02-13T13:00:00", 6, 62);
    add_metrhseis(&list, "2014-02-13T18:50:00", 4.0, 75);
    add_metrhseis(&list, "2014-02-13T13:20:00", 6.0, 70);
    add_metrhseis(&list, "2014-02-13T15:00:00", 6, 56);
    add_metrhseis(&list, "2014-02-13T08:50:00", 4.0, 87);
    add_metrhseis(&list, "2014-02-13T21:50:00", 4.0, 75);
    add_metrhseis(&list, "2014-02-13T08:00:00", 3, 88);

    list_print(list);

    printf("Date:");
    scanf("%s",in);
    interpolation_search(list, in);

    list_delete(&list);
}

void list_print(struct metrhseis *m) {
    printf("List\n");
    do {
        printf("%lld:%d,%d\n", m->time, m->temp, m->hum);
        m = m->next;
    } while (m);
}

void list_delete(struct metrhseis **list) {
    struct metrhseis *m = *list;
    if (m->next) {
        list_delete(&m->next);
    }
    free(m);
    *list = NULL;
}
void add_metrhseis(struct metrhseis **list, const char *time, int temp, int hum)
{
    struct metrhseis *current = *list;
    struct metrhseis *m = malloc(sizeof(struct metrhseis));
    m->time = string_To_long(time);
    m->temp = temp;
    m->hum = hum;

    if (*list == NULL || (*list)->time > m->time) {
        m->next = *list;
        *list = m;
        return;
    }
    while (current->next && current->next->time <= m->time) {
        current = current->next;
    }
    m->next = current->next;
    current->next = m;
}

void interpolation_search(struct metrhseis *list, const char * in) {
    long long int time = string_To_long(in);
    float ratio;

    if (time < list->time) {
        printf("Time: %s Temperatura: %d Hum: %d\n", in, list->temp, list->hum);
        return;
    }
    while(list->next && list->next->time < time) {
        list = list->next;
    }
    if (!list->next) {
        printf("Time: %s Temperatura: %d Hum: %d\n", in, list->temp, list->hum);
        return;
    }
    ratio = (float)(time - list->time) / (list->next->time - list->time);
    printf("Time: %s Temperatura: %f Hum: %f\n",
           in,
           list->temp + ratio * (list->next->temp - list->temp),
           list->hum  + ratio * (list->next->hum  - list->hum )
    );
    return;

}
long long string_To_long(const char arr[]) {
    long long int n = 0;
    for (int i = 0; arr[i] != '\0'; i++) {
        char c = arr[i];
        if (c >= '0' && c <= '9')
            n = n * 10 + (c - '0');
    }
    return n;
}

</code>```

Title: with Strings in c

Body:
I try to do interpolation search with the data from the struct. For example I give as input the time 2014-02-13T18:50:00 and I want interpolation search return the temp 4.0 and the hum 75 but something doesn't work.
I think the problem appears when calculate mid with (High-Low)*(In-Low) but I don't understand why this happen.

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

#define SIZE 11
struct metrhseis{
char time[21];
int temp;
int hum;

};
long long int string_To_long(const char  arr[]);
void interpolation_search(struct metrhseis  arr[], char * in);
int main(){

char in[25];
int inI;
int j;
struct  metrhseis s[SIZE];

strcpy(s[0].time, "2014-02-13T06:20:00");
s[0].temp=3.0;
s[0].hum=93;
strcpy(s[1].time, "2014-02-13T13:50:00");
s[1].temp=7.0;
s[1].hum=66;
strcpy(s[2].time, "2014-02-13T06:00:00");
s[2].temp=2;
s[2].hum=91;
strcpy(s[3].time, "2014-02-13T03:00:00");
s[3].temp=3;
s[3].hum=84;
strcpy(s[4].time, "2014-02-13T13:00:00");
s[4].temp=6;
s[4].hum=62;
strcpy(s[5].time, "2014-02-13T18:50:00");
s[5].temp=4.0;
s[5].hum=75;
strcpy(s[6].time, "2014-02-13T13:20:00");
s[6].temp=6.0;
s[6].hum=70;
strcpy(s[7].time, "2014-02-13T15:00:00");
s[7].temp=6;
s[7].hum=56;
strcpy(s[8].time, "2014-02-13T08:50:00");
s[8].temp=4.0;
s[8].hum=87;
strcpy(s[9].time, "2014-02-13T21:50:00");
s[9].temp=4.0;
s[9].hum=75;
strcpy(s[10].time, "2014-02-13T08:00:00");
s[10].temp=3;
s[10].hum=88;

 int i;

  for (i = 0; i < SIZE; i++)
     printf("%s\n%d\n%d\n", s[i].time,  s[i].temp,s[i].hum);

printf("Date:");
scanf("%s",in);
interpolation_search(s, in);

}
 void interpolation_search(struct metrhseis  arr[], char * in){
  long long int High,Low,In;
  long long int mid,low,high;
  low=0;
  high =SIZE - 1 ;
  High = string_To_long(arr[high].time);
  Low = string_To_long(arr[low].time);
  In = string_To_long(in);

  while(low<=high  ){
  High= string_To_long(arr[high].time);
  Low= string_To_long(arr[low].time);

  mid =low+(high-low)/(High-Low)*(In-Low);

  if(strcmp(arr[mid].time,in)>0){
  high=mid-1;
  }
  else if(strcmp(arr[mid].time,in)<0){
  low=mid+1;

 }
 else
 printf("Time: %s Temperatura: %d Hum: %d",arr[mid].time ,arr[mid].temp,arr[mid].hum);
 break;
}

printf("Time: %s Temperatura: %d Hum: %d", in,arr[mid].temp,arr[mid].hum);
}
long long string_To_long(const char arr[]) {
long long int n = 0;
for (int i = 0; arr[i] != '\0'; i++) {
    char c = arr[i];
    if (c >= '0' && c <= '9')
        n = n * 10 + (c - '0');
}
return n;
}

Body:
Use an ordered list
Then compute ratio between two time and finally display temp and hum

For 2014-02-13T13:40:00 get

Time: 20140213134000 Temperatura: 6.666667 Hum: 67.333336

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

struct metrhseis{
    long long int time;
    int temp;
    int hum;

    struct metrhseis *next;
};

long long int string_To_long(const char  arr[]);
void interpolation_search(struct metrhseis  *list, const char * in);
void add_metrhseis(struct metrhseis **list, const char *time, int temp, int hum);
void list_delete(struct metrhseis **list);
void list_print(struct metrhseis *list);

int main(){

    char in[25];
    struct  metrhseis *list = NULL;

    add_metrhseis(&list, "2014-02-13T06:20:00", 3.0, 93);
    add_metrhseis(&list, "2014-02-13T13:50:00", 7.0, 66);
    add_metrhseis(&list, "2014-02-13T06:00:00", 2, 91);
    add_metrhseis(&list, "2014-02-13T03:00:00", 3, 84);
    add_metrhseis(&list, "2014-02-13T13:00:00", 6, 62);
    add_metrhseis(&list, "2014-02-13T18:50:00", 4.0, 75);
    add_metrhseis(&list, "2014-02-13T13:20:00", 6.0, 70);
    add_metrhseis(&list, "2014-02-13T15:00:00", 6, 56);
    add_metrhseis(&list, "2014-02-13T08:50:00", 4.0, 87);
    add_metrhseis(&list, "2014-02-13T21:50:00", 4.0, 75);
    add_metrhseis(&list, "2014-02-13T08:00:00", 3, 88);

    list_print(list);

    printf("Date:");
    scanf("%s",in);
    interpolation_search(list, in);

    list_delete(&list);
}

void list_print(struct metrhseis *m) {
    printf("List\n");
    do {
        printf("%lld:%d,%d\n", m->time, m->temp, m->hum);
        m = m->next;
    } while (m);
}

void list_delete(struct metrhseis **list) {
    struct metrhseis *m = *list;
    if (m->next) {
        list_delete(&m->next);
    }
    free(m);
    *list = NULL;
}
void add_metrhseis(struct metrhseis **list, const char *time, int temp, int hum)
{
    struct metrhseis *current = *list;
    struct metrhseis *m = malloc(sizeof(struct metrhseis));
    m->time = string_To_long(time);
    m->temp = temp;
    m->hum = hum;

    if (*list == NULL || (*list)->time > m->time) {
        m->next = *list;
        *list = m;
        return;
    }
    while (current->next && current->next->time <= m->time) {
        current = current->next;
    }
    m->next = current->next;
    current->next = m;
}

void interpolation_search(struct metrhseis *list, const char * in) {
    long long int time = string_To_long(in);
    float ratio;

    if (time < list->time) {
        printf("Time: %s Temperatura: %d Hum: %d\n", in, list->temp, list->hum);
        return;
    }
    while(list->next && list->next->time < time) {
        list = list->next;
    }
    if (!list->next) {
        printf("Time: %s Temperatura: %d Hum: %d\n", in, list->temp, list->hum);
        return;
    }
    ratio = (float)(time - list->time) / (list->next->time - list->time);
    printf("Time: %s Temperatura: %f Hum: %f\n",
           in,
           list->temp + ratio * (list->next->temp - list->temp),
           list->hum  + ratio * (list->next->hum  - list->hum )
    );
    return;

}
long long string_To_long(const char arr[]) {
    long long int n = 0;
    for (int i = 0; arr[i] != '\0'; i++) {
        char c = arr[i];
        if (c >= '0' && c <= '9')
            n = n * 10 + (c - '0');
    }
    return n;
}


问:
I want to have a type that matches every single type of union type, but not any union of those single types
Let's suppose I have following types defined:

```<code>type A = {a:number};
type B = {a:string};
type C = {a:boolean};

type All = A | B | C;
</code>```

Now I want to define generic type S (not using any of the types A,B and C in the definition) that behaves like that:

```<code>var a: S<A>;  // a is actually of type A
var b: S<B>;  // b is of type B
var c: S<C>;  // c is of type C
var all: S<All>; // all is of type never
</code>```

To achieve that I can define S like that:

```<code>type S<T> = All extends T ? never : T;
</code>```

However this is not sufficient for me because I also want that

```<code>var ab: S<A|B>; // ab should be type never but actually is A|B
var bc: S<B|C>; // bc should be type never but actually is B|C
var ca: S<C|A>; // ca should be type never but actually is C|A
</code>```

Question

Given some union type, how to define generic type that can be matched to every single constituent of the union type, but can't be matched to any union of those constituents?

Solution should also work for union types with more than 3 constituents.

答:
It seems that this does exactly what I want:</p>

```<code>type S<T> = [T] extends (T extends All ? [T] : never) ? T : never;
</code>```

Body:
Let's suppose I have following types defined:

type A = {a:number};
type B = {a:string};
type C = {a:boolean};

type All = A | B | C;

Now I want to define generic type S (not using any of the types A,B and C in the definition) that behaves like that:

var a: S;  // a is actually of type A
var b: S;  // b is of type B
var c: S<C>;  // c is of type C
var all: S<All>; // all is of type never

To achieve that I can define S like that:

type S<T> = All extends T ? never : T;

However this is not sufficient for me because I also want that

var ab: S; // ab should be type never but actually is A|B
var bc: S; // bc should be type never but actually is B|C
var ca: S<C|A>; // ca should be type never but actually is C|A

Question

Given some union type, how to define generic type that can be matched to every single constituent of the union type, but can't be matched to any union of those constituents?

Solution should also work for union types with more than 3 constituents.

Body:
It seems that this does exactly what I want:

type S<T> = [T] extends (T extends All ? [T] : never) ? T : never;


问:
Overwrite Existing Image
I have this code

```<code>    private void saveImage()
    {
        Bitmap bmp1 = new Bitmap(pictureBox.Image);
        bmp1.Save("c:\\t.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
        // Dispose of the image files.
        bmp1.Dispose();
    }
</code>```

i already have an image t.jpg at my drive "c:\".

i wanted to replace it with a new image every time my program runs. but a GDI+ error shows up

how could i fix it?

答:
I presume you earlier loaded the c:\t.jpg image using the Image.Load method. If so, the Image object is holding an open file handle on the image file, which means that the file can't be overwritten.

Instead of using Image.Load to get the original image, load it from a FileStream that you create and dispose of.

So, instead of

```<code>Image image = Image.Load(@"c:\\t.jpg");
</code>```

do this:

```<code>using(FileStream fs = new FileStream(@"c:\\t.jpg", FileMode.Open))
{
    pictureBox.Image = Image.FromStream(fs);
    fs.Close();
}
</code>```

The file handle has been released so overwriting the file with Bitmap.Save can succeed. The code you gave in your question should therefore work. There is no need to delete the original file or dispose of the image before saving.

Additional:
If you close the FileStream as above,then calls to Image.Save will throw an exception. See here: A Generic error occurred in GDI+ in Bitmap.Save method

ContentLicense: CC BY-SA 3.0

Title: Overwrite Existing Image

Body:
I have this code

    private void saveImage()
    {
        Bitmap bmp1 = new Bitmap(pictureBox.Image);
        bmp1.Save("c:\\t.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
        // Dispose of the image files.
        bmp1.Dispose();
    }

i already have an image t.jpg at my drive "c:\".

i wanted to replace it with a new image every time my program runs. but a GDI+ error shows up

how could i fix it?

Body:
I presume you earlier loaded the c:\t.jpg image using the Image.Load method. If so, the Image object is holding an open file handle on the image file, which means that the file can't be overwritten.

Instead of using Image.Load to get the original image, load it from a FileStream that you create and dispose of.

So, instead of

Image image = Image.Load(@"c:\\t.jpg");

do this:

using(FileStream fs = new FileStream(@"c:\\t.jpg", FileMode.Open))
{
    pictureBox.Image = Image.FromStream(fs);
    fs.Close();
}

The file handle has been released so overwriting the file with Bitmap.Save can succeed. The code you gave in your question should therefore work. There is no need to delete the original file or dispose of the image before saving.

Additional:
If you close the FileStream as above,then calls to Image.Save will throw an exception. See here: A Generic error occurred in GDI+ in Bitmap.Save method


问:
grails and version control specific to plugins
I am using 1.3.7 on a windows system, the plugins are placed in a different folder and I have made a few changes in the code related to the plugins.

I now need to check in this project into svn, how do i go about doing it ? specifically how do i check in he plugins ?

When a team mate of mine checks out this project, where will he find the plugins ?

I realize that similar questions have been asked here and here

However they do not address this specific problem.

答:
The plugins you have made need to be made inline. i.e. they will be in your grails-app folder.

To make a plugin inline create a folder say "custom-plugins" in your grails-app folder and copy the modified plugin there. Now in your BuildConfig.groovy add following lines

grails.plugin.location.'plugin-name'="custom-plugins/plugin-name"

repeat this for different plugins you have changed.

I personally prefer to add "custom" in the name of modified plugin to differentiate it from original.


问:
Find the two numbers that appear only once - divide and conquer
Given an array in which each element appears twice, I have to find which two numbers of the array appear only once. Maximum additional memory is O(1).

I have found this amazing solution: https://medium.com/@gurupad93/two-numbers-that-appear-once-b89e92a9334b

The problem is that my solution should be divide and conquer, and my understanding is that the solution I found is not.

I know how to solve this problem with divide and conquer when the element appearing once is just one. Here, I wouldn't know how to divide the array recursively to be honest.

Any suggestions?

Thank you so much!

答:
The problem can be divided in tree structure (similar to the tree structure of merge sort) and each partition returns the xor value of its elements to the parent. In this way, we obtain the xor value of two numbers which appear only once in the array.

From the problem, it is clear that the xor value has at at-least one non-zero bit.

Let us assume the xor value is X and its i-th bit is non-zero.

Now again we divide the problem in tree structure and consider elements, whose i-th bit is set, for the xor-computation. This value is returned to the parent. The root node will get the xor-value of the elements whose i-th bit is set. Let us call this value Y.

Hence, the two numbers are Y and X xor Y.


问:
cmder ~ alias for user home folder
Simple question :

I am using cmder and i would like to be able to define ~(or ~USERID) as my %USERPROFILE% environment variables. I edited %CMDERROOT%\config\aliases to add this line : ~=%USERPROFILE% it does work for ls command but not for cd for instance.

Is there a better way to have this unix-like user profile aliases ?

答:
I don´t remember where I got it but add these lines to your profile:

```<code>function cuserprofile { Set-Location ~ }
Set-Alias ~ cuserprofile -Option AllScope
</code>```

you just hit ~ (enter) and you'll send to your home directory.

PS. I'm using PowerShell in cmder, regards.

Title: cmder ~ alias for user home folder

Body:
I don´t remember where I got it but add these lines to your profile:

function cuserprofile { Set-Location ~ }
Set-Alias ~ cuserprofile -Option AllScope

you just hit ~ (enter) and you'll send to your home directory.

PS. I'm using PowerShell in cmder, regards.


问:
could not stat file - c
I need to stat a file to get the size of it. I also need to provide the name of the file as a command line argument. This is my code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

int main (int argc, char* argv[])
{
    int N = 300;
    int L = 1000;
    char Nseq[N][L];

    FILE *myfile;
    char *token;
    const char s[2] = ",";
    char *line;
    int lenline;
    char filename[100];
    strcpy(filename, "/path/");
    char name[100];
    strcpy(name, argv[1]);
    strcat(filename, name);
    strcat(filename, ".txt");
    printf("%s\n", filename);

    int err;
    struct stat st;
    int n = 0;

    err = stat(filename,&st);
    if (err < 0) {
        printf("could not stat file %s", filename);
        exit(1);
    }
    lenline = st.st_size + 1;

    line = malloc(lenline);

    myfile = fopen(filename, "r");
    if (myfile == NULL) {
        printf("could not open file %s", filename);
        exit(1);
    }

    while (fgets(line, lenline, myfile) != NULL) {
        token = strtok(line, s);
        while (token != NULL && n<N) {
            strcpy(Nseq[n], token);
            printf("%s\t%u\n", token, n);
            token = strtok(NULL, s);
            n++;
        }
    }

    fclose(myfile);

    return 0;
}
</code>```

The output I get is:

```<code>/path/file.txt

could not stat file /path/file.txt
</code>```

Does anyone know why is this happening?
how can I fix it?
thank you!

答:
The manual page of stat (2) says: On success, zero (0) is returned. On error, -1 is returned, and errno is set appropriately.

You don't actually use errno and basically are causing your own error message to be a rather unhelpful variant of "something went wrong".

Actually use errno, implicitly by calling

```<code>perror("stat");
</code>```

or explicitly by calling

```<code>fprintf(stderr, "could not stat file %s: %s", filename, strerror(errno));
</code>```

Title: could not stat file - c

Body:
I need to stat a file to get the size of it. I also need to provide the name of the file as a command line argument. This is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

int main (int argc, char* argv[])
{
    int N = 300;
    int L = 1000;
    char Nseq[N][L];

    FILE *myfile;
    char *token;
    const char s[2] = ",";
    char *line;
    int lenline;
    char filename[100];
    strcpy(filename, "/path/");
    char name[100];
    strcpy(name, argv[1]);
    strcat(filename, name);
    strcat(filename, ".txt");
    printf("%s\n", filename);

    int err;
    struct stat st;
    int n = 0;

    err = stat(filename,&st);
    if (err < 0) {
        printf("could not stat file %s", filename);
        exit(1);
    }
    lenline = st.st_size + 1;

    line = malloc(lenline);

    myfile = fopen(filename, "r");
    if (myfile == NULL) {
        printf("could not open file %s", filename);
        exit(1);
    }

    while (fgets(line, lenline, myfile) != NULL) {
        token = strtok(line, s);
        while (token != NULL && n<N) {
            strcpy(Nseq[n], token);
            printf("%s\t%u\n", token, n);
            token = strtok(NULL, s);
            n++;
        }
    }

    fclose(myfile);

    return 0;
}

The output I get is:

/path/file.txt

could not stat file /path/file.txt

Does anyone know why is this happening?
how can I fix it?
thank you!

Body:
The manual page of stat (2) says: On success, zero (0) is returned. On error, -1 is returned, and errno is set appropriately.

You don't actually use errno and basically are causing your own error message to be a rather unhelpful variant of "something went wrong".

Actually use errno, implicitly by calling

perror("stat");

or explicitly by calling

fprintf(stderr, "could not stat file %s: %s", filename, strerror(errno));


问:
How can I run an asyncio loop as long as there are pending cancellation-shielded tasks left but no longer?
I'm trying to add some code to my existing asyncio loop to provide for a clean shutdown on Ctrl-C.  Below is an abstraction of the sort of thing it's doing.

```<code>import asyncio, signal

async def task1():
    print("Starting simulated task1")
    await asyncio.sleep(5)
    print("Finished simulated task1")

async def task2():
    print("Starting simulated task2")
    await asyncio.sleep(5)
    print("Finished simulated task2")

async def tasks():
    await task1()
    await task2()

async def task_loop():
    try:
        while True:
            await asyncio.shield(tasks())
            await asyncio.sleep(60)
    except asyncio.CancelledError:
        print("Shutting down task loop")
        raise

async def aiomain():
    loop = asyncio.get_running_loop()
    task = asyncio.Task(task_loop())
    loop.add_signal_handler(signal.SIGINT, task.cancel)
    await task

def main():
    try:
        asyncio.run(aiomain())
    except asyncio.CancelledError:
        pass

#def main():
#    try:
#        loop = asyncio.get_event_loop()
#        loop.create_task(aiomain())
#        loop.run_forever()
#    except asyncio.CancelledError:
#        pass

if __name__ == '__main__':
    main()
</code>```

In this example, imagine that the sequence of task1 and task2 needs to be finished once it's started, or some artifacts will be left in an inconsistent state.  (Hence the asyncio.shield wrapper around calling tasks.)

With the code as above, if I interrupt the script soon after it starts and it's just printed Starting simulated task1 then the loop stops and task2 never gets started.  If I try switching to the version of main that's commented out then that one never exits, even though the loop is properly cancelled and nothing further happens at least for several minutes.  It does have a bit of progress in that it at least finishes any in-progress sequence of task1 and task2.

Some possible solutions from brainstorming, though I still get the feeling there must be something simpler that I'm missing:

Create a wrapper around asyncio.shield which increments a variable synchronized by an asyncio.Condition object, runs the shielded function, then decrements the variable.  Then, in aiomain in a CancelledError handler, wait for the variable to reach zero before reraising the exception.  (In an implementation, I would probably go for combining all the parts of this into one class with __aexit__ implementing the wait for zero on CancelledError logic.)

Skip using asyncio's cancellation mechanism entirely, and instead use an asyncio.Event or similar to allow for interruption points or interruptible sleeps.  Though this does seem like it would be more invasive requiring me to specify what points are considered interruptible, as opposed to declaring what sequences need to be shielded from cancellation.

答:
Here is what I ended up using:

```<code>import asyncio, signal

async def _shield_and_wait_body(coro, finish_event):
    try:
        await coro
    finally:
        finish_event.set()

async def shield_and_wait(coro):
    finish_event = asyncio.Event()
    task = asyncio.shield(_shield_and_wait_body(coro, finish_event))
    try:
        await task
    except asyncio.CancelledError:
        await finish_event.wait()
        raise

def shield_and_wait_decorator(coro_fn):
    return lambda *args, **kwargs: shield_and_wait(coro_fn(*args, **kwargs))

async def task1():
    print("Starting simulated task1")
    await asyncio.sleep(5)
    print("Finished simulated task1")

async def task2():
    print("Starting simulated task2")
    await asyncio.sleep(5)
    print("Finished simulated task2")

@shield_and_wait_decorator
async def tasks():
    await task1()
    await task2()

async def task_loop():
    try:
        while True:
            # Alternative to applying @shield_and_wait_decorator to tasks()
            #await shield_and_wait(tasks())
            await tasks()
            await asyncio.sleep(60)
    except asyncio.CancelledError:
        print("Shutting down task loop")
        raise

def sigint_handler(task):
    print("Cancelling task loop")
    task.cancel()

async def aiomain():
    loop = asyncio.get_running_loop()
    task = asyncio.Task(task_loop())
    loop.add_signal_handler(signal.SIGINT, sigint_handler, task)
    await task

def main():
    try:
        asyncio.run(aiomain())
    except asyncio.CancelledError:
        pass

if __name__ == '__main__':
    main()
</code>```

Similar to the answer by Paul Cornelius, this inserts a wait for the subtask to finish before allowing the CancelledError to propagate up the call chain.  However, it does not require touching the code other than at the point you would be calling asyncio.shield.

(In my actual use case, I had three loops running simultaneously, using an asyncio.Lock to make sure one task or sequence of tasks finished before another would start.  I also had an asyncio.Condition on that lock communicating from one coroutine to another.  When I tried the approach of waiting in aiomain or main for all shielded tasks to be done, I ran into an issue where a cancelled parent released the lock, then a shielded task tried to signal the condition variable using that lock, giving an error.  It also didn't make sense to move acquiring and releasing the lock into the shielded task - that would result in task B still running in the sequence: shielded task A starts, coroutine for task B expires its timer and blocks waiting for the lock, Control+C.  By putting the wait at the point of the shield_and_wait call, on the other hand, it neatly avoided prematurely releasing the lock.)

One caveat: it seems that shield_and_wait_decorator doesn't work properly on class methods.

Body:
I'm trying to add some code to my existing asyncio loop to provide for a clean shutdown on Ctrl-C.  Below is an abstraction of the sort of thing it's doing.

import asyncio, signal

async def task1():
    print("Starting simulated task1")
    await asyncio.sleep(5)
    print("Finished simulated task1")

async def task2():
    print("Starting simulated task2")
    await asyncio.sleep(5)
    print("Finished simulated task2")

async def tasks():
    await task1()
    await task2()

async def task_loop():
    try:
        while True:
            await asyncio.shield(tasks())
            await asyncio.sleep(60)
    except asyncio.CancelledError:
        print("Shutting down task loop")
        raise

async def aiomain():
    loop = asyncio.get_running_loop()
    task = asyncio.Task(task_loop())
    loop.add_signal_handler(signal.SIGINT, task.cancel)
    await task

def main():
    try:
        asyncio.run(aiomain())
    except asyncio.CancelledError:
        pass

#def main():
#    try:
#        loop = asyncio.get_event_loop()
#        loop.create_task(aiomain())
#        loop.run_forever()
#    except asyncio.CancelledError:
#        pass

if __name__ == '__main__':
    main()

In this example, imagine that the sequence of task1 and task2 needs to be finished once it's started, or some artifacts will be left in an inconsistent state.  (Hence the asyncio.shield wrapper around calling tasks.)

With the code as above, if I interrupt the script soon after it starts and it's just printed Starting simulated task1 then the loop stops and task2 never gets started.  If I try switching to the version of main that's commented out then that one never exits, even though the loop is properly cancelled and nothing further happens at least for several minutes.  It does have a bit of progress in that it at least finishes any in-progress sequence of task1 and task2.

Some possible solutions from brainstorming, though I still get the feeling there must be something simpler that I'm missing:

Create a wrapper around asyncio.shield which increments a variable synchronized by an asyncio.Condition object, runs the shielded function, then decrements the variable.  Then, in aiomain in a CancelledError handler, wait for the variable to reach zero before reraising the exception.  (In an implementation, I would probably go for combining all the parts of this into one class with __aexit__ implementing the wait for zero on CancelledError logic.)

Skip using asyncio's cancellation mechanism entirely, and instead use an asyncio.Event or similar to allow for interruption points or interruptible sleeps.  Though this does seem like it would be more invasive requiring me to specify what points are considered interruptible, as opposed to declaring what sequences need to be shielded from cancellation.

Body:
Here is what I ended up using:

import asyncio, signal

async def _shield_and_wait_body(coro, finish_event):
    try:
        await coro
    finally:
        finish_event.set()

async def shield_and_wait(coro):
    finish_event = asyncio.Event()
    task = asyncio.shield(_shield_and_wait_body(coro, finish_event))
    try:
        await task
    except asyncio.CancelledError:
        await finish_event.wait()
        raise

def shield_and_wait_decorator(coro_fn):
    return lambda *args, **kwargs: shield_and_wait(coro_fn(*args, **kwargs))

async def task1():
    print("Starting simulated task1")
    await asyncio.sleep(5)
    print("Finished simulated task1")

async def task2():
    print("Starting simulated task2")
    await asyncio.sleep(5)
    print("Finished simulated task2")

@shield_and_wait_decorator
async def tasks():
    await task1()
    await task2()

async def task_loop():
    try:
        while True:
            # Alternative to applying @shield_and_wait_decorator to tasks()
            #await shield_and_wait(tasks())
            await tasks()
            await asyncio.sleep(60)
    except asyncio.CancelledError:
        print("Shutting down task loop")
        raise

def sigint_handler(task):
    print("Cancelling task loop")
    task.cancel()

async def aiomain():
    loop = asyncio.get_running_loop()
    task = asyncio.Task(task_loop())
    loop.add_signal_handler(signal.SIGINT, sigint_handler, task)
    await task

def main():
    try:
        asyncio.run(aiomain())
    except asyncio.CancelledError:
        pass

if __name__ == '__main__':
    main()

Similar to the answer by Paul Cornelius, this inserts a wait for the subtask to finish before allowing the CancelledError to propagate up the call chain.  However, it does not require touching the code other than at the point you would be calling asyncio.shield.

(In my actual use case, I had three loops running simultaneously, using an asyncio.Lock to make sure one task or sequence of tasks finished before another would start.  I also had an asyncio.Condition on that lock communicating from one coroutine to another.  When I tried the approach of waiting in aiomain or main for all shielded tasks to be done, I ran into an issue where a cancelled parent released the lock, then a shielded task tried to signal the condition variable using that lock, giving an error.  It also didn't make sense to move acquiring and releasing the lock into the shielded task - that would result in task B still running in the sequence: shielded task A starts, coroutine for task B expires its timer and blocks waiting for the lock, Control+C.  By putting the wait at the point of the shield_and_wait call, on the other hand, it neatly avoided prematurely releasing the lock.)

One caveat: it seems that shield_and_wait_decorator doesn't work properly on class methods.


问:
Cannot get output from cmd.exe execution
The code is as follows:

```<code>ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/c" + command);
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.Arguments = arguments;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;

Process process = Process.start(startInfo);
StreamReader srOutput = process.StandardOutput;
string output = srOutput.ReadToEnd();
</code>```

The command is rmdir /s /q 123

I expect to get "The system cannot find the file specified" inside the variable output because "123" is a file path that doesn't exist. But output is an empty string. Why and how should I go about getting the output?

答: The message you're expecting to see will be onStandardError, not StandardOutput.

Body:
The code is as follows:

ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/c" + command);
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.Arguments = arguments;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;

Process process = Process.start(startInfo);
StreamReader srOutput = process.StandardOutput;
string output = srOutput.ReadToEnd();

The command is rmdir /s /q 123

I expect to get "The system cannot find the file specified" inside the variable output because "123" is a file path that doesn't exist. But output is an empty string. Why and how should I go about getting the output?


问:
Creating exceptions with super constructors
I have a custom exception class like the following :

```<code>public abstract class AccountException extends BankServiceException {

private int accountNo;

public AccountException(String message, int accountNo) {
    super(message);
    this.accountNo = accountNo;

}

public int getAccountNo() {
    return accountNo;
}
</code>```

Now I need to extend this abstract class to a more specific exception:

```<code>public class  OverdraftLimitReachedException extends AccountException {

private double amount;
private double overdraft;

public OverdraftLimitReachedException(int accountNo,double amount,double overdraft) {
 super("The overdraft limit has been exceded",accountNo,amount,overdraft);
    this.overdraft = overdraft;
    this.amount = amount;
}

public double getAmount() {
    return amount;
}

public double getOverdraft() {
    return overdraft;
}
</code>```

Now the problem here is the super constructor,I am aware that I need to give it the parameter amount and overdraft as well but when I try to compile it says that the arguments differentiate in length.How do I call the super constructor corectlly, so that I can give out the error message.Thank you!

EDIT:I have added how the constructor actually looks like (sorry I'm a bit clumsy).Later in the code when I actually throw the exception I need to give the parameters of the constructor.

答:
In your code you call the superconstructor with:

```<code>super("The overdraft limit has been exceded",accountNo,amount,overdraft);
</code>```

This passes in 4 arguments:

"The overdraft limit has been exceded" (String)

accountNo (int)

amount (double)

overdraft (double)

Your superconstructor is written like this:

```<code>public AccountException(String message, int accountNo) {
</code>```

This accepts 2 arguments:

A String

An int

You need to make the two argument lists match.  Either you need to edit the call to super to be:

```<code>super("The overdraft limit has been exceded", accountNo);
</code>```

OR you need to edit the superconstructor to be:

```<code>public AccountException(String message, int accountNo, double amount, double overdraft) {
</code>```

I suspect you want to use the former because you already use amount and overdraft with this code:

```<code>this.overdraft = overdraft;
this.amount = amount;
</code>```

Also, a minor mistake, but you misspelled the word "exceeded" in your message.

Body:
I have a custom exception class like the following :

public abstract class AccountException extends BankServiceException {

private int accountNo;

public AccountException(String message, int accountNo) {
    super(message);
    this.accountNo = accountNo;

}

public int getAccountNo() {
    return accountNo;
}

Now I need to extend this abstract class to a more specific exception:

public class  OverdraftLimitReachedException extends AccountException {

private double amount;
private double overdraft;

public OverdraftLimitReachedException(int accountNo,double amount,double overdraft) {
 super("The overdraft limit has been exceded",accountNo,amount,overdraft);
    this.overdraft = overdraft;
    this.amount = amount;
}

public double getAmount() {
    return amount;
}

public double getOverdraft() {
    return overdraft;
}

Now the problem here is the super constructor,I am aware that I need to give it the parameter amount and overdraft as well but when I try to compile it says that the arguments differentiate in length.How do I call the super constructor corectlly, so that I can give out the error message.Thank you!

EDIT:I have added how the constructor actually looks like (sorry I'm a bit clumsy).Later in the code when I actually throw the exception I need to give the parameters of the constructor.

Body:
In your code you call the superconstructor with:

super("The overdraft limit has been exceded",accountNo,amount,overdraft);

This passes in 4 arguments:

"The overdraft limit has been exceded" (String)

accountNo (int)

amount (double)

overdraft (double)

Your superconstructor is written like this:

public AccountException(String message, int accountNo) {

This accepts 2 arguments:

A String

An int

You need to make the two argument lists match.  Either you need to edit the call to super to be:

super("The overdraft limit has been exceded", accountNo);

OR you need to edit the superconstructor to be:

public AccountException(String message, int accountNo, double amount, double overdraft) {

I suspect you want to use the former because you already use amount and overdraft with this code:

this.overdraft = overdraft;
this.amount = amount;

Also, a minor mistake, but you misspelled the word "exceeded" in your message.


问:
How to make a catch block with more arguments that i catch it from objects from classes for exceptions?
I have three exceptions classes in my code, so when i want to use more arguments (more different objects to catch i get an compile error) so how i can catch more exceptions?

i tried to do this

```<code>try{
        User * u = new FacebookUser(username,password,email,friends,likes,comments);
        network += u;
        }
        catch(InvalidPassword ip,InvalidEmail ie,MaximumSizeLimit ms){
            ip.message();
            ie.message();
            ms.message():
        }
</code>```

First exception is for checking if password have at least 1 uppercase,lowercase and number.

Second exception is for checking if email have at least 1 @ .

Third exception is for changing static variable, if the maximum is equal to n throw exception.

My throw exceptions for email and password are in my user constructor.

答:
If you have multiple types of exceptions you want to catch, you need to catch them separately - otherwise, what would be in say ip if InvalidEmail was thrown?

Correct code will be like

try {
    //...
} catch (const InvalidPassword& ip) {
    //...
} catch (const InvalidEmail& ie) {
    //...
} catch (const MaximumSizeLimit& ms) {
    //...
}
```

Othewrise, you can make all this exceptions inherited to the same base class and make message virtual function of this base class.

(as a separate note, it is sometimes considered bad style to use exceptions for such checks)

Body:
I have three exceptions classes in my code, so when i want to use more arguments (more different objects to catch i get an compile error) so how i can catch more exceptions?

i tried to do this

try{
        User * u = new FacebookUser(username,password,email,friends,likes,comments);
        network += u;
        }
        catch(InvalidPassword ip,InvalidEmail ie,MaximumSizeLimit ms){
            ip.message();
            ie.message();
            ms.message():
        }

First exception is for checking if password have at least 1 uppercase,lowercase and number.

Second exception is for checking if email have at least 1 @ .

Third exception is for changing static variable, if the maximum is equal to n throw exception.

My throw exceptions for email and password are in my user constructor.

Body:
If you have multiple types of exceptions you want to catch, you need to catch them separately - otherwise, what would be in say ip if InvalidEmail was thrown?

Correct code will be like

try {
    //...
} catch (const InvalidPassword& ip) {
    //...
} catch (const InvalidEmail& ie) {
    //...
} catch (const MaximumSizeLimit& ms) {
    //...
}

Othewrise, you can make all this exceptions inherited to the same base class and make message virtual function of this base class.

(as a separate note, it is sometimes considered bad style to use exceptions for such checks)


问:
Can't run typescript code with decorators
I have this two simple files but every time I try to run the testClass.ts I get this error:

```<code>PS C:\Deno\pancakes> deno run testClass.ts
Compile file:///C:/Deno/pancakes/testClass.ts
error: TS1219 [ERROR]: Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig' to remove this warning.
    name: string;
    ~~~~
    at file:///C:/Deno/pancakes/testClass.ts:5:5
</code>```

testClass.ts

```<code>import { notNull } from "./mod.ts";

class Person {
    @notNull
    name: string;

    constructor(name: string) {
        this.name = name;
    }
}

let newPerson = new Person("");
</code>```

mod.ts

```<code>export function notNull(target: any, propertyKey: string) {
    console.log(target, propertyKey);
}
</code>```

I have already enable the experimentalDecorators option in VSCode, create the tsconfig.json and everything but still can't run the program. I't doesn't show the error in VSCode but can't run.

Edit: this is what happens

答:
With deno you need to explicitly specify your tsconfig,

```<code>> deno run -c tsconfig.json testClass.ts
</code>```

https://deno.land/manual/getting_started/typescript#custom-typescript-compiler-options

Body:
I have this two simple files but every time I try to run the testClass.ts I get this error:

PS C:\Deno\pancakes> deno run testClass.ts
Compile file:///C:/Deno/pancakes/testClass.ts
error: TS1219 [ERROR]: Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig' to remove this warning.
    name: string;
    ~~~~
    at file:///C:/Deno/pancakes/testClass.ts:5:5

testClass.ts

import { notNull } from "./mod.ts";

class Person {
    @notNull
    name: string;

    constructor(name: string) {
        this.name = name;
    }
}

let newPerson = new Person("");

mod.ts

export function notNull(target: any, propertyKey: string) {
    console.log(target, propertyKey);
}

I have already enable the experimentalDecorators option in VSCode, create the tsconfig.json and everything but still can't run the program. I't doesn't show the error in VSCode but can't run.

Edit: this is what happens

Body:
With deno you need to explicitly specify your tsconfig,

> deno run -c tsconfig.json testClass.ts

https://deno.land/manual/getting_started/typescript#custom-typescript-compiler-options


问:
Use R to Randomly Assign of Participants to Treatments on a Daily Basis
The Problem:

I am attempting to use R to generate a random study design where half of the participants are randomly assigned to "Treatement 1" and the other half are assigned to "Treatment 2". However, because half of the subjects are male and half are female and I also want to ensure that an equal number of males and females are exposed to each treatment, half of the males and females should be assigned to "Treatment 1" and the remaining half should be assigned to "Treatment 2".

There are two complications to this design: (1) This is a yearlong study and the assignment of participants to treatment must occur on a daily basis; and (2) Each participant must be exposed to "Treatment 1" a minimum 10 times in a 28 day period.

Is this even possible to automate this in the R interface? I assume so, but I think my beginner status as an R programmer prohibits me from finding the solution on my own. I have been struggling for days to figure out how to actualize this, and have looked through many similar-sounding posts on this site that were not able to be successfully applied here. I am hoping someone out there knows some tricks that could help me get unstuck in solving this problem, any advice would be greatly appreciated!

What I Have Tried:

Specific Information

```<code># There are 16 participants
p <- c("P01", "P02", "P03", "P04", "P05", "P06", "P07", "P08", "P09", "P10", "P11", "P12", "P13", "P14", "P15", "P16")

# Half are male and half are female
g <- c(rep("M", 8), rep("F", 8))

# I make a dataframe but this may not be necessary
df <- cbind.data.frame(p,g)

# There are 365 days in one year
d <- seq(1,365,1)
</code>```

...unfortunately, I am not sure how to proceed from here.

Ideal Outcome:

I am envisioning something approximate to this table as the outcome:

Basically there is a column for each participant and a row for each day. Associated with each day is an assignment to either Treatment 1 (T1) or Treatment 2 (T2), with 4 of the 8 males and 4 of the 8 females being assigned to T1 and the remainder to T2. These treatments are reassigned every day for 1 year. Not depicted in this chart is the need for each participant to be exposed to T1 at least 10 times in a 28-day period. The table does not have to look like that if something else makes more sense!

答:
Nice first question. Thanks for posting.

My understanding of your constraints is that on any given day, four males must have one treatment and four males the other treatment. The same is true of the eight females: there must be four getting each treatment. Effectively, this means that on any given day, you only need a random sample applied to four individuals, since the rest of the individuals will effectively be constrained by the first four. Males 5 - 8 will be paired up to males 1 - 4, so that male 1 always get the opposite treatment to male 5, male 2 gets the opposite treatment to male 6, etc. The same pattern is applied to the females, so that although the individual assignations are random, there are always 4 females getting treatment 1, 4 females getting treatment 2, four males getting treatment 1 and four males getting treatment 2 on any given day.

You want at least ten days where each person gets treatment 1 in a 28-day period. This further constrains randomization to the point where it probably makes as much sense to ensure that each 28 day period contains a total of 14 days of treatment 1 and 14 days of treatment 2.

That way, you can get your assignations like this:

four_cols <- replicate(4, as.vector(replicate(14, sample(rep(1:2, 14))))[1:365])
eight_cols <- cbind(four_cols, 3 - four_cols)
sixteen_cols <- cbind(1:365, eight_cols, eight_cols)
df <- setNames(as.data.frame(sixteen_cols), c("Day", paste0("M", 1:8), paste0("F", 1:8)))
```

<p>Now <code>df</code> is a data frame with a layout like your table. The treatments are given as numbers 1 or 2 and the participants are labelled M1 - M8 and F1 - F8:</p>

```df
#>    Day M1 M2 M3 M4 M5 M6 M7 M8 F1 F2 F3 F4 F5 F6 F7 F8
#> 1    1  1  1  1  1  2  2  2  2  1  1  1  1  2  2  2  2
#> 2    2  2  2  2  2  1  1  1  1  2  2  2  2  1  1  1  1
#> 3    3  2  1  1  2  1  2  2  1  2  1  1  2  1  2  2  1
#> 4    4  2  2  2  1  1  1  1  2  2  2  2  1  1  1  1  2
#> 5    5  1  2  1  1  2  1  2  2  1  2  1  1  2  1  2  2
#> 6    6  2  2  2  2  1  1  1  1  2  2  2  2  1  1  1  1
#> 7    7  1  2  1  1  2  1  2  2  1  2  1  1  2  1  2  2
#> 8    8  1  1  2  2  2  2  1  1  1  1  2  2  2  2  1  1
#> 9    9  2  2  1  2  1  1  2  1  2  2  1  2  1  1  2  1
#> 10  10  2  1  2  2  1  2  1  1  2  1  2  2  1  2  1  1
#> 11  11  1  2  2  2  2  1  1  1  1  2  2  2  2  1  1  1
#> 12  12  2  1  2  1  1  2  1  2  2  1  2  1  1  2  1  2
#> 13  13  1  1  1  1  2  2  2  2  1  1  1  1  2  2  2  2
#> 14  14  2  1  1  1  1  2  2  2  2  1  1  1  1  2  2  2
#> 15  15  1  1  2  1  2  2  1  2  1  1  2  1  2  2  1  2
#> 16  16  1  2  1  1  2  1  2  2  1  2  1  1  2  1  2  2
#> 17  17  2  2  2  2  1  1  1  1  2  2  2  2  1  1  1  1
#> ...
#> 365 365  2  2  2  2  1  1  1  1  2  2  2  2  1  1  1  1
```

Body:
The Problem:

I am attempting to use R to generate a random study design where half of the participants are randomly assigned to "Treatement 1" and the other half are assigned to "Treatment 2". However, because half of the subjects are male and half are female and I also want to ensure that an equal number of males and females are exposed to each treatment, half of the males and females should be assigned to "Treatment 1" and the remaining half should be assigned to "Treatment 2".

There are two complications to this design: (1) This is a yearlong study and the assignment of participants to treatment must occur on a daily basis; and (2) Each participant must be exposed to "Treatment 1" a minimum 10 times in a 28 day period.

Is this even possible to automate this in the R interface? I assume so, but I think my beginner status as an R programmer prohibits me from finding the solution on my own. I have been struggling for days to figure out how to actualize this, and have looked through many similar-sounding posts on this site that were not able to be successfully applied here. I am hoping someone out there knows some tricks that could help me get unstuck in solving this problem, any advice would be greatly appreciated!

What I Have Tried:

Specific Information

# There are 16 participants
p <- c("P01", "P02", "P03", "P04", "P05", "P06", "P07", "P08", "P09", "P10", "P11", "P12", "P13", "P14", "P15", "P16")

# Half are male and half are female
g <- c(rep("M", 8), rep("F", 8))

# I make a dataframe but this may not be necessary
df <- cbind.data.frame(p,g)

# There are 365 days in one year
d <- seq(1,365,1)

...unfortunately, I am not sure how to proceed from here.

Ideal Outcome:

I am envisioning something approximate to this table as the outcome:

Basically there is a column for each participant and a row for each day. Associated with each day is an assignment to either Treatment 1 (T1) or Treatment 2 (T2), with 4 of the 8 males and 4 of the 8 females being assigned to T1 and the remainder to T2. These treatments are reassigned every day for 1 year. Not depicted in this chart is the need for each participant to be exposed to T1 at least 10 times in a 28-day period. The table does not have to look like that if something else makes more sense!

Body:
Nice first question. Thanks for posting.

My understanding of your constraints is that on any given day, four males must have one treatment and four males the other treatment. The same is true of the eight females: there must be four getting each treatment. Effectively, this means that on any given day, you only need a random sample applied to four individuals, since the rest of the individuals will effectively be constrained by the first four. Males 5 - 8 will be paired up to males 1 - 4, so that male 1 always get the opposite treatment to male 5, male 2 gets the opposite treatment to male 6, etc. The same pattern is applied to the females, so that although the individual assignations are random, there are always 4 females getting treatment 1, 4 females getting treatment 2, four males getting treatment 1 and four males getting treatment 2 on any given day.

You want at least ten days where each person gets treatment 1 in a 28-day period. This further constrains randomization to the point where it probably makes as much sense to ensure that each 28 day period contains a total of 14 days of treatment 1 and 14 days of treatment 2.

That way, you can get your assignations like this:

four_cols <- replicate(4, as.vector(replicate(14, sample(rep(1:2, 14))))[1:365])
eight_cols <- cbind(four_cols, 3 - four_cols)
sixteen_cols <- cbind(1:365, eight_cols, eight_cols)
df <- setNames(as.data.frame(sixteen_cols), c("Day", paste0("M", 1:8), paste0("F", 1:8)))

Now df is a data frame with a layout like your table. The treatments are given as numbers 1 or 2 and the participants are labelled M1 - M8 and F1 - F8:

df
#>    Day M1 M2 M3 M4 M5 M6 M7 M8 F1 F2 F3 F4 F5 F6 F7 F8
#> 1    1  1  1  1  1  2  2  2  2  1  1  1  1  2  2  2  2
#> 2    2  2  2  2  2  1  1  1  1  2  2  2  2  1  1  1  1
#> 3    3  2  1  1  2  1  2  2  1  2  1  1  2  1  2  2  1
#> 4    4  2  2  2  1  1  1  1  2  2  2  2  1  1  1  1  2
#> 5    5  1  2  1  1  2  1  2  2  1  2  1  1  2  1  2  2
#> 6    6  2  2  2  2  1  1  1  1  2  2  2  2  1  1  1  1
#> 7    7  1  2  1  1  2  1  2  2  1  2  1  1  2  1  2  2
#> 8    8  1  1  2  2  2  2  1  1  1  1  2  2  2  2  1  1
#> 9    9  2  2  1  2  1  1  2  1  2  2  1  2  1  1  2  1
#> 10  10  2  1  2  2  1  2  1  1  2  1  2  2  1  2  1  1
#> 11  11  1  2  2  2  2  1  1  1  1  2  2  2  2  1  1  1
#> 12  12  2  1  2  1  1  2  1  2  2  1  2  1  1  2  1  2
#> 13  13  1  1  1  1  2  2  2  2  1  1  1  1  2  2  2  2
#> 14  14  2  1  1  1  1  2  2  2  2  1  1  1  1  2  2  2
#> 15  15  1  1  2  1  2  2  1  2  1  1  2  1  2  2  1  2
#> 16  16  1  2  1  1  2  1  2  2  1  2  1  1  2  1  2  2
#> 17  17  2  2  2  2  1  1  1  1  2  2  2  2  1  1  1  1
#> ...
#> 365 365  2  2  2  2  1  1  1  1  2  2  2  2  1  1  1  1


问:
PHP imap_open(), OpenSSL, and no Cipher
I have moved a PHP script to another server, and now fail to login to an IMAP (TLS) postbox:

```<code>TLS/SSL failure for mail.servername.de: SSL negotiation failed
</code>```

It seems that the problem is caused by OpenSSL, because when I try to connect to the Mailserver from both servers, I get a connection in one case (the mailserver asking for input), but none in the other (the connection is closed, I am back to bash):

```<code> openssl s_client -crlf -connect mail.servername.de:993
</code>```

The most obvious difference is here:

```<code>verify return:1
---

<snip>

-----END CERTIFICATE-----
subject=/CN=mail.servername.de
issuer=/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
---
No client certificate CA names sent
Peer signing digest: SHA512
Server Temp Key: DH, 1024 bits
---
SSL handshake has read 3398 bytes and written 483 bytes
Verification: OK
---
New, TLSv1.2, Cipher is DHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit
</code>```

And on th other server (where no connection is made)

```<code>verify return:1
depth=0 CN = mail.servername.de
verify return:1
140410888582464:error:141A318A:SSL routines:tls_process_ske_dhe:dh key too small:../ssl/statem/statem_clnt.c:2149:
---

<snip>

-----END CERTIFICATE-----
subject=CN = mail.servername.de

issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3

---
No client certificate CA names sent
---
SSL handshake has read 3167 bytes and written 318 bytes
Verification: OK
---
New, (NONE), Cipher is (NONE)
Server public key is 2048 bit
</code>```

On the mailserver dovecot is configured not to accept non-encrypted connections. But, I assume it already fails due to dh key too small, which seems to relate to cipher negotiation.

Now I simply fail to put the things together... Why does the SSL connection work from one server, but not from the other?

答:
As I own the "remote end" myself, I was able to increase security. The solution is simple, and may be relevant for others as well ...

The dovecot version is 2.2.x, which is of some relevance for the DH parmaters (see Dovecot SSL configuration). In the configuration file /etc/dovecot/conf.d/10-ssl.conf you can simply add this line:

```<code>ssl_dh_parameters_length = 2048
</code>```

And eventually, it may be necessary to add this here to the main configuration file /etc/dovecot/dovecot.conf at the end:

```<code>!include conf.d/*.conf
</code>```

Finally, it is important not to reload, but to restart dovecot.

```<code>systemctl restart dovecot
</code>```

And suddently, the weight, troubles, and frustration of several hours is gone. Great...

Title: PHP imap_open(), OpenSSL, and no Cipher

Body:
I have moved a PHP script to another server, and now fail to login to an IMAP (TLS) postbox:

TLS/SSL failure for mail.servername.de: SSL negotiation failed

It seems that the problem is caused by OpenSSL, because when I try to connect to the Mailserver from both servers, I get a connection in one case (the mailserver asking for input), but none in the other (the connection is closed, I am back to bash):

 openssl s_client -crlf -connect mail.servername.de:993

The most obvious difference is here:

verify return:1
---

<snip>

-----END CERTIFICATE-----
subject=/CN=mail.servername.de
issuer=/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3
---
No client certificate CA names sent
Peer signing digest: SHA512
Server Temp Key: DH, 1024 bits
---
SSL handshake has read 3398 bytes and written 483 bytes
Verification: OK
---
New, TLSv1.2, Cipher is DHE-RSA-AES256-GCM-SHA384
Server public key is 2048 bit

And on th other server (where no connection is made)

verify return:1
depth=0 CN = mail.servername.de
verify return:1
140410888582464:error:141A318A:SSL routines:tls_process_ske_dhe:dh key too small:../ssl/statem/statem_clnt.c:2149:
---

<snip>

-----END CERTIFICATE-----
subject=CN = mail.servername.de

issuer=C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3

---
No client certificate CA names sent
---
SSL handshake has read 3167 bytes and written 318 bytes
Verification: OK
---
New, (NONE), Cipher is (NONE)
Server public key is 2048 bit

On the mailserver dovecot is configured not to accept non-encrypted connections. But, I assume it already fails due to dh key too small, which seems to relate to cipher negotiation.

Now I simply fail to put the things together... Why does the SSL connection work from one server, but not from the other?

Body:
As I own the "remote end" myself, I was able to increase security. The solution is simple, and may be relevant for others as well ...

The dovecot version is 2.2.x, which is of some relevance for the DH parmaters (see Dovecot SSL configuration). In the configuration file /etc/dovecot/conf.d/10-ssl.conf you can simply add this line:

ssl_dh_parameters_length = 2048

And eventually, it may be necessary to add this here to the main configuration file /etc/dovecot/dovecot.conf at the end:

!include conf.d/*.conf

Finally, it is important not to reload, but to restart dovecot.

systemctl restart dovecot

And suddently, the weight, troubles, and frustration of several hours is gone. Great...


答:
This call

```<code>super("The overdraft limit has been exceded", accountNo , amount, overdraft);
</code>```

won't work because your super constructor only has 2 parameters.

```<code>AccountException(String message, int accountNo)
</code>```

I'm not sure what you wanted to do, but if you wanted to add the amount and overdraft in the message, you can do something like this, which only passes in a String and an int.

```<code>super("The overdraft limit has been exceded by " +
      overdraft + ". You had " + amount +
      " dollars left in your account.",
      accountNo);
</code>```

You can't expect your AccountException superclass to know about overdrafts - that's considered bad design. Instead, your OverdraftLimitReachedException class has to make its own specialized message.

Title: Creating exceptions with super constructors

Body:
This call

super("The overdraft limit has been exceded", accountNo , amount, overdraft);

won't work because your super constructor only has 2 parameters.

AccountException(String message, int accountNo)

I'm not sure what you wanted to do, but if you wanted to add the amount and overdraft in the message, you can do something like this, which only passes in a String and an int.

super("The overdraft limit has been exceded by " +
      overdraft + ". You had " + amount +
      " dollars left in your account.",
      accountNo);

You can't expect your AccountException superclass to know about overdrafts - that's considered bad design. Instead, your OverdraftLimitReachedException class has to make its own specialized message.


问:
How do you work out the average of a sum function within a temp table?
I have created a temp table that lists each client's invoice(s), plus the number of days it took to pay the invoice. A client can have more than one invoice.

Instead of this, I would just like the temp table to list each client once, along with the AVERAGE number of days it took to pay all of their invoices.

Any tips on how to do this would be much appreciated.

Thanks

```<code>select
c.client_code,
b.bill_num,
b.bill_date,
ba.TRAN_DATE,
sum(datediff(Day,b.BILL_DATE, ba.TRAN_DATE)) as Days_To_Pay

into #tempG1

from blt_bill b
left outer join blt_billm bm on b.tran_uno = bm.bill_tran_uno
left outer join BLT_BILL_AMT ba on bm.BILLM_UNO = ba.BILLM_UNO
left outer join hbm_matter m on bm.matter_uno = m.matter_uno
left outer join hbm_client c on m.client_uno = c.client_uno

where b.total_bill_amt > 0.0
and bm.ar_status NOT IN ('P','X')
and ba.TRAN_TYPE in ('CR','crx')

group by c.client_code,b.bill_num,b.bill_date,ba.TRAN_DATE

select * from #tempG1

Drop Table #tempG1
</code>```

答:
I am not familiar with temp tables, but this should work (tested on a simliar scenario on MySQL8 and assuming that #tempG1 return results):

```<code>select
c.client_code,
b.bill_num,
b.bill_date,
ba.TRAN_DATE,
sum(datediff(Day,b.BILL_DATE, ba.TRAN_DATE)) as Days_To_Pay

from blt_bill b
left outer join blt_billm bm on b.tran_uno = bm.bill_tran_uno
left outer join BLT_BILL_AMT ba on bm.BILLM_UNO = ba.BILLM_UNO
left outer join hbm_matter m on bm.matter_uno = m.matter_uno
left outer join hbm_client c on m.client_uno = c.client_uno

where b.total_bill_amt > 0.0
and bm.ar_status NOT IN ('P','X')
and ba.TRAN_TYPE in ('CR','crx')

group by c.client_code,b.bill_num,b.bill_date,ba.TRAN_DATE

into #tempG1
############################
SELECT temp.client_code, AVG(temp.Days_To_Pay)
FROM (select * from #tempG1) as temp
GROUP BY temp.client_code
############################
#### Do you see results if drop? ####
Drop Table #tempG1

</code>```

Note that I put #tempG1, at the bottom of your SELECT request, but might not be what want to achieve, not sure if you want to include your JOIN conditions or not.

Or you could do without temp table(including your join conditions):

```<code>SELECT   temp.client_code, AVG(temp.Days_To_Pay)
(
   select
   c.client_code,
   b.bill_num,
   b.bill_date,
   ba.TRAN_DATE,
   sum(datediff(Day,b.BILL_DATE, ba.TRAN_DATE)) as Days_To_Pay

   from blt_bill b
   left outer join blt_billm bm on b.tran_uno = bm.bill_tran_uno
   left outer join BLT_BILL_AMT ba on bm.BILLM_UNO = ba.BILLM_UNO
   left outer join hbm_matter m on bm.matter_uno = m.matter_uno
   left outer join hbm_client c on m.client_uno = c.client_uno

   where b.total_bill_amt > 0.0
   and bm.ar_status NOT IN ('P','X')
   and ba.TRAN_TYPE in ('CR','crx')

   group by c.client_code,b.bill_num,b.bill_date,ba.TRAN_DATE
) as temp

GROUP BY temp.client_code

</code>```

Body:
I have created a temp table that lists each client's invoice(s), plus the number of days it took to pay the invoice. A client can have more than one invoice.

Instead of this, I would just like the temp table to list each client once, along with the AVERAGE number of days it took to pay all of their invoices.

Any tips on how to do this would be much appreciated.

Thanks

select
c.client_code,
b.bill_num,
b.bill_date,
ba.TRAN_DATE,
sum(datediff(Day,b.BILL_DATE, ba.TRAN_DATE)) as Days_To_Pay

into #tempG1

from blt_bill b
left outer join blt_billm bm on b.tran_uno = bm.bill_tran_uno
left outer join BLT_BILL_AMT ba on bm.BILLM_UNO = ba.BILLM_UNO
left outer join hbm_matter m on bm.matter_uno = m.matter_uno
left outer join hbm_client c on m.client_uno = c.client_uno

where b.total_bill_amt > 0.0
and bm.ar_status NOT IN ('P','X')
and ba.TRAN_TYPE in ('CR','crx')

group by c.client_code,b.bill_num,b.bill_date,ba.TRAN_DATE

select * from #tempG1

Drop Table #tempG1

Body:
I am not familiar with temp tables, but this should work (tested on a simliar scenario on MySQL8 and assuming that #tempG1 return results):

select
c.client_code,
b.bill_num,
b.bill_date,
ba.TRAN_DATE,
sum(datediff(Day,b.BILL_DATE, ba.TRAN_DATE)) as Days_To_Pay

from blt_bill b
left outer join blt_billm bm on b.tran_uno = bm.bill_tran_uno
left outer join BLT_BILL_AMT ba on bm.BILLM_UNO = ba.BILLM_UNO
left outer join hbm_matter m on bm.matter_uno = m.matter_uno
left outer join hbm_client c on m.client_uno = c.client_uno

where b.total_bill_amt > 0.0
and bm.ar_status NOT IN ('P','X')
and ba.TRAN_TYPE in ('CR','crx')

group by c.client_code,b.bill_num,b.bill_date,ba.TRAN_DATE

into #tempG1
############################
SELECT temp.client_code, AVG(temp.Days_To_Pay)
FROM (select * from #tempG1) as temp
GROUP BY temp.client_code
############################
#### Do you see results if drop? ####
Drop Table #tempG1

Note that I put #tempG1, at the bottom of your SELECT request, but might not be what want to achieve, not sure if you want to include your JOIN conditions or not.

Or you could do without temp table(including your join conditions):

SELECT   temp.client_code, AVG(temp.Days_To_Pay)
(
   select
   c.client_code,
   b.bill_num,
   b.bill_date,
   ba.TRAN_DATE,
   sum(datediff(Day,b.BILL_DATE, ba.TRAN_DATE)) as Days_To_Pay

   from blt_bill b
   left outer join blt_billm bm on b.tran_uno = bm.bill_tran_uno
   left outer join BLT_BILL_AMT ba on bm.BILLM_UNO = ba.BILLM_UNO
   left outer join hbm_matter m on bm.matter_uno = m.matter_uno
   left outer join hbm_client c on m.client_uno = c.client_uno

   where b.total_bill_amt > 0.0
   and bm.ar_status NOT IN ('P','X')
   and ba.TRAN_TYPE in ('CR','crx')

   group by c.client_code,b.bill_num,b.bill_date,ba.TRAN_DATE
) as temp

GROUP BY temp.client_code


问:
How to add a search function to my JavaScript?
I am developing a music player using JavaScript and I am trying to add a search bar to my page but every tutorial I have seen so far uses a list created in the HTML page, whereas I have created a list using JavaScript code like this:

```<code>const songs = [
    "BlindingLights.mp3",
    "Boyfriend.mp3",
    "DontStartNow.mp3",
    "Intentions.mp3",
    "Physical"
]

const createSongList = () => {
    const list = document.createElement('ol')

    for(let i = 0; i<songs.length; i++){
        const item = document.createElement('li')
        item.appendChild(document.createTextNode(songs[i]))

        list.appendChild(item)
    }

    return list
}

document.getElementById('songList').appendChild(createSongList())
</code>```

Is there a way I can use the 'songs' array or to develop a search function? Any advice would be appreciated. Thanks! :)

Edit for clarity:

So I have an input tag on my html that I want to use for a search bar, then I want what the user types in to return any matching songs from the songs array. For example if they type in 'Bli' I want it to show the Blinding Lights song.
The code snippet above is how I am currently displaying a list of songs using the array.

This is my input tag:

```<code><input type="text" name="searchBar" id="searchBar" placeholder="Search" onkeyup="searchBar()">
</code>```

答:
Maybe you can create a new function search to Array.prototype to make it used more easily

```<code>Array.prototype.search = function (keyword) {
  return this.filter(text => text.toLowerCase().includes(keyword.toLowerCase().trim()))
}
const songs = [
    "BlindingLights.mp3",
    "Boyfriend.mp6",
    "DontStartNow.mp5",
    "Intentions.mp3",
    "Physical"
];

songs.search('phy ')  // => ["Physical"]
songs.search(' MP3')  // =>  ["BlindingLights.mp3", "Intentions.mp3"]
</code>```

Body:
I am developing a music player using JavaScript and I am trying to add a search bar to my page but every tutorial I have seen so far uses a list created in the HTML page, whereas I have created a list using JavaScript code like this:

const songs = [
    "BlindingLights.mp3",
    "Boyfriend.mp3",
    "DontStartNow.mp3",
    "Intentions.mp3",
    "Physical"
]

const createSongList = () => {
    const list = document.createElement('ol')

    for(let i = 0; i<songs.length; i++){
        const item = document.createElement('li')
        item.appendChild(document.createTextNode(songs[i]))

        list.appendChild(item)
    }

    return list
}

document.getElementById('songList').appendChild(createSongList())

Is there a way I can use the 'songs' array or to develop a search function? Any advice would be appreciated. Thanks! :)

Edit for clarity:

So I have an input tag on my html that I want to use for a search bar, then I want what the user types in to return any matching songs from the songs array. For example if they type in 'Bli' I want it to show the Blinding Lights song.
The code snippet above is how I am currently displaying a list of songs using the array.

This is my input tag:

<input type="text" name="searchBar" id="searchBar" placeholder="Search" onkeyup="searchBar()">

Body:
Maybe you can create a new function search to Array.prototype to make it used more easily

Array.prototype.search = function (keyword) {
  return this.filter(text => text.toLowerCase().includes(keyword.toLowerCase().trim()))
}
const songs = [
    "BlindingLights.mp3",
    "Boyfriend.mp6",
    "DontStartNow.mp5",
    "Intentions.mp3",
    "Physical"
];

songs.search('phy ')  // => ["Physical"]
songs.search(' MP3')  // =>  ["BlindingLights.mp3", "Intentions.mp3"]


问:
Android load native library
I'm trying to load a library I built with the standalone NDK toolchain.

I built libGLmove.so and placed it in libs/armeabi of my Eclipse project

However, the call to System.loadLibrary("GLmove") throws an UnsatisfiedLinkError

Any ideas as to how to resolve the problem or make Android find my library?
How does ndk-build package the library after it builds it?

Edit:  The exact compile flags are:

/Users/thomas/Documents/android-ndk-r5b/toolchains/arm-eabi-4.4.0/prebuilt/darwin-x86/bin/arm-eabi-g++ --sysroot=/Users/thomas/Documents/android-ndk-r5b/platforms/android-8/arch-arm  -march=armv7-a -mfloat-abi=softfp -mfpu=neon -Wl,--fix-cortex-a8 -fno-exceptions -fno-rtti -nostdlib -fpic -shared -o GLmove.so -O3

答:
Could you please check the syntax and the location of System.loadLibrary("GLmove")

the System.loadLibrary call should be in static block of the Java source file

```<code>static {
    System.loadLibrary("nativelib");
}</code>```

http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html

Title: Android load native library

Body:
Could you please check the syntax and the location of System.loadLibrary("GLmove")

the System.loadLibrary call should be in static block of the Java source file

static {
    System.loadLibrary("nativelib");
}

http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html


问:
Having hard time working with ArrayForm : adding form field
I'm trying to display add a playlist in Mat-dialog that has songs in a list using (formArray) like this:

but I don't what mistake I'm making

my dialogue look this way:

here's my code:

my Dialog.component.html

```<code><h1 mat-dialog-title>Create New Playlist
</h1>
<form [formGroup]='form'>
<div>

  <div mat-dialog-content>

      <mat-form-field class="input-width" appearance="standard">
        <mat-label>Playlist name</mat-label>
        <input  matInput placeholder="" required formControlName="name"  [(ngModel)]="data.name">

      </mat-form-field>
      <mat-form-field class="input-width" appearance="standard">
        <mat-label>Description</mat-label>
        <input  matInput placeholder="" required formControlName="description" [(ngModel)]="data.description" >

      </mat-form-field>

  <div formArrayName="songs" >
    <div *ngFor = "let song of form.controls.songs?.value; let i = index">
      <div class="song-input-wrapper" [formGroupName]="i">
        <mat-form-field  appearance="standard">
          <mat-label>Song Title</mat-label>
          <input  matInput placeholder="" required formControlName="title">

        </mat-form-field>
        <mat-form-field  appearance="standard">
          <mat-label>Artist</mat-label>
          <input matInput placeholder="" required formControlName="artist">

        </mat-form-field>
        <mat-form-field appearance="standard">
          <mat-label>Duration</mat-label>
          <input matInput type="number" required  formControlName="duration">
          <span matSuffix>minutes</span>
        </mat-form-field>
          <button mat-icon-button color="primary" (click)="addSong()">
            <mat-icon>add_circle</mat-icon>
          </button>
          <button
          *ngIf="form.controls.songs?.value > 1"
          mat-icon-button
          color="warn"
          (click)="removeSong(i)"
        >
          <mat-icon>remove_circle</mat-icon>
        </button>

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

</div>

  </div>
         <mat-dialog-actions class="action-buttons">
    <button mat-raised-button  color="warn" (click)="close()" >Cancel </button>
  <button mat-raised-button color="primary"  [disabled] = "form.invalid" (click)="onSubmit()" [mat-dialog-close]="data">Submit</button>

  </mat-dialog-actions>
</form>
</code>```

and my dialog.componenet.ts:

```<code>export class DialogComponent implements OnInit {

  description:string;
  songs: FormArray;
  constructor(public service: PlaylistService,public dialogRef: MatDialogRef<DialogComponent>, private formBuilder: FormBuilder, @Inject(MAT_DIALOG_DATA) public data: Playlist  )
   {
   }

   form : FormGroup = new FormGroup(
    {
      name:new FormControl('', Validators.required),
      description:new FormControl('',Validators.required),
      title:new FormControl('',Validators.required),
      artist:new FormControl('',Validators.required),
      duration:new FormControl(0,[Validators.required , Validators.min(0)]),
      songs:  this.formBuilder.array([  ])

    }
  )

  songsform() :FormArray {
    return this.form.get('songs') as FormArray ;
  }
  addCreds() {
    const creds = this.form.controls.credentials as FormArray;
    creds.push(this.formBuilder.group({
      title:'',
      artist: '',
      duration: 0,
    }));
  }

  ngOnInit(): void {

      }

  close() {
    this.dialogRef.close();
}

createSong(): FormGroup {
  return this.formBuilder.group({
    title: [null, Validators.required],
    artist: [null, Validators.required],
    duration: [null, Validators.compose([Validators.required, Validators.min(0)])],
  });
}
addSong(): void {
  this.songs.push(this.createSong());
}
removeSong(index: number): void {
  if (this.songs.controls.length > 1) {
    this.songs.removeAt(index);
  }
}
  onSubmit(){

      this.dialogRef.close(this.form.value);

  }
  }
</code>```

and finally, the component where I open the dialog and where my playlist class exist:

```<code>export interface Playlist {
  name: string;
  totalDuration: number;
  totalSongs: number;
  description: string;
  songs: Song[];
}

export interface Song {
  title: string;
  artist: string;
  duration: number;
}
@Component({
  selector: 'app-playlist',
  templateUrl: './playlist.component.html',
  styleUrls: ['./playlist.component.css']
})

export class PlaylistComponent implements OnInit {

  constructor(public dialog: MatDialog,public service: PlaylistService) { }

  ngOnInit(): void {
  }

  playlists: Playlist[] = [
    {
      name: 'Kopikustik',
      totalDuration: 5,
      totalSongs: 2,
      description: 'More than a coffee, this is all of your favorite accoustic songs.',
      songs: [
        {
          title: 'Cigarettes of ours',
          artist: 'Ardhito Pramono',
          duration: 3
        },
        {
          title: 'Walking Back Home',
          artist: 'Vira Talisa',
          duration: 2
        },
      ]
    },
    {
      name: 'Anime Hits',
      totalDuration: 13,
      totalSongs: 3,
      description: 'Listen to your favorite Anime songs, all in one playlist.',
      songs: [
        {
          title: 'Renai Circulation',
          artist: 'Kana Hanazawa',
          duration: 4
        },
        {
          title: 'Platinum Disco',
          artist: 'Tsukihi Phoenix',
          duration: 4
        },
        {
          title: 'Silhouette',
          artist: 'KANA-BOON',
          duration: 5
        },
      ]
    }
  ];
  name:String
  @Input() data: Playlist
  openDialog(): void {
    const dialogConfig = new MatDialogConfig();
    dialogConfig.autoFocus = false;
    const dialogRef = this.dialog.open(DialogComponent, {

      width: '900px',
      data: {
        name : this.name,
      songs: []
      }
    });

    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
      if (result) {
        this.name = result.name;
        alert("name is :"+ this.name)
        }
    });
  }

  deletePlaylist(i)
  {
    this.playlists.splice(i, 1);
  }

}
</code>```

if anyone is familiar or can see what I'm missing please help me
I've been for a similar solution and example but I always get the same interface

答:
According to this article, it looks like you need to set a form group instance inside your array item when the form is created, the place where you create your form. Try this on ngOnInit():

```<code>form : FormGroup = new FormGroup({
      name:new FormControl('', Validators.required),
      description:new FormControl('',Validators.required),
      title:new FormControl('',Validators.required),
      artist:new FormControl('',Validators.required),
      duration:new FormControl(0,[Validators.required , Validators.min(0)]),
      songs:  this.formBuilder.array([ this.createSong() ])
    });
</code>```

Hope it helps.

Body:
I'm trying to display add a playlist in Mat-dialog that has songs in a list using (formArray) like this:

but I don't what mistake I'm making

my dialogue look this way:

here's my code:

my Dialog.component.html

Create New Playlist

<form [formGroup]='form'>

      <mat-form-field class="input-width" appearance="standard">
        <mat-label>Playlist name</mat-label>
        <input  matInput placeholder="" required formControlName="name"  [(ngModel)]="data.name">

      </mat-form-field>
      <mat-form-field class="input-width" appearance="standard">
        <mat-label>Description</mat-label>
        <input  matInput placeholder="" required formControlName="description" [(ngModel)]="data.description" >

      </mat-form-field>

        <mat-form-field  appearance="standard">
          <mat-label>Song Title</mat-label>
          <input  matInput placeholder="" required formControlName="title">

        </mat-form-field>
        <mat-form-field  appearance="standard">
          <mat-label>Artist</mat-label>
          <input matInput placeholder="" required formControlName="artist">

        </mat-form-field>
        <mat-form-field appearance="standard">
          <mat-label>Duration</mat-label>
          <input matInput type="number" required  formControlName="duration">
          minutes
        </mat-form-field>
          <button mat-icon-button color="primary" (click)="addSong()">
            <mat-icon>add_circle</mat-icon>
          </button>
          <button
          *ngIf="form.controls.songs?.value > 1"
          mat-icon-button
          color="warn"
          (click)="removeSong(i)"
        >
          <mat-icon>remove_circle</mat-icon>
        </button>

         <mat-dialog-actions class="action-buttons">
    <button mat-raised-button  color="warn" (click)="close()" >Cancel </button>
  <button mat-raised-button color="primary"  [disabled] = "form.invalid" (click)="onSubmit()" [mat-dialog-close]="data">Submit</button>

  </mat-dialog-actions>
</form>

and my dialog.componenet.ts:

export class DialogComponent implements OnInit {

  description:string;
  songs: FormArray;
  constructor(public service: PlaylistService,public dialogRef: MatDialogRef<DialogComponent>, private formBuilder: FormBuilder, @Inject(MAT_DIALOG_DATA) public data: Playlist  )
   {
   }

   form : FormGroup = new FormGroup(
    {
      name:new FormControl('', Validators.required),
      description:new FormControl('',Validators.required),
      title:new FormControl('',Validators.required),
      artist:new FormControl('',Validators.required),
      duration:new FormControl(0,[Validators.required , Validators.min(0)]),
      songs:  this.formBuilder.array([  ])

    }
  )

  songsform() :FormArray {
    return this.form.get('songs') as FormArray ;
  }
  addCreds() {
    const creds = this.form.controls.credentials as FormArray;
    creds.push(this.formBuilder.group({
      title:'',
      artist: '',
      duration: 0,
    }));
  }

  ngOnInit(): void {

      }

  close() {
    this.dialogRef.close();
}

createSong(): FormGroup {
  return this.formBuilder.group({
    title: [null, Validators.required],
    artist: [null, Validators.required],
    duration: [null, Validators.compose([Validators.required, Validators.min(0)])],
  });
}
addSong(): void {
  this.songs.push(this.createSong());
}
removeSong(index: number): void {
  if (this.songs.controls.length > 1) {
    this.songs.removeAt(index);
  }
}
  onSubmit(){

      this.dialogRef.close(this.form.value);

  }
  }

and finally, the component where I open the dialog and where my playlist class exist:

export interface Playlist {
  name: string;
  totalDuration: number;
  totalSongs: number;
  description: string;
  songs: Song[];
}

export interface Song {
  title: string;
  artist: string;
  duration: number;
}
@Component({
  selector: 'app-playlist',
  templateUrl: './playlist.component.html',
  styleUrls: ['./playlist.component.css']
})

export class PlaylistComponent implements OnInit {

  constructor(public dialog: MatDialog,public service: PlaylistService) { }

  ngOnInit(): void {
  }

  playlists: Playlist[] = [
    {
      name: 'Kopikustik',
      totalDuration: 5,
      totalSongs: 2,
      description: 'More than a coffee, this is all of your favorite accoustic songs.',
      songs: [
        {
          title: 'Cigarettes of ours',
          artist: 'Ardhito Pramono',
          duration: 3
        },
        {
          title: 'Walking Back Home',
          artist: 'Vira Talisa',
          duration: 2
        },
      ]
    },
    {
      name: 'Anime Hits',
      totalDuration: 13,
      totalSongs: 3,
      description: 'Listen to your favorite Anime songs, all in one playlist.',
      songs: [
        {
          title: 'Renai Circulation',
          artist: 'Kana Hanazawa',
          duration: 4
        },
        {
          title: 'Platinum Disco',
          artist: 'Tsukihi Phoenix',
          duration: 4
        },
        {
          title: 'Silhouette',
          artist: 'KANA-BOON',
          duration: 5
        },
      ]
    }
  ];
  name:String
  @Input() data: Playlist
  openDialog(): void {
    const dialogConfig = new MatDialogConfig();
    dialogConfig.autoFocus = false;
    const dialogRef = this.dialog.open(DialogComponent, {

      width: '900px',
      data: {
        name : this.name,
      songs: []
      }
    });

    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
      if (result) {
        this.name = result.name;
        alert("name is :"+ this.name)
        }
    });
  }

  deletePlaylist(i)
  {
    this.playlists.splice(i, 1);
  }

}

if anyone is familiar or can see what I'm missing please help me
I've been for a similar solution and example but I always get the same interface

Body:
According to this article, it looks like you need to set a form group instance inside your array item when the form is created, the place where you create your form. Try this on ngOnInit():

form : FormGroup = new FormGroup({
      name:new FormControl('', Validators.required),
      description:new FormControl('',Validators.required),
      title:new FormControl('',Validators.required),
      artist:new FormControl('',Validators.required),
      duration:new FormControl(0,[Validators.required , Validators.min(0)]),
      songs:  this.formBuilder.array([ this.createSong() ])
    });

Hope it helps.