来源: stackexchange

问:
How to exploit this string format vulnerability
I have this piece of code I've been playing around with

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

void authenticated(void) {
    printf("Authenticated\n");
    fflush(stdout);
}

void authenticate() {
    char buf[200];
    char auth = 0;

    printf("%p\n", &auth);
    fflush(stdout);

    fgets(buf, 200, stdin);

    printf(buf);
    fflush(stdout);

    if (auth) {
        authenticated();
    }
}

int main(void) {
    authenticate();
    return 0;
}
</code>```

Compiled with

```<code>gcc test.c -o test -fno-stack-protector -m32
</code>```

I followed this guide here https://www.ayrx.me/protostar-walkthrough-format to write arbitrary addresses.

By using this input

```<code>AAAA%6$p
</code>```

I get AAAA0x41414141 as the output. Now using the printed auth address as input

```<code>\xff\xff\xff\xff%x%x%x%x%x%x%n
</code>```

I get a Segmentation Fault

答:
In the general flow, printf uses the fmt to determine the types of the arguments, and copies them to its output.  Unless you have some knowledge of where the output, or output control structure is, you won't have much luck attempting to jam random stack strings or other such things into it.

If generating a SEGV is enough of an exploit you already have your answer; however there is one formatting option %n which goes in the other direction.  %n writes out, through a pointer in the argument list, how many chars it has written so far.   If we can find a stray pointer to &auth on the stack, we can make a format string which goes through this.

First up, what does the stack look like?  Run your program, and input:

%p %p %p %p %p %p .....

and look at the values that come out.  All you need is one lower than the &auth by less than the size of an int.  Greater doesn't help. If you can find one, you can then set a string with the number of %p to move to that pointer, then a %n to over-write it.   If you don't find any, you can probe further in the stack frame by starting with "%64p", which moves to arg #64 (base 1) then proceeds from there.

If your over-write misses (say you were off in address by one byte ), you can substitute in a %256.256d for one of the %p's to increase your #written.

Sadly, on my machine and compiler (macos, clang), I couldn't find a value; and I tried to induce some by shifting environment variables, etc, but to no avail.

ContentLicense: CC BY-SA 4.0

Body:
I have this piece of code I've been playing around with

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

void authenticated(void) {
    printf("Authenticated\n");
    fflush(stdout);
}

void authenticate() {
    char buf[200];
    char auth = 0;

    printf("%p\n", &auth);
    fflush(stdout);

    fgets(buf, 200, stdin);

    printf(buf);
    fflush(stdout);

    if (auth) {
        authenticated();
    }
}

int main(void) {
    authenticate();
    return 0;
}

Compiled with

gcc test.c -o test -fno-stack-protector -m32

I followed this guide here https://www.ayrx.me/protostar-walkthrough-format to write arbitrary addresses.

By using this input

AAAA%6$p

I get AAAA0x41414141 as the output. Now using the printed auth address as input

\xff\xff\xff\xff%x%x%x%x%x%x%n

I get a Segmentation Fault


问:
Helgrind (Valgrind) and OpenMP (C): avoiding false positives?
The documentation for the Valgrind thread error detection tool Helgrind, found here

warns that, if you use GCC to compile your OpenMP code, GCC's OpenMP runtime library (libgomp.so) will cause a chaos of false positive reports of data races, because of its use of atomic machine instructions and Linux futex system calls instead of POSIX pthreads primitives.  It tells you that you can solve this problem, however, by recompiling GCC with the --disable-linux-futex configuration option.

So I tried this.  I compiled and installed to a local directory (~/GCC_Valgrind/gcc_install) a new GCC version 4.7.0 (the latest release as of this writing) with the --disable-linux-futex configuration option.  I then created a small OpenMP test program (test1.c) that has no visible data races:

```<code>/* test1.c */

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

#define NUM_THREADS 2

int a[NUM_THREADS];

int main(void) {
        int i;
#pragma omp parallel num_threads(NUM_THREADS)
        {
                int tid = omp_get_thread_num();
                a[tid] = tid + 1;
        }
        for (i = 0; i < NUM_THREADS; i++)
                printf("%d ", a[i]);
        printf("\n");
        return EXIT_SUCCESS;
}
</code>```

I compiled this program as follows

```<code>~/GCC_Valgrind/gcc_install/bin/gcc -Wall -fopenmp  -static -L~/GCC_Valgrind/gcc_install/lib64 -L~/GCC_Valgrind/gcc_install/lib -o test1 test1.c
</code>```

However, I got 30 false positive data race reports!--all occurring in libgomp code.  I then compiled test1.c without the -static flag, and ran Helgrind on it again.  This time, I got only 9 false positive data race reports, but that is still too many--and, without the -static flag, I cannot trace the supposed race in the libgomp code.

Has anybody found a way to reduce, if not eliminate, the number of false positive data race reports from Helgrind applied to an OpenMP program compiled with GCC?  Thanks!

答: Please also note, that if omp_set_lock is used in the code the omp.h path must be substituted because of different lock struct size. See https://xrunhprof.wordpress.com/2018/08/27/tsan-with-openmp/

ContentLicense: CC BY-SA 3.0

Body:
The documentation for the Valgrind thread error detection tool Helgrind, found here

warns that, if you use GCC to compile your OpenMP code, GCC's OpenMP runtime library (libgomp.so) will cause a chaos of false positive reports of data races, because of its use of atomic machine instructions and Linux futex system calls instead of POSIX pthreads primitives.  It tells you that you can solve this problem, however, by recompiling GCC with the --disable-linux-futex configuration option.

So I tried this.  I compiled and installed to a local directory (~/GCC_Valgrind/gcc_install) a new GCC version 4.7.0 (the latest release as of this writing) with the --disable-linux-futex configuration option.  I then created a small OpenMP test program (test1.c) that has no visible data races:

/* test1.c */

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

#define NUM_THREADS 2

int a[NUM_THREADS];

int main(void) {
        int i;
#pragma omp parallel num_threads(NUM_THREADS)
        {
                int tid = omp_get_thread_num();
                a[tid] = tid + 1;
        }
        for (i = 0; i < NUM_THREADS; i++)
                printf("%d ", a[i]);
        printf("\n");
        return EXIT_SUCCESS;
}

I compiled this program as follows

~/GCC_Valgrind/gcc_install/bin/gcc -Wall -fopenmp  -static -L~/GCC_Valgrind/gcc_install/lib64 -L~/GCC_Valgrind/gcc_install/lib -o test1 test1.c

However, I got 30 false positive data race reports!--all occurring in libgomp code.  I then compiled test1.c without the -static flag, and ran Helgrind on it again.  This time, I got only 9 false positive data race reports, but that is still too many--and, without the -static flag, I cannot trace the supposed race in the libgomp code.

Has anybody found a way to reduce, if not eliminate, the number of false positive data race reports from Helgrind applied to an OpenMP program compiled with GCC?  Thanks!


问:
looping mysql_real_connect or what
consider following c code:

```<code>int main (int argc, char *argv[]) {
  MYSQL *sql_handle;

  fprintf(stdout,"initializing handle..\n");
  sql_handle = mysql_init(sql_handle);

  fprintf(stdout,"connecting to database..\n");
  mysql_real_connect(sql_handle,NULL,NULL,
                      NULL,"test",0,NULL,0);

  fprintf(stdout,"connection established\n");
  mysql_close(sql_handle);
}
</code>```

this produces the following output

```<code>...
initializing handle..
connecting to database..
initializing handle..
connecting to database..
initializing handle..
connecting to database..
initializing handle..
connecting to database..
connection established
Error: Can't create UNIX socket (24)
</code>```

the real_connect function seems to have problems. the daemon is running for sure. it's long time ago since i was used to c so this might be a stupid question.

[update]
here's the complete code

```<code>  1 #include <stdio.h>
  2 #include <stdlib.h>
  3
  4 #if defined __WIN32__ || _MSC_VER
  5    #include "my_global.h"
  6    #include "mysql.h"
  7 #else
  8    #include <mysql.h>
  9 #endif
 10
 11 /* prototypes */
 12 void connect(void);
 13
 14 /* sql handle */
 15 MYSQL *sql_handle;
 16
 17 int main (int argc, char *argv[]) {
 18   fprintf(stdout,"main..\n");
 19   connect();
 20   return EXIT_SUCCESS;
 21
 22 }
 23 void connect(void){
 24   fprintf(stdout,"initializing database handle..\n");
 25   sql_handle = mysql_init(NULL);
 26
 27   fprintf(stdout,"connecting to database..\n");
 28   mysql_real_connect(sql_handle,NULL,NULL,NULL,NULL,0,NULL,0);
 29
 30   fprintf(stdout,"closing connection..\n");
 31   mysql_close(sql_handle);
 32 }
</code>```

this code produces that output:

```<code>...
connecting to database..
initializing database handle..
connecting to database..
initializing database handle..
connecting to database..
closing connection..
[1]    12914 segmentation fault (core dumped)  ./db
</code>```

copying the body of the connect-function into main and removing the connect-functions resolves the issue. but this is not a solution.

答:
renaming the method

```<code>void connect(void)
</code>```

to

```<code>void connect_to_database(void)
</code>```

solved that issue for me

Title: looping mysql_real_connect or what

Body:
consider following c code:

int main (int argc, char *argv[]) {
  MYSQL *sql_handle;

  fprintf(stdout,"initializing handle..\n");
  sql_handle = mysql_init(sql_handle);

  fprintf(stdout,"connecting to database..\n");
  mysql_real_connect(sql_handle,NULL,NULL,
                      NULL,"test",0,NULL,0);

  fprintf(stdout,"connection established\n");
  mysql_close(sql_handle);
}

this produces the following output

...
initializing handle..
connecting to database..
initializing handle..
connecting to database..
initializing handle..
connecting to database..
initializing handle..
connecting to database..
connection established
Error: Can't create UNIX socket (24)

the real_connect function seems to have problems. the daemon is running for sure. it's long time ago since i was used to c so this might be a stupid question.

[update]
here's the complete code

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3
  4 #if defined __WIN32__ || _MSC_VER
  5    #include "my_global.h"
  6    #include "mysql.h"
  7 #else
  8    #include <mysql.h>
  9 #endif
 10
 11 /* prototypes */
 12 void connect(void);
 13
 14 /* sql handle */
 15 MYSQL *sql_handle;
 16
 17 int main (int argc, char *argv[]) {
 18   fprintf(stdout,"main..\n");
 19   connect();
 20   return EXIT_SUCCESS;
 21
 22 }
 23 void connect(void){
 24   fprintf(stdout,"initializing database handle..\n");
 25   sql_handle = mysql_init(NULL);
 26
 27   fprintf(stdout,"connecting to database..\n");
 28   mysql_real_connect(sql_handle,NULL,NULL,NULL,NULL,0,NULL,0);
 29
 30   fprintf(stdout,"closing connection..\n");
 31   mysql_close(sql_handle);
 32 }

this code produces that output:

...
connecting to database..
initializing database handle..
connecting to database..
initializing database handle..
connecting to database..
closing connection..
[1]    12914 segmentation fault (core dumped)  ./db

copying the body of the connect-function into main and removing the connect-functions resolves the issue. but this is not a solution.

Body:
renaming the method

void connect(void)

to

void connect_to_database(void)

solved that issue for me


问:
Angular 9 Material Dialog returning undefined on close
I'm using Angular 9 and have a Material dialog that is set to return "test" on close like this:

```<code><mat-dialog-actions align='center'>
    <button mat-raised-button color='primary' [mat-dialog-close]='"test"'>
        Submit
    </button>
</mat-dialog-actions>
</code>```

In my main page component, I'm subscribing to afterAllClosed:

```<code>  constructor(private matDialog: MatDialog) { }

  OpenMatDialog(data): void {
    this.matDialog.open(
      DialogComponent,
      { data },
    );

    if( !this.matDialogCloseSub$ )
      this.matDialogCloseSub$ = this.matDialog.afterAllClosed.subscribe(result => {
        console.log(result);
      });
  }
</code>```

However, result always comes back as undefined. What am I doing wrong?

I have set the dialog component in app.module.ts in entrycomponents as follows:

```<code>@NgModule({
  declarations: [
    AppComponent,
    DialogComponent
  ],
  imports: [
    MatDialogModule,
  ],
  entryComponents: [
    DialogComponent,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答:
The Observable afterAllClosed does not return any value, because it doesn't know which dialog data it should return. You should use, afterClosed from the MatDialogRef, which is returned from the open call:

```<code>OpenMatDialog(data): void {
  const dialogRef = this.matDialog.open(
    DialogComponent,
    { data },
  );

  if( !this.matDialogCloseSub$) {
    this.matDialogCloseSub$ = dialogRef.afterClosed.subscribe(result => {
      console.log(result);
    });
  }
}
</code>```

However, considering you are using some custom global method OpenMatDialog, I do see some issues, but at least you know now how to get the result from a dialog :). You will have to use the dialog reference, not the dialog service.

Body:
I'm using Angular 9 and have a Material dialog that is set to return "test" on close like this:

<mat-dialog-actions align='center'>
    <button mat-raised-button color='primary' [mat-dialog-close]='"test"'>
        Submit
    </button>
</mat-dialog-actions>

In my main page component, I'm subscribing to afterAllClosed:

  constructor(private matDialog: MatDialog) { }

  OpenMatDialog(data): void {
    this.matDialog.open(
      DialogComponent,
      { data },
    );

    if( !this.matDialogCloseSub$ )
      this.matDialogCloseSub$ = this.matDialog.afterAllClosed.subscribe(result => {
        console.log(result);
      });
  }

However, result always comes back as undefined. What am I doing wrong?

I have set the dialog component in app.module.ts in entrycomponents as follows:

@NgModule({
  declarations: [
    AppComponent,
    DialogComponent
  ],
  imports: [
    MatDialogModule,
  ],
  entryComponents: [
    DialogComponent,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Body:
The Observable afterAllClosed does not return any value, because it doesn't know which dialog data it should return. You should use, afterClosed from the MatDialogRef, which is returned from the open call:

OpenMatDialog(data): void {
  const dialogRef = this.matDialog.open(
    DialogComponent,
    { data },
  );

  if( !this.matDialogCloseSub$) {
    this.matDialogCloseSub$ = dialogRef.afterClosed.subscribe(result => {
      console.log(result);
    });
  }
}

However, considering you are using some custom global method OpenMatDialog, I do see some issues, but at least you know now how to get the result from a dialog :). You will have to use the dialog reference, not the dialog service.


问:
How to create a custom queryset from a json file
Is it somehow possible to create a custom queryset data structure from a given json file?

I have the json file and I want the queryset in order to use the queryset for presentation with django_tables2 and filtering with django_filters.

The key point is that I do not have any model and I do not want to create a model with the data from json.

I just want to create the queryset.

```<code>existence = 1
try:
      offer_request = requests.get(url, headers=headers)
      existence = 2
except:
      print("nothing")

if existence == 2:
     offers=json.loads(offer_request.text)
</code>```

The offers variable contains my json.

The json is a list of dictionaries.

For example one item is :

```<code>{'yachtId': 16425620217200198, 'yacht': 'Bravo Kiss', 'startBaseId': 1, 'endBaseId': 1, 'startBase': 'Dubrovnik/ACI Marina Dubrovnik', 'endBase': 'Dubrovnik/ACI Marina Dubrovnik', 'dateFrom': '2020-06-02 00:00:00', 'dateTo': '2020-06-03 00:00:00', 'product': 'Bareboat', 'price': 271.0, 'currency': 'EUR', 'startPrice': 271.0, 'discountPercentage': 0.0}
</code>```

Is it somehow possible from this data to create a queryset with structure based on the keys of the dictionary data in order to feed my template?

答:
From what I understood, you need to filter your queries based on your JSON. Considering offers have yours JSON, you can use:

```<code>MyModel.objects.filter(**offers)
</code>```

Body:
Is it somehow possible to create a custom queryset data structure from a given json file?

I have the json file and I want the queryset in order to use the queryset for presentation with django_tables2 and filtering with django_filters.

The key point is that I do not have any model and I do not want to create a model with the data from json.

I just want to create the queryset.

existence = 1
try:
      offer_request = requests.get(url, headers=headers)
      existence = 2
except:
      print("nothing")

if existence == 2:
     offers=json.loads(offer_request.text)

The offers variable contains my json.

The json is a list of dictionaries.

For example one item is :

{'yachtId': 16425620217200198, 'yacht': 'Bravo Kiss', 'startBaseId': 1, 'endBaseId': 1, 'startBase': 'Dubrovnik/ACI Marina Dubrovnik', 'endBase': 'Dubrovnik/ACI Marina Dubrovnik', 'dateFrom': '2020-06-02 00:00:00', 'dateTo': '2020-06-03 00:00:00', 'product': 'Bareboat', 'price': 271.0, 'currency': 'EUR', 'startPrice': 271.0, 'discountPercentage': 0.0}

Is it somehow possible from this data to create a queryset with structure based on the keys of the dictionary data in order to feed my template?

Body:
From what I understood, you need to filter your queries based on your JSON. Considering offers have yours JSON, you can use:

MyModel.objects.filter(**offers)


问:
Are dates/times handled differently in the Google Apps Script V8 Runtime?
I recently switched to the V8 Runtime in Google Apps Script and I'm having a strange problem. (Which I can't seem to reproduce in a minimal format.)

My Google Sheet allows users to enter (in cells) a 'work_start' time and a 'work_end' time. For now I have chosen "9:30" and "18:00". With the old Runtime this becomes:

Sat Dec 30 1899 09:30:00 GMT+0009 (Central European Standard Time)

Sat Dec 30 1899 18:00:00 GMT+0009 (Central European Standard Time)

When I switch to the V8 Runtime, however, I get this:

Sat Dec 30 1899 08:39:21 GMT+0009 (Central European Standard Time)

Sat Dec 30 1899 17:09:21 GMT+0009 (Central European Standard Time)

If I run it again immediately, with the old runtime, it goes back to 9:30 and 18:00.

I have checked my code multiple times and I set these values once (as globals) but I never change them. I only use/read them. I even set a breakpoint on the first line of my main function.

I set up a new project and tried to recreate the problem, but for some reason the problem doesn't occur in a new sheet. I have also tried clearing the formatting of those two cells.

Next, I tried one last thing. I moved the code out of the global space and put it in a function, then had a breakpoint on the next line so I could check my variables:

```<code>function Main() {
  var work_start = cal.getRange("G1").getValue(); // work start time
  var work_end = cal.getRange("G2").getValue(); // work end time
  var test = 0; // SET A BREAKPOINT HERE
  ...
}
</code>```

This gives me the same strange results: 8:39:21 and 17:09:21. (Again, only when part of my program. In a new sheet it gives 9:30 and 18:00, as expected.)

Not even sure how to begin to look for an answer to this bug, so any help or guidance will be appreciated.

答:
I could also experience this 50'39'' time difference between the value in the cell and what Apps Script reads. Enabling or disabling V8 didn't make any difference.

This is because Sheets uses the date 1899-12-30 0:00:00 as reference, while Apps Script (and most Google services) uses Unix Time (which starts at 1970-1-1 00:00:00 UTC). Leap seconds are ignored in Unix Time so it could be that.

As a workaround, you can:

Get the values with getDisplayValue instead.

Set the cell format to "plain text".

Body:
I recently switched to the V8 Runtime in Google Apps Script and I'm having a strange problem. (Which I can't seem to reproduce in a minimal format.)

My Google Sheet allows users to enter (in cells) a 'work_start' time and a 'work_end' time. For now I have chosen "9:30" and "18:00". With the old Runtime this becomes:

Sat Dec 30 1899 09:30:00 GMT+0009 (Central European Standard Time)

Sat Dec 30 1899 18:00:00 GMT+0009 (Central European Standard Time)

When I switch to the V8 Runtime, however, I get this:

Sat Dec 30 1899 08:39:21 GMT+0009 (Central European Standard Time)

Sat Dec 30 1899 17:09:21 GMT+0009 (Central European Standard Time)

If I run it again immediately, with the old runtime, it goes back to 9:30 and 18:00.

I have checked my code multiple times and I set these values once (as globals) but I never change them. I only use/read them. I even set a breakpoint on the first line of my main function.

I set up a new project and tried to recreate the problem, but for some reason the problem doesn't occur in a new sheet. I have also tried clearing the formatting of those two cells.

Next, I tried one last thing. I moved the code out of the global space and put it in a function, then had a breakpoint on the next line so I could check my variables:

function Main() {
  var work_start = cal.getRange("G1").getValue(); // work start time
  var work_end = cal.getRange("G2").getValue(); // work end time
  var test = 0; // SET A BREAKPOINT HERE
  ...
}

This gives me the same strange results: 8:39:21 and 17:09:21. (Again, only when part of my program. In a new sheet it gives 9:30 and 18:00, as expected.)

Not even sure how to begin to look for an answer to this bug, so any help or guidance will be appreciated.


问:
Android dependency has different version for the compile and runtime
After updating Android Studio from Canary 3 to Canary 4, the following error is thrown at the build time.

Android dependency 'com.android.support:support-support-v4' has different version for the compile (25.2.0) and runtime (26.0.0-beta2) classpath. You should manually set the same version via DependencyResolution.

I ran a complete search throughout the project and the version 25.1.0 is no where used.

App-build.gradle

```<code>android {
compileSdkVersion 26
buildToolsVersion '26.0.0'

defaultConfig {
    applicationId "com.xxx.xxxx"
    minSdkVersion 14
    targetSdkVersion
    versionCode 1
    versionName "1.0"
    multiDexEnabled true

}

buildTypes {
    debug {
        debuggable true
    }
    release {
        debuggable false
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }

    lintOptions {
        abortOnError false
    }

}}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
testImplementation 'junit:junit:4.12'
implementation project(':core')
implementation com.google.android.gms:play-services-gcm:9.0.0'

implementation('com.crashlytics.sdk.android:crashlytics:2.6.5@aar') {
    transitive = true
}
implementation 'com.android.support:multidex:1.0.1'
implementation 'com.flurry.android:analytics:7.0.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
implementation 'com.jakewharton:butterknife:8.6.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}
</code>```

Library-build.gradle:

```<code>apply plugin: 'com.android.library'
android {
compileSdkVersion 26
buildToolsVersion '26.0.0'

defaultConfig {
    minSdkVersion 14
    targetSdkVersion
    versionCode 1
    versionName "1.0"
}

}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation files('libs/model.jar')
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:percent:26.0.0-beta2'
implementation 'com.android.support:appcompat-v7:26.0.0-beta2'
implementation 'com.android.support:support-core-utils:26.0.0-beta2'

implementation 'com.squareup.retrofit2:retrofit:2.0.2'
implementation 'com.squareup.picasso:picasso:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'com.squareup.okhttp3:logging-interceptor:3.2.0'
implementation 'uk.co.chrisjenx:calligraphy:2.2.0'
implementation 'com.google.code.gson:gson:2.2.4'
implementation 'com.android.support:design:26.0.0-beta2'
implementation 'com.github.PhilJay:MPAndroidChart:v3.0.1'

}
</code>```

Note: Project was building fine in Canary 3

答:
    configurations.all {
        resolutionStrategy.force
        //"com.android.support:appcompat-v7:25.3.1"
        //here put the library that made the error with the version you want to use
    }```

add this to gradle (project) inside allprojects

Body:
After updating Android Studio from Canary 3 to Canary 4, the following error is thrown at the build time.

Android dependency 'com.android.support:support-support-v4' has different version for the compile (25.2.0) and runtime (26.0.0-beta2) classpath. You should manually set the same version via DependencyResolution.

I ran a complete search throughout the project and the version 25.1.0 is no where used.

App-build.gradle

android {
compileSdkVersion 26
buildToolsVersion '26.0.0'

defaultConfig {
    applicationId "com.xxx.xxxx"
    minSdkVersion 14
    targetSdkVersion
    versionCode 1
    versionName "1.0"
    multiDexEnabled true

}

buildTypes {
    debug {
        debuggable true
    }
    release {
        debuggable false
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }

    lintOptions {
        abortOnError false
    }

}}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
testImplementation 'junit:junit:4.12'
implementation project(':core')
implementation com.google.android.gms:play-services-gcm:9.0.0'

implementation('com.crashlytics.sdk.android:crashlytics:2.6.5@aar') {
    transitive = true
}
implementation 'com.android.support:multidex:1.0.1'
implementation 'com.flurry.android:analytics:7.0.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
implementation 'com.jakewharton:butterknife:8.6.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}

Library-build.gradle:

apply plugin: 'com.android.library'
android {
compileSdkVersion 26
buildToolsVersion '26.0.0'

defaultConfig {
    minSdkVersion 14
    targetSdkVersion
    versionCode 1
    versionName "1.0"
}

}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation files('libs/model.jar')
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:percent:26.0.0-beta2'
implementation 'com.android.support:appcompat-v7:26.0.0-beta2'
implementation 'com.android.support:support-core-utils:26.0.0-beta2'

implementation 'com.squareup.retrofit2:retrofit:2.0.2'
implementation 'com.squareup.picasso:picasso:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'com.squareup.okhttp3:logging-interceptor:3.2.0'
implementation 'uk.co.chrisjenx:calligraphy:2.2.0'
implementation 'com.google.code.gson:gson:2.2.4'
implementation 'com.android.support:design:26.0.0-beta2'
implementation 'com.github.PhilJay:MPAndroidChart:v3.0.1'

}

Note: Project was building fine in Canary 3

Body:
    configurations.all {
        resolutionStrategy.force
        //"com.android.support:appcompat-v7:25.3.1"
        //here put the library that made the error with the version you want to use
    }

add this to gradle (project) inside allprojects


问:
How to check if a character is in a specific position in a string in Python?
I am making an algorithm for hangman that can guess the word quite well, but it's not working exactly as intended. It's supposed to check the specific positions of characters, but it doesn't really work. For example, I'll use the word aardvark. The first letter it guesses correctly is a, and aardvark contains 3 a's, so the algorithm sees this:

aa_ _ _ a _ _

But when I check the possible words, most of them don't look like this, and the algorithm should instantly be able to solve it, as it's the only word that looks like this.

The program has functions to remove words that contain incorrectly guessed letters, and a function to guess the optimal letter. Both of these functions work perfectly.

This is the part of the code that isn't working, and is supposed to check the position of the letters:

```<code>def narrowdown(guessedword, possible):
    for i in guessedword:
        if i != "_":
            for j in possible:
                k = list(j)
                if k[guessedword.index(i)] != i:
                    possible.remove(j)
</code>```

Here, guessedword is a list version of the letters that the guesser can see, and possible is the list of words that the guessed word can be. The "_" are the blank letters that the guesser can't see.

It repeats this function after every time it has guessed a word.

The problem is that it includes words that definitely aren't eligable. For example, I'll use aardvark again.

When the word looks like this: aa_  _ _ a _ _

And the incorrectly guessed letters are e, i, s and u, it still shows these words:

['aardvark', 'aardwolf', 'abnormal', 'adorably', 'advocacy', 'agaragar', 'agronomy', 'anaconda', 'anaphora', 'approach', 'approval', 'arrogant', 'atombomb']

As I said, aardvark is the only word that fills all those criteria, but the algorithm still takes 3 more guesses to find out which word it is.

Anyone have an idea how to fix this?

答:
Multi-line solution:

```<code>def narrowdown(guessedword, possible):
    res = []
    for w in possible:
        if (len(w) == len(guessedword)) and all((c1 == "_") or (c1 == c2) for c1, c2 in zip(guessedword, w)):
            res.append(w)
    return res

words = ['aardvark', 'aardwolf', 'abnormal', 'adorably', 'advocacy', 'agaragar', 'agronomy', 'anaconda', 'anaphora', 'approach', 'approval', 'arrogant', 'atombomb']
mask = "aa___a__"

print(narrowdown(mask, words))
</code>```

One line solution:

```<code>def narrowdown(gw, p):
    return [w for w in p if (len(w) == len(gw)) and all((c1 == "_") or (c1 == c2) for c1, c2 in zip(gw, w))]

words = ['aardvark', 'aardwolf', 'abnormal', 'adorably', 'advocacy', 'agaragar', 'agronomy', 'anaconda', 'anaphora', 'approach', 'approval', 'arrogant', 'atombomb']
mask = "aa___a__"

print(narrowdown(mask, words))
</code>```

Body:
I am making an algorithm for hangman that can guess the word quite well, but it's not working exactly as intended. It's supposed to check the specific positions of characters, but it doesn't really work. For example, I'll use the word aardvark. The first letter it guesses correctly is a, and aardvark contains 3 a's, so the algorithm sees this:

aa_ _ _ a _ _

But when I check the possible words, most of them don't look like this, and the algorithm should instantly be able to solve it, as it's the only word that looks like this.

The program has functions to remove words that contain incorrectly guessed letters, and a function to guess the optimal letter. Both of these functions work perfectly.

This is the part of the code that isn't working, and is supposed to check the position of the letters:

def narrowdown(guessedword, possible):
    for i in guessedword:
        if i != "_":
            for j in possible:
                k = list(j)
                if k[guessedword.index(i)] != i:
                    possible.remove(j)

Here, guessedword is a list version of the letters that the guesser can see, and possible is the list of words that the guessed word can be. The "_" are the blank letters that the guesser can't see.

It repeats this function after every time it has guessed a word.

The problem is that it includes words that definitely aren't eligable. For example, I'll use aardvark again.

When the word looks like this: aa_  _ _ a _ _

And the incorrectly guessed letters are e, i, s and u, it still shows these words:

['aardvark', 'aardwolf', 'abnormal', 'adorably', 'advocacy', 'agaragar', 'agronomy', 'anaconda', 'anaphora', 'approach', 'approval', 'arrogant', 'atombomb']

As I said, aardvark is the only word that fills all those criteria, but the algorithm still takes 3 more guesses to find out which word it is.

Anyone have an idea how to fix this?

Body:
Multi-line solution:

def narrowdown(guessedword, possible):
    res = []
    for w in possible:
        if (len(w) == len(guessedword)) and all((c1 == "_") or (c1 == c2) for c1, c2 in zip(guessedword, w)):
            res.append(w)
    return res

words = ['aardvark', 'aardwolf', 'abnormal', 'adorably', 'advocacy', 'agaragar', 'agronomy', 'anaconda', 'anaphora', 'approach', 'approval', 'arrogant', 'atombomb']
mask = "aa___a__"

print(narrowdown(mask, words))

One line solution:

def narrowdown(gw, p):
    return [w for w in p if (len(w) == len(gw)) and all((c1 == "_") or (c1 == c2) for c1, c2 in zip(gw, w))]

words = ['aardvark', 'aardwolf', 'abnormal', 'adorably', 'advocacy', 'agaragar', 'agronomy', 'anaconda', 'anaphora', 'approach', 'approval', 'arrogant', 'atombomb']
mask = "aa___a__"

print(narrowdown(mask, words))


问:
Why .click event handler is not updated here?
I am passing a table row to a function which is supposed to update the onclick attribute on an anchor.

Whatever I have tried I am not able to set it to a new value. I can see that it is jQuery selects the anchor. But when I alert before an after, onclick attribute still points to the same value not the 'url' parameter that is provided to the function:

```<code>function modifyTrEditUrl(tr, url) {

           console.log(tr.find('td:eq(6) a')[0]);

           tr.find('td:eq(6) a')
                .attr('onclick', url); // I have tried
                                       //.click(function(e){..}) way too!

           console.log(tr.find('td:eq(6) a')[0]); //still the same value! :(
        }
</code>```

Any advices?

答:
How about using</p>

```<code> tr.find('td:eq(6) a').attr('href', url);
</code>```

Body:
I am passing a table row to a function which is supposed to update the onclick attribute on an anchor.

Whatever I have tried I am not able to set it to a new value. I can see that it is jQuery selects the anchor. But when I alert before an after, onclick attribute still points to the same value not the 'url' parameter that is provided to the function:

function modifyTrEditUrl(tr, url) {

           console.log(tr.find('td:eq(6) a')[0]);

           tr.find('td:eq(6) a')
                .attr('onclick', url); // I have tried
                                       //.click(function(e){..}) way too!

           console.log(tr.find('td:eq(6) a')[0]); //still the same value! :(
        }

Any advices?

Body:
How about using

 tr.find('td:eq(6) a').attr('href', url);


问:
Recursive challenge in JS combining all possible array keys in true | false versions, I attach the input and output
I have found many solutions about all posible combinations between array values but I need something different, I hope you could support me. Basically is to create all posible objects that combine array keys with true|false values, something like this:

Input: (Should return an array of 32 objects, 2exp5, two posible values in 5 keys)

```<code>let properties = ['arm','lens','season','food','size'];
</code>```

Output:

```<code>let combinations = [
  {"arm": "false","lens": "false","season": "false","food": "false","size": "false"}
  {"arm": "false","lens": "false","season": "false","food": "false","size": "true"}
  {"arm": "false","lens": "false","season": "false","food": "true","size": "true"}
  {"arm": "false","lens": "false","season": "true","food": "true","size": "true"}
  {"arm": "false","lens": "true","season": "true","food": "true","size": "true"}
  {"arm": "true","lens": "true","season": "true","food": "true","size": "true"}
  {"arm": "true","lens": "true","season": "true","food": "false","size": "true"}
  {"arm": "true","lens": "true","season": "false","food": "false","size": "true"}
  and so on...
]
</code>```

Thank you so much!

答:
We can build this on two reusable functions, like this:

const crossproduct = (xss) =>
  xss.reduce ((ps, xs) => ps.reduce ((r, p) => [...r, ...(xs.map (x => [...p, x]))], []), [[]])

const mergeAll = xs =>
  Object.assign ({}, ...xs)

const combine = (properties, values) =>
  crossproduct (properties.map (p => values.map (v => ({[p]: v}))))
    .map (mergeAll)

const properties = ['arm', 'lens', 'season', 'food', 'size']
const values = [true, false]

console.log (combine (properties, values))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {min-height: 100% !important; top: 0}</code>```

Our utility functions are:

crossproduct, which takes an array of arrays and finds the cartesian product of them.  For instance,

crossproduct ([['a', 'b', 'c'], [1, 2], ['x', 'y']])
  //=> [["a", 1, "x"], ["a", 1, "y"], ["a", 2, "x"], ["a", 2, "y"],
  //    ["b", 1, "x"], ["b", 1, "y"], ["b", 2, "x"], ["b", 2, "y"],
  //    ["c", 1, "x"], ["c", 1, "y"], ["c", 2, "x"], ["c", 2, "y"]]
```</li>
<li><p>and <strong><code>mergeAll</code></strong>, which combines an array of separate objects into one like this:</p>

<pre class="lang-js prettyprint-override"><code>mergeAll ([{foo: 1}, {bar: 2}, {baz: 3}])
  //=> {foo: 1, bar: 2, baz: 3}
</code>```

This is just a thin wrapper around Object.assign, simply applying it to an array rather than individual objects.

Our main function, combine first creates an array of arrays matching individual property names to values like this:

  [
    [{"arm": true}, {"arm": false}],
    [{"lens": true}, {"lens": false}],
    [{"season": true}, {"season": false}],
    [{"food": true}, {"food": false}],
    [{"size": true}, {"size": false}]
]
```

<p>This is the bit <code>properties.map (p => values.map (v => ({[p]: v})))</code>.  While that could be extracted as a stand-alone function, it doesn't seem to have any other uses, so the decision is simply a matter of code aesthetics.</p>

<p>We call <code>crossproduct</code> on that result, getting this intermediate format:</p>

<pre class="lang-js prettyprint-override"><code>[
  [{"arm": true}, {"lens": true}, {"season": true}, {"food": true}, {"size": true}],
  [{"arm": true}, {"lens": true}, {"season": true}, {"food": true}, {"size": false}],
  [{"arm": true}, {"lens": true}, {"season": true}, {"food": false}, {"size": true}],
  [{"arm": true}, {"lens": true}, {"season": true}, {"food": false}, {"size": false}],
  // ...
  [{"arm": false}, {"lens": false}, {"season": false}, {"food": false}, {"size": false}]
]
</code>```

And finally, we call .map (mergeAll) on that array to get our final format.

Note that if you really have no other use for mergeAll, it's short and can easily be inlined in the main function as .map (xs => Object.assign ({}, ...xs)).  It's a function that I use often and would simply have in handy in my utility toolbox, so I personally wouldn't inline it.  You may feel differently.

Do notice the basic idea here.  We don't try to solve the problem in one go, but rather apply a series of transforms to get to our final format.  This allows us to take advantage of reusable functions for some of those steps.  It's a powerful technique.

Body:
I have found many solutions about all posible combinations between array values but I need something different, I hope you could support me. Basically is to create all posible objects that combine array keys with true|false values, something like this:

Input: (Should return an array of 32 objects, 2exp5, two posible values in 5 keys)

let properties = ['arm','lens','season','food','size'];

Output:

let combinations = [
  {"arm": "false","lens": "false","season": "false","food": "false","size": "false"}
  {"arm": "false","lens": "false","season": "false","food": "false","size": "true"}
  {"arm": "false","lens": "false","season": "false","food": "true","size": "true"}
  {"arm": "false","lens": "false","season": "true","food": "true","size": "true"}
  {"arm": "false","lens": "true","season": "true","food": "true","size": "true"}
  {"arm": "true","lens": "true","season": "true","food": "true","size": "true"}
  {"arm": "true","lens": "true","season": "true","food": "false","size": "true"}
  {"arm": "true","lens": "true","season": "false","food": "false","size": "true"}
  and so on...
]

Thank you so much!

Body:
We can build this on two reusable functions, like this:

const crossproduct = (xss) =>
  xss.reduce ((ps, xs) => ps.reduce ((r, p) => [...r, ...(xs.map (x => [...p, x]))], []), [[]])

const mergeAll = xs =>
  Object.assign ({}, ...xs)

const combine = (properties, values) =>
  crossproduct (properties.map (p => values.map (v => ({[p]: v}))))
    .map (mergeAll)

const properties = ['arm', 'lens', 'season', 'food', 'size']
const values = [true, false]

console.log (combine (properties, values))

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

Our utility functions are:

crossproduct, which takes an array of arrays and finds the cartesian product of them.  For instance,

crossproduct ([['a', 'b', 'c'], [1, 2], ['x', 'y']])
  //=> [["a", 1, "x"], ["a", 1, "y"], ["a", 2, "x"], ["a", 2, "y"],
  //    ["b", 1, "x"], ["b", 1, "y"], ["b", 2, "x"], ["b", 2, "y"],
  //    ["c", 1, "x"], ["c", 1, "y"], ["c", 2, "x"], ["c", 2, "y"]]

and mergeAll, which combines an array of separate objects into one like this:

mergeAll ([{foo: 1}, {bar: 2}, {baz: 3}])
  //=> {foo: 1, bar: 2, baz: 3}

This is just a thin wrapper around Object.assign, simply applying it to an array rather than individual objects.

Our main function, combine first creates an array of arrays matching individual property names to values like this:

  [
    [{"arm": true}, {"arm": false}],
    [{"lens": true}, {"lens": false}],
    [{"season": true}, {"season": false}],
    [{"food": true}, {"food": false}],
    [{"size": true}, {"size": false}]
]

This is the bit properties.map (p => values.map (v => ({[p]: v}))).  While that could be extracted as a stand-alone function, it doesn't seem to have any other uses, so the decision is simply a matter of code aesthetics.

We call crossproduct on that result, getting this intermediate format:

[
  [{"arm": true}, {"lens": true}, {"season": true}, {"food": true}, {"size": true}],
  [{"arm": true}, {"lens": true}, {"season": true}, {"food": true}, {"size": false}],
  [{"arm": true}, {"lens": true}, {"season": true}, {"food": false}, {"size": true}],
  [{"arm": true}, {"lens": true}, {"season": true}, {"food": false}, {"size": false}],
  // ...
  [{"arm": false}, {"lens": false}, {"season": false}, {"food": false}, {"size": false}]
]

And finally, we call .map (mergeAll) on that array to get our final format.

Note that if you really have no other use for mergeAll, it's short and can easily be inlined in the main function as .map (xs => Object.assign ({}, ...xs)).  It's a function that I use often and would simply have in handy in my utility toolbox, so I personally wouldn't inline it.  You may feel differently.

Do notice the basic idea here.  We don't try to solve the problem in one go, but rather apply a series of transforms to get to our final format.  This allows us to take advantage of reusable functions for some of those steps.  It's a powerful technique.


问:
Mark Duplicated Rows & Add Range Numbers for Duplicate Rows, Python 3.6
Data:

```<code>Data = pd.DataFrame([['1', '2', '3', '4'], ['4', '3', '2', '1'], ['1', '2', '3', '4'], ['4', '3', '2', '1'], ['1', '2', '3', '4'], ['3', '5', '2', '6'], ['10', '9', '8', '7'], ['5', '6', '7', '3'], ['10', '9', '8', '7']], columns=['F1', 'F2', 'F3', 'F4'])
</code>```

Marking Duplicate Rows:

```<code>Data['Is_Dup'] = Data[['F1', 'F2', 'F3', 'F4']].duplicated(keep=False).astype(int)
</code>```

Data:

Expected Results: I want to generate extra field called Dup_Ser, here range values needs to add for duplicate rows.

答:
What you want (Dup_Ser column) is provided by cumcount() function within
grouby. But to group duplicated sets of rows together, you need also ngroup()
function.

To sum up, use the following code:

```<code>gr = Data[Data.Is_Dup == 1].groupby(['F1', 'F2', 'F3', 'F4'], sort=False)
Data['gNo'] = gr.ngroup()
Data['Dup_Ser'] = gr.cumcount() + 1
del gr
Data = Data.sort_values('gNo').drop(columns='gNo')
Data.Dup_Ser = Data.Dup_Ser.fillna(0, downcast='infer')
</code>```

Body:
Data:

Data = pd.DataFrame([['1', '2', '3', '4'], ['4', '3', '2', '1'], ['1', '2', '3', '4'], ['4', '3', '2', '1'], ['1', '2', '3', '4'], ['3', '5', '2', '6'], ['10', '9', '8', '7'], ['5', '6', '7', '3'], ['10', '9', '8', '7']], columns=['F1', 'F2', 'F3', 'F4'])

Marking Duplicate Rows:

Data['Is_Dup'] = Data[['F1', 'F2', 'F3', 'F4']].duplicated(keep=False).astype(int)

Data:

Expected Results: I want to generate extra field called Dup_Ser, here range values needs to add for duplicate rows.

Body:
What you want (Dup_Ser column) is provided by cumcount() function within
grouby. But to group duplicated sets of rows together, you need also ngroup()
function.

To sum up, use the following code:

gr = Data[Data.Is_Dup == 1].groupby(['F1', 'F2', 'F3', 'F4'], sort=False)
Data['gNo'] = gr.ngroup()
Data['Dup_Ser'] = gr.cumcount() + 1
del gr
Data = Data.sort_values('gNo').drop(columns='gNo')
Data.Dup_Ser = Data.Dup_Ser.fillna(0, downcast='infer')


问:
Is a core data migration required when changing the Transformer for a Transformable attribute?
After getting the error described at the link below, I have set the Transfomer to NSSecureUnarchiveFromData (it was nil before) for an entity's attribute.

CoreData crash error Xcode 11 Beta, IOS 13 Beta

I am using the transformable type to store an array.

Everything seems to work fine when I update my app, and data is preserved, however, I haven't had to perform any kind of migration. I just made the changes in the same xcdatamodel that I had before.

Why haven't I had to do a migration, or should I have done one and could problems be caused further down the line if I don't do one?

答:
Yes, you need to do migration. Here is some more information for this

Core Data: Rename Attribute without having issues with users and their current data


问:
How do I get the value of a child div
Good day,
I would like to ask how I can get the value from price. Neither of them has a unique id so it makes things hard for a noob like me. Any suggestions? Thanks.</p>

```<code><div class="modal">
    <span class="name">$</span>
    <span class="price">0.04</span>
    <hr style="background: linear-gradient(to right, #ffc82d , #ffff73);">
    <div class="weapon" style="background-image: url('assets/img/free_case_item.png');"></div>
</div>
</code>```

答:
You can try with document.querySelector:

```<code>var price = document.querySelector("div.modal span.price").innerText
</code>```

This matches the first  inside
.

Title: How do I get the value of a child div

Body:
Good day,
I would like to ask how I can get the value from price. Neither of them has a unique id so it makes things hard for a noob like me. Any suggestions? Thanks.

    $
    0.04

Body:
You can try with document.querySelector:

var price = document.querySelector("div.modal span.price").innerText

This matches the first <span class="price"> inside <div class="modal">.


问:
Why is non-existent image working on kubernetes deployment
First I have created two different version of image as below

docker image ls

```<code>REPOSITORY     |    TAG      |    IMAGE ID
isaac88/posts  |    0.0.1    |    xxx
isaac88/posts  |    0.0.5    |    yyy
</code>```

Then I created a kubernetes deployment file as below

posts-depl.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: posts-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: posts
  template:
    metadata:
      labels:
        app: posts
    spec:
      containers:
        - name: posts
          image: isaac88/posts:0.0.1
```

<p>If you noticed, I specified version of image in deployment yaml file. by swapping the version between <code>0.0.1</code> and <code>0.0.5</code> and executed below commands to see the differences</p>

<ol>
<li><code>kubectl apply -f posts-depl.yaml</code></li>
<li><code>kubectl get pods</code></li>
<li><code>kubectl logs xxxxxxxxx</code></li>
</ol>

<p>Everything works fine so far.</p>

<p>Now I've tried to remove <code>0.0.1</code> from the deployment yaml, i'm wondering on how it behaves since I do not have a latest version being tagged to my docker image. I've verified using <code>docker image ls</code></p>

<p>Below is my latest <code>yaml</code></p>

<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: posts-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: posts
  template:
    metadata:
      labels:
        app: posts
    spec:
      containers:
        - name: posts
          image: isaac88/posts
</code>```

After removed the version, I've ran kubectl apply -f posts-depl.yaml and surprisingly it is able to create the deployment successfully, and I went ahead and executed kubectl logs xxxxx on latest pods created, I see the logs which are belongs to version 0.0.1. I don't understand the reason behind

答:
That is because your deployment failed to fetch image with the latest tag
and rolled back to the previous version of the deployment where you have specified tag 0.0.1

Rolling updates are the default strategy to update the running version of your app.

You can read more about it here

Body:
First I have created two different version of image as below

docker image ls

REPOSITORY     |    TAG      |    IMAGE ID
isaac88/posts  |    0.0.1    |    xxx
isaac88/posts  |    0.0.5    |    yyy

Then I created a kubernetes deployment file as below

posts-depl.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: posts-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: posts
  template:
    metadata:
      labels:
        app: posts
    spec:
      containers:
        - name: posts
          image: isaac88/posts:0.0.1

If you noticed, I specified version of image in deployment yaml file. by swapping the version between 0.0.1 and 0.0.5 and executed below commands to see the differences

kubectl apply -f posts-depl.yaml

kubectl get pods

kubectl logs xxxxxxxxx

Everything works fine so far.

Now I've tried to remove 0.0.1 from the deployment yaml, i'm wondering on how it behaves since I do not have a latest version being tagged to my docker image. I've verified using docker image ls

Below is my latest yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: posts-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: posts
  template:
    metadata:
      labels:
        app: posts
    spec:
      containers:
        - name: posts
          image: isaac88/posts

After removed the version, I've ran kubectl apply -f posts-depl.yaml and surprisingly it is able to create the deployment successfully, and I went ahead and executed kubectl logs xxxxx on latest pods created, I see the logs which are belongs to version 0.0.1. I don't understand the reason behind


问:
Selecting items in a listview
I want to select a particular subitem in a row of a listview. For example if the row contains
5 subitems, if I click the 3rd subitem it only gets selected.

I solved the issue successfully

答:
```<code>ListViewItem list;

for(int a=0;a<37;a++)
{
    list=new ListViewItem();
    list.UseItemStyleForSubItems=false;
    list.Text="vinoth";
    list.SubItems.Add("afdsdf");
    list.SubItems.Add("afddfdfdfdsdf");
    list.SubItems.Add("afdsdddsdf");
    listView1.Items.Add(list);
}

private void listView1_Click(object sender, System.EventArgs e)
{
    listView1.SelectedItems[0].SubItems[1].BackColor=Color.Red;
}
</code>```

OwnerDisplayName: karthik

LastEditorDisplayName: karthik

Title: Selecting items in a listview

OwnerDisplayName: Vinoth


问:
Black transparent modal alert on iOS, as seen in several apps
I'm looking for an API for a certain type of modal alert view (iOS), but I'm not entirely sure whether it's home-built or Apple-provided. It looks like a black transparent square, with rounded corners, usually one icon and a label below. For instance, it is used in the iPhone Twitter app. As observed, it only displays information momentarily and is dismissed when a state has changed (like "Loading" or "Posting").

Is there a pre-built API for this or is it custom built? And if possible, when shared publicly, where can I find such a thing?

Any help is greatly appreciated.

Kind regards,

Reinder

答:
MBProgressHUD is what you're looking for:

https://github.com/matej/MBProgressHUD

Apple does not reject applications using MBProgressHUD.


问:
ImportError: No module named pythoncom
I am a newbie (just 1 week) to this Python world. I tried installing django-mssql, but when I tried to import the library (using import sqlserver_ado.dbapi), I got this error message:

```<code>ImportError: No module named pythoncom
</code>```

I tried to look for that library without success.

Can you guys point me in the right direction?

答: Just go to cmd and install pip install pywin32 pythoncom is part of pywin32 for API window extension....

Title: ImportError: No module named pythoncom

Body:
I am a newbie (just 1 week) to this Python world. I tried installing django-mssql, but when I tried to import the library (using import sqlserver_ado.dbapi), I got this error message:

ImportError: No module named pythoncom

I tried to look for that library without success.

Can you guys point me in the right direction?


问:
How to force the refresh of the thumbnail when the window is minimized ? (C# WPF)
In the code of my application, I created a function that minimizes the window then changes the appearance of it.
But as long as the application is minimized, the taskbar thumbnail displays the window as it was before the function was called.

How to force the refresh of the thumbnail when the window is minimized?

Here is the simplified code:

```<code>MyWindow.WindowState = WindowState.Minimized;
MyWindow.Background = Brushes.Blue;
MyWindow.RenderTransform = new ScaleTransform(1, 0.5);
</code>```

答: This is a function of the OS and is not something you can control. At one time Windows did do live updates to the taskbar thumbnail, but removed it for performance reasons.</p>

Body:
In the code of my application, I created a function that minimizes the window then changes the appearance of it.
But as long as the application is minimized, the taskbar thumbnail displays the window as it was before the function was called.

How to force the refresh of the thumbnail when the window is minimized?

Here is the simplified code:

MyWindow.WindowState = WindowState.Minimized;
MyWindow.Background = Brushes.Blue;
MyWindow.RenderTransform = new ScaleTransform(1, 0.5);


问:
Regex expression to fetch correct value in python
I have below repeated pattern of data in a text file(info.txt). I need to read only 5 components from each block

SENDER

RECEIVER

OBJ_CLASS

JOBN_PAR

CONVTAB

```<code>SENDER=DEMO RECEIVER=REC OBJ_CLASS=message
  JOBN_PAR=JOB.NAME "ROLLBACK=NO" "CONVTAB=message_to_convert_document.cfg" "REST=NO"
  EVN_TYPE=USER
  JOB_SEQU=N
  JOB_PRIO=0
  TIME_WINDOW=
  HC_DIRECTION=1
  POP_ENABLE=Y
</code>```

I have written below python code to read the above pattern of data, It reads all the values until 2nd Line and attaches the values to JOBN_PAR and CONVTAB, while I want only value corresponding to the CONVTAB="" and JOBN_PAR="" in my output

```<code>import re
with open("info.txt", "r") as f:
    s = f.read().replace('"','')

field_labels = [
                'SENDER',
                'RECEIVER',
                'OBJ_CLASS',
                'JOBN_PAR',
                'CONVTAB'
                ]

pat = '=(.*)\s*'.join(field_labels) + '=(.*)\s'
pat = re.compile(pat)

print(pat)
data = pat.findall(s)
print(data)
</code>```

Outcome

[('DEMO ', 'REC ', 'message', 'JOB.NAME ROLLBACK=NO ',
  'message_to_convert_document.cfg  REST=NO')]

Expected Output
[('DEMO ', 'REC ', 'message', 'JOB.NAME', 'message_to_convert_document.cfg')]

答:
=(.*)\s will also match blocks that contain whitespace, as long as there is whitespace at the end. Since regex matching is greedy you can't prevent this without explicitly excluding it in the pattern. If you know that the value will never contain whitespace you can use =([^\s]*)\s instead, which will match on text that contains anything but whitespace. This introduces another problem, however, since now the fields are not longer strictly seperated by whitespace, so the regex will not match at all. To solve this, you can replace the \s* that seperates the seperate fields by a \s.*, which still requires whitespace but allows for any characters after that. Thus, the final regex to join on is =([^\s]*)\s.*. This gives the required result:

>>> text = """
...     SENDER=DEMO RECEIVER=REC OBJ_CLASS=message
...       JOBN_PAR=JOB.NAME "ROLLBACK=NO" "CONVTAB=message_to_convert_document.cfg" "REST=NO"
...       EVN_TYPE=USER
...       JOB_SEQU=N
...       JOB_PRIO=0
...       TIME_WINDOW=
...       HC_DIRECTION=1
...       POP_ENABLE=Y
... """.replace('"', '') # replicating the replacement done by the original code
>>> import re
>>> field_labels = [
...                 'SENDER',
...                 'RECEIVER',
...                 'OBJ_CLASS',
...                 'JOBN_PAR',
...                 'CONVTAB'
...                 ]
>>> pat = '=([^\s]*)\s.*'.join(field_labels) + '=([^\s]*)\s'
>>> repat = re.compile(pat)
>>> print(repat.findall(text))
[('DEMO', 'REC', 'message', 'JOB.NAME', 'message_to_convert_document.cfg')]
```

Body:
I have below repeated pattern of data in a text file(info.txt). I need to read only 5 components from each block

SENDER

RECEIVER

OBJ_CLASS

JOBN_PAR

CONVTAB

SENDER=DEMO RECEIVER=REC OBJ_CLASS=message
  JOBN_PAR=JOB.NAME "ROLLBACK=NO" "CONVTAB=message_to_convert_document.cfg" "REST=NO"
  EVN_TYPE=USER
  JOB_SEQU=N
  JOB_PRIO=0
  TIME_WINDOW=
  HC_DIRECTION=1
  POP_ENABLE=Y

I have written below python code to read the above pattern of data, It reads all the values until 2nd Line and attaches the values to JOBN_PAR and CONVTAB, while I want only value corresponding to the CONVTAB="" and JOBN_PAR="" in my output

import re
with open("info.txt", "r") as f:
    s = f.read().replace('"','')

field_labels = [
                'SENDER',
                'RECEIVER',
                'OBJ_CLASS',
                'JOBN_PAR',
                'CONVTAB'
                ]

pat = '=(.*)\s*'.join(field_labels) + '=(.*)\s'
pat = re.compile(pat)

print(pat)
data = pat.findall(s)
print(data)

Outcome

[('DEMO ', 'REC ', 'message', 'JOB.NAME ROLLBACK=NO ',
  'message_to_convert_document.cfg  REST=NO')]

Expected Output
[('DEMO ', 'REC ', 'message', 'JOB.NAME', 'message_to_convert_document.cfg')]


问:
Deselecting ListView Item if already same item selected WPF
I had a ListView collection in WPF.

Let's say items were Apple, Banana, Cherry.

Assume user selected Banana at first.

If again user clicks on Banana the item was still selected.

I want to deselect the item on user click, If the same item was already selected.

答:
Set the SelectionMode to Multiple or handle the PreviewMouseLeftButtonDown event for the ListViewItem containers depending on whether you want to be able to select several items or not:

```<code>private void ListViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    ListViewItem lvi = (ListViewItem)sender;
    if (lvi.IsSelected)
    {
        e.Handled = true;
        lvi.IsSelected = false;
    }
}
</code>```

XAML:

```<code><ListView xmlns:s="clr-namespace:System;assembly=System.Runtime">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <EventSetter Event="PreviewMouseLeftButtonDown"
                         Handler="ListViewItem_PreviewMouseLeftButtonDown" />
        </Style>
    </ListView.ItemContainerStyle>
    <s:String>Apple</s:String>
    <s:String>Banana</s:String>
    <s:String>Cherry</s:String>
</ListView>
</code>```

Body:
Set the SelectionMode to Multiple or handle the PreviewMouseLeftButtonDown event for the ListViewItem containers depending on whether you want to be able to select several items or not:

private void ListViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    ListViewItem lvi = (ListViewItem)sender;
    if (lvi.IsSelected)
    {
        e.Handled = true;
        lvi.IsSelected = false;
    }
}

XAML:

<ListView xmlns:s="clr-namespace:System;assembly=System.Runtime">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <EventSetter Event="PreviewMouseLeftButtonDown"
                         Handler="ListViewItem_PreviewMouseLeftButtonDown" />
        </Style>
    </ListView.ItemContainerStyle>
    <s:String>Apple</s:String>
    <s:String>Banana</s:String>
    <s:String>Cherry</s:String>
</ListView>


问:
Compare the first word of a page title to an array in Javascript
the following code gets the page title, compares it with data in array and outputs me a final value

```<code>var title = (document.title);

//test variables
testarray =["blue","top","110","in stock", "red","down","111","in stock"]

//function
function testfunction(array, variable){
    var varindex = array.indexOf(variable)
    return array[varindex+2]
}
//calling the function
testfunction(testarray, title)

var finalvalue = testfunction(testarray, title);
</code>```

So if my page title is Blue, it gives me the value 110 that is what I need.
It works fine but in this way the only valid title for my page has to be Blue, otherwise it won't work.

I would like to be able to have a longer page title like Blue Shoes .  I tried by adding the following variable at the beginning to get only the title first word

```<code>var fulltitle = (document.title);
var title = fulltitle.split(' ').slice(0,1);
</code>```

but it doesn't work. What is wrong with my code ?
thanks

答:
Few issues here:

When document.title is Blue Shoes and then you do:

```<code>fulltitle.split(' ').slice(0,1)
</code>```

It actually returns an array like ["Blue"]. You need to convert it into text first like:

```<code>var title = fulltitle.split(' ').slice(0,1)[0];
</code>```

Also, the title value returned is in a different case then what you have in the testarray array variable ("Blue" !== "blue"), thus indexOf doesn't work. You need to make title to lower case like:

```<code>var varindex = array.indexOf(variable.toLowerCase())
</code>```

Working Demo:

var fulltitle = "Blue Shoes";
var arr = fulltitle.split(' ').slice(0, 1);
var title = arr && arr.length ? arr[0] : "";

//test variables
testarray = ["blue", "top", "110", "in stock", "red", "down", "111", "in stock"]

//function
function testfunction(array, variable) {
  var varindex = array.indexOf(variable.toLowerCase())
  return array[varindex + 2]
}

//calling the function
var finalvalue = testfunction(testarray, title);

console.log( finalvalue )```

Body:
the following code gets the page title, compares it with data in array and outputs me a final value

var title = (document.title);

//test variables
testarray =["blue","top","110","in stock", "red","down","111","in stock"]

//function
function testfunction(array, variable){
    var varindex = array.indexOf(variable)
    return array[varindex+2]
}
//calling the function
testfunction(testarray, title)

var finalvalue = testfunction(testarray, title);

So if my page title is Blue, it gives me the value 110 that is what I need.
It works fine but in this way the only valid title for my page has to be Blue, otherwise it won't work.

I would like to be able to have a longer page title like Blue Shoes .  I tried by adding the following variable at the beginning to get only the title first word

var fulltitle = (document.title);
var title = fulltitle.split(' ').slice(0,1);

but it doesn't work. What is wrong with my code ?
thanks

Body:
Few issues here:

When document.title is Blue Shoes and then you do:

fulltitle.split(' ').slice(0,1)

It actually returns an array like ["Blue"]. You need to convert it into text first like:

var title = fulltitle.split(' ').slice(0,1)[0];

Also, the title value returned is in a different case then what you have in the testarray array variable ("Blue" !== "blue"), thus indexOf doesn't work. You need to make title to lower case like:

var varindex = array.indexOf(variable.toLowerCase())

Working Demo:

var fulltitle = "Blue Shoes";
var arr = fulltitle.split(' ').slice(0, 1);
var title = arr && arr.length ? arr[0] : "";

//test variables
testarray = ["blue", "top", "110", "in stock", "red", "down", "111", "in stock"]

//function
function testfunction(array, variable) {
  var varindex = array.indexOf(variable.toLowerCase())
  return array[varindex + 2]
}

//calling the function
var finalvalue = testfunction(testarray, title);

console.log( finalvalue )


问:
How to Loop through a ListTile from ListView.builder in flutter

I am trying to display a list tile in flutter based on list of data from cloud firestore. I want the leading icon to change for each tile when the tile is tapped. My problem is whenever I tap any tile, the whole list changes. I want only the tapped tile to change. Here is my code:

```<code> StreamBuilder(
                        stream: Firestore.instance
                            .collection('Recharge_Card')
                            .snapshots(),
                        //print an integer every 2secs, 10 times
                        builder: (context, snapshot) {
                          if (!snapshot.hasData) {
                            return Text("Loading..");
                          }
                          return SizedBox(
                            height: _height / 1.9,
                            child: ListView.builder(
                              // itemExtent: 80.0,
                              itemCount: snapshot.data.documents.length,
                              itemBuilder: (context, index) {
                                DocumentSnapshot myCards =
                                    snapshot.data.documents[index];

                                return Card(
                                  elevation: 20.0,
                                  child: ListTile(
                                    onTap: () {
                                      setState(() {
                                        x = Text('Tapped');
                                      });
                                    },
                                    leading: x,
                                    title: Text(myCards['CardPin']),
                                    trailing: Text(myCards['Value']),
                                  ),
                                );
                              },
                            ),
                          );`
                        },
                      ),
</code>```

答:
Add key to your card and provide the unique value, in your case it is your index</p>

```<code>         Card(
            key: ValueKey(index),
              //....
            )
</code>```

Body:
I am trying to display a list tile in flutter based on list of data from cloud firestore. I want the leading icon to change for each tile when the tile is tapped. My problem is whenever I tap any tile, the whole list changes. I want only the tapped tile to change. Here is my code:

 StreamBuilder(
                        stream: Firestore.instance
                            .collection('Recharge_Card')
                            .snapshots(),
                        //print an integer every 2secs, 10 times
                        builder: (context, snapshot) {
                          if (!snapshot.hasData) {
                            return Text("Loading..");
                          }
                          return SizedBox(
                            height: _height / 1.9,
                            child: ListView.builder(
                              // itemExtent: 80.0,
                              itemCount: snapshot.data.documents.length,
                              itemBuilder: (context, index) {
                                DocumentSnapshot myCards =
                                    snapshot.data.documents[index];

                                return Card(
                                  elevation: 20.0,
                                  child: ListTile(
                                    onTap: () {
                                      setState(() {
                                        x = Text('Tapped');
                                      });
                                    },
                                    leading: x,
                                    title: Text(myCards['CardPin']),
                                    trailing: Text(myCards['Value']),
                                  ),
                                );
                              },
                            ),
                          );`
                        },
                      ),

Body:
Add key to your card and provide the unique value, in your case it is your index

         Card(
            key: ValueKey(index),
              //....
            )


问:
How to add a border to the last angular components (list-group-item) generated with *ngFor
I have a list of nested component generated in a *ngFor loop.
The hierarchy is :
*ngFor categories of products -> *ngFor list of products
The item components have a 1px border, which turns into 2px when there is two close to each other.
I removed the bottom border for all the elements, but i can't manage to getan additional bottom border for the last component. This is what i have so far :

Here is the loop who generate my categories :

    <app-product-category
      *ngFor="let groupOfProduct of productGroups | keyvalue"
      [category]="groupOfProduct.key"
      [products]="groupOfProduct.value">
    </app-product-category>

```

<p>And the loop who generate the items inside the app-product-category component :</p>

<pre class="lang-html prettyprint-override"><code><div class="collapse mb-2" id="collapseProducts{{category}}">
  <app-product-item
    *ngFor="let product of products; index as i; last as isLast"
    [product]="product"
    [index]="i"
    [ngClass]="{'last-child' : isLast}">
  </app-product-item>
</div>
</code>```

And the css:

.list-group-item {
  border-bottom: 0;
}

.last-child>.list-group-item{
  border-bottom: 1px solid black;
}
```

The last component  get the good class, but the border doesn't display. Any idea ?
Thanks a lot !

答:
With ngFor you can get access to whether you're on the last element with.

```<code><div *ngFor="let item of items; last as isLast">
  <p *ngIf="isLast"></p>
</div>
</code>```

Body:
I have a list of nested component generated in a *ngFor loop.
The hierarchy is :
*ngFor categories of products -> *ngFor list of products
The item components have a 1px border, which turns into 2px when there is two close to each other.
I removed the bottom border for all the elements, but i can't manage to getan additional bottom border for the last component. This is what i have so far :

Here is the loop who generate my categories :

    <app-product-category
      *ngFor="let groupOfProduct of productGroups | keyvalue"
      [category]="groupOfProduct.key"
      [products]="groupOfProduct.value">
    </app-product-category>

And the loop who generate the items inside the app-product-category component :

  <app-product-item
    *ngFor="let product of products; index as i; last as isLast"
    [product]="product"
    [index]="i"
    [ngClass]="{'last-child' : isLast}">
  </app-product-item>

And the css:

.list-group-item {
  border-bottom: 0;
}

.last-child>.list-group-item{
  border-bottom: 1px solid black;
}

The last component  get the good class, but the border doesn't display. Any idea ?
Thanks a lot !

Body:
With ngFor you can get access to whether you're on the last element with.

<div *ngFor="let item of items; last as isLast">
  <p *ngIf="isLast"></p>
</div>


问:
Ajax laravel doesn't return single record in console but all data and nothing in html
I'am trying to make search function that user input code of product in textbox and click button to see detail of the product using ajax and laravel.

this is my route

```<code>Route::get('tracking', 'ClientController@show')->name('tracking');
</code>```

and my controller (ClientController)

```<code>public function show(Request $request){
    $no_smu = $request->input('search');
    $tracking = Incoming::where('no_smu', 'like', '%' . $no_smu . '%')->get();
    return response()->json($tracking);
}
</code>```

my form blade

```<code><form class="lockscreen-credentials" id="form">
  <div class="input-group">
    <input type="text" name="no_smu" id="no_smu" class="form-control" placeholder="SMU Number">
    <div class="input-group-append">
      <button type="submit" id="submit" class="btn"><i class="fas fa-arrow-right text-muted"></i></a>
    </div>
  </div>
</form>

<div class="help-block text-center" id="content">
 <!-- data should load here -->
</div>
</code>```

ajax script

```<code>  $(document).ready(function(){
    $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

    $('#submit').on('click', function(e){
      e.preventDefault();
      var no_smu = $('#no_smu').val();
      // alert(no_smu);
      $.ajax({
        type: "GET",
        url: "{{ route('tracking') }}",
        dataType: "json",
        data: {'no_smu' : no_smu},
        success: function(data){
          console.log(data);
          // $('#content').html(data);
        }
      });
    });
  });
</code>```

the problems, it return all data not a single data of input product and if i comment console.log(data) and uncommented $('#content').html(data) it's return nothing.

答:
Make your controller code as below.

```<code>public function show(Request $request){
    $no_smu = $request->input('search');
    $tracking = Incoming::where('no_smu', 'like', '%' . $no_smu . '%')->first();
    return view('traking_data');
}
</code>```

make one new view file under view folder, where you can add HTML to print

traking_data.blade.php

```<code><div>
{{ $tracking->no_smu }}
</div>
</code>```

It'll return HTML in ajax

```<code>$('#content').html(data)
</code>```

Body:
I'am trying to make search function that user input code of product in textbox and click button to see detail of the product using ajax and laravel.

this is my route

Route::get('tracking', 'ClientController@show')->name('tracking');

and my controller (ClientController)

public function show(Request $request){
    $no_smu = $request->input('search');
    $tracking = Incoming::where('no_smu', 'like', '%' . $no_smu . '%')->get();
    return response()->json($tracking);
}

my form blade

<form class="lockscreen-credentials" id="form">

    <input type="text" name="no_smu" id="no_smu" class="form-control" placeholder="SMU Number">

      <button type="submit" id="submit" class="btn">

</form>

ajax script

  $(document).ready(function(){
    $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

    $('#submit').on('click', function(e){
      e.preventDefault();
      var no_smu = $('#no_smu').val();
      // alert(no_smu);
      $.ajax({
        type: "GET",
        url: "{{ route('tracking') }}",
        dataType: "json",
        data: {'no_smu' : no_smu},
        success: function(data){
          console.log(data);
          // $('#content').html(data);
        }
      });
    });
  });

the problems, it return all data not a single data of input product and if i comment console.log(data) and uncommented $('#content').html(data) it's return nothing.

Body:
Make your controller code as below.

public function show(Request $request){
    $no_smu = $request->input('search');
    $tracking = Incoming::where('no_smu', 'like', '%' . $no_smu . '%')->first();
    return view('traking_data');
}

make one new view file under view folder, where you can add HTML to print

traking_data.blade.php

<div>
{{ $tracking->no_smu }}
</div>

It'll return HTML in ajax

$('#content').html(data)


问:
Nothing shows up on console after powering coral dev board
I have been recently trying to flash the google coral dev board.

dmesg | grep ttyUSB [ I get the expected output]
[ 6437.706335] usb 2-13.1: cp210x converter now attached to ttyUSB0
[ 6437.708049] usb 2-13.1: cp210x converter now attached to ttyUSB1

screen /dev/ttyUSB0 115200
Screen goes back (blinking cursor)

But after I power up the dev board, no welcome message or anything comes up on the console, it just remains blank. I am not sure what the issue is. Any help would be highly appreciated. Thank you.

答:
I believe you have reached out to us privately via the coral-support channel and this issue was resolved.
Just wanted to add in for other to reference, this is a rarer issue that we've faced, but we were able to get the board working again after a reflash with an sdcard recovery image.</p>


问:
TCP support in Azure IoT Hub
Azure IoT Hub Supports AMQP, MQTT, HTTP protocols. In order to customize these protocols we have Azure IoT protocol gateway. I can find good samples on MQTT protocol customization. I need some sample codes for TCP based protocol customization using Azure IoT Protocol Gateway.

EDIT (in order to get an answer): what the OP was asking, is an example using the Azure Protocol Gateway to support a proprietary TCP-based protocol. Currently the IoT hub only supports AMQP, MQTT and HTTP. While those protocols actually rely on TCP, the hub doesn't support direct TCP connection without the extra layer of AMQP, MQTT or HTTP.
As explained here, we need a basic example of a custom TCP based protocol.

Imagine a basic device that can only send some proprietary payload through TCP on a given IP address/port: we need an example of a gateway customization that allows this device to send data to the hub.

The current code of the protocol gateway is poorly designed, as it heavily relies on MQTT.

Adding some bounty too.

答:
I know I am late to this conversation. However I have interesting add on or might be a solution for some.

Azure IoT Gateway is now known as Azure IoT Edge, this is clearly mentioned in the following Azure github repo

https://github.com/Azure/iot-edge-modbus.git

On the other hand, Azure IoT Edge supports TCP for some protocols which can be found in the following links

https://learn.microsoft.com/en-us/azure/iot-edge/deploy-modbus-gateway

https://learn.microsoft.com/en-us/azure/iot-edge/iot-edge-as-gateway

Title: TCP support in Azure IoT Hub


问:
How to pop fragment off backstack
I have an activity A, which calls fragment Bf, which calls fragment Cf.  I want Bf to be placed in the backstack when Cf is called so that users can navigate back to it.  However, if a specific button is pressed in Cf, I would like Bf to be removed from the backstack.  Is this possible?

I see that there is a popBackStack() function.  However, I am a little confused on how this would work.  Is it safe to use this function?  Is there any possibility that an activity from a different application would be inserted after Bf on the backstack?

Also, is there any way to alter the savedInstanceState of the fragment on the backstack?

I just can't figure out how to do a robust test on the backstack using the emulator.

答:
Here's example to pop last fragment using BackStackEntry

```<code>val manager = supportFragmentManager
try {
    // get last entry (you can get another if needed)
    val entry = manager.getBackStackEntryAt(manager.backStackEntryCount - 1)
    // you can pop it by name
    manager.popBackStack(entry.name, FragmentManager.POP_BACK_STACK_INCLUSIVE)
    // or pop by id
    manager.popBackStack(entry.id, FragmentManager.POP_BACK_STACK_INCLUSIVE)
} catch (ex: Exception) {
    ex.printStackTrace()
}
</code>```

Title: How to pop fragment off backstack

Body:
Here's example to pop last fragment using BackStackEntry

val manager = supportFragmentManager
try {
    // get last entry (you can get another if needed)
    val entry = manager.getBackStackEntryAt(manager.backStackEntryCount - 1)
    // you can pop it by name
    manager.popBackStack(entry.name, FragmentManager.POP_BACK_STACK_INCLUSIVE)
    // or pop by id
    manager.popBackStack(entry.id, FragmentManager.POP_BACK_STACK_INCLUSIVE)
} catch (ex: Exception) {
    ex.printStackTrace()
}


问:
Read from executable and write back response
I'm starting an executable with

```<code>./test
</code>```

It will then write a text to stdout

```<code>static test: DYNAMIC_VAL
</code>```

The static test is always the same but the value DYNAMIC_VAL changes.
I need to read DYNAMIC_VAL, process it and send back byte hex codes \x12\x34\x56 to the stdin depending on DYNAMIC_VAL.

./test is an executable and the stdin should be performed to the original invocation of test, otherwise the DYNAMIC_VAL would have changed with a new invocation.

Is there a simple way of doing this in bash?

答:
If I'm understanding this question correctly, you want to read a line from your ./test process, and write data back to the same process and repeat until it produces something saying it's done (Or forever)?

One way is to use a coprocess.

Example:

```<code>$ cat test.sh
#!/bin/sh

echo "static test: foo"
read line
echo "static test: bar"
read line
echo "static test: done"

$ cat demo.sh
#!/usr/bin/env bash

coproc ./test.sh
while true; do
    read -r -u "${COPROC[0]}" s t dynamic_val
    case "$dynamic_val" in
        "done")
            echo "Exiting"
            break;;
        *)
            echo "read $dynamic_val"
            printf "\x12\x34\x56\n" >&"${COPROC[1]}";;
    esac
done

$ ./demo.sh
read foo
read bar
Exiting
</code>```

Body:
I'm starting an executable with

./test

It will then write a text to stdout

static test: DYNAMIC_VAL

The static test is always the same but the value DYNAMIC_VAL changes.
I need to read DYNAMIC_VAL, process it and send back byte hex codes \x12\x34\x56 to the stdin depending on DYNAMIC_VAL.

./test is an executable and the stdin should be performed to the original invocation of test, otherwise the DYNAMIC_VAL would have changed with a new invocation.

Is there a simple way of doing this in bash?

Body:
If I'm understanding this question correctly, you want to read a line from your ./test process, and write data back to the same process and repeat until it produces something saying it's done (Or forever)?

One way is to use a coprocess.

Example:

$ cat test.sh
#!/bin/sh

echo "static test: foo"
read line
echo "static test: bar"
read line
echo "static test: done"

$ cat demo.sh
#!/usr/bin/env bash

coproc ./test.sh
while true; do
    read -r -u "${COPROC[0]}" s t dynamic_val
    case "$dynamic_val" in
        "done")
            echo "Exiting"
            break;;
        *)
            echo "read $dynamic_val"
            printf "\x12\x34\x56\n" >&"${COPROC[1]}";;
    esac
done

$ ./demo.sh
read foo
read bar
Exiting


问:
Compare two strings of ints in java
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10? </p>

```<code>String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";
</code>```

答:
Try like this.</p>

```<code>String one = "1 2 3  4 5 ";
String two = " 3 2 1 4 5 ";
Set<String> a = new HashSet<String> (Arrays.asList(one.trim().replaceAll("\\s*"," ").split(" ")));
Set<String> b = new HashSet<String> (Arrays.asList(two.trim().replaceAll("\\s*"," ").split(" ")));
boolean ret = (a.size() == b.size()) && a.containsAll(b);
</code>```

Title: Compare two strings of ints in java

Body:
I have two Strings that contain numbers and I want to see if the second string contains the same numbers as the first String, whether they are in order or not. If it has any number repeating than report false. Is there anyway in java other than using .charAt() because its not working for number after 10?

String one = "1 2 3 4 5 ";
String two = " 3 2 1 4 5 ";
String three = "3 2 1 4 4 ";

Body:
Try like this.

String one = "1 2 3  4 5 ";
String two = " 3 2 1 4 5 ";
Set<String> a = new HashSet<String> (Arrays.asList(one.trim().replaceAll("\\s*"," ").split(" ")));
Set<String> b = new HashSet<String> (Arrays.asList(two.trim().replaceAll("\\s*"," ").split(" ")));
boolean ret = (a.size() == b.size()) && a.containsAll(b);


问:
How to split csv data by value
im in a situation where i have to plot this csv data like below.

```<code>"x1","x2","y"
-0.626453810742332,0.409401839650934,-1
0.183643324222082,1.68887328620405,1
-0.835628612410047,1.58658843344197,-1
</code>```

And the information of the label y should be expressed in the form of color.

I tried coding like this.

```<code>import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("data.csv")

df['x'] = df['x1'] + df['x2']

for value in df['y']:
    if value == 1:
        df['y1'] = df['y']
    else:
        df['y-1'] = df['y']
print(df['y1'])

plt.figure()
plt.scatter(df['x'], df['y1'], c='red')
plt.figure()
plt.scatter(df['x'], df['y-1'], c='blue')
plt.show()
</code>```

but this didn't give me what i wanted.
and i ran print(df['y1']) to see what went wrong and the result is

```<code>0     -1
1      1
2     -1
3      1
4     -1
.
.
.
</code>```

i splitted by value 1 or -1 but still mixed. how can i split this by value 1 or -1?

答:
By equalling df['y1'] to  df['y'], the entire column is copied. Instead, you can do like this:

for value in df['y']:
    if value == 1:
        df['y1'] = value
    else:
        df['y-1'] = value
print(df['y1'])

Title: How to split csv data by value

Body:
im in a situation where i have to plot this csv data like below.

"x1","x2","y"
-0.626453810742332,0.409401839650934,-1
0.183643324222082,1.68887328620405,1
-0.835628612410047,1.58658843344197,-1

And the information of the label y should be expressed in the form of color.

I tried coding like this.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("data.csv")

df['x'] = df['x1'] + df['x2']

for value in df['y']:
    if value == 1:
        df['y1'] = df['y']
    else:
        df['y-1'] = df['y']
print(df['y1'])

plt.figure()
plt.scatter(df['x'], df['y1'], c='red')
plt.figure()
plt.scatter(df['x'], df['y-1'], c='blue')
plt.show()

but this didn't give me what i wanted.
and i ran print(df['y1']) to see what went wrong and the result is

0     -1
1      1
2     -1
3      1
4     -1
.
.
.

i splitted by value 1 or -1 but still mixed. how can i split this by value 1 or -1?


答:
Hello i'm not sure what exactly you're looking for but if you are trying to add a border then its not working then try changing the second part of you css from
this:

```<code>.last-child>.list-group-item{
  border-bottom: 1px solid black;
  }
</code>```

to this:

```<code>.last-child.list-group-item{
   border-bottom: 1px solid black;
  }
</code>```

Title: How to add a border to the last angular components (list-group-item) generated with *ngFor

Body:
Hello i'm not sure what exactly you're looking for but if you are trying to add a border then its not working then try changing the second part of you css from
this:

.last-child>.list-group-item{
  border-bottom: 1px solid black;
  }

to this:

.last-child.list-group-item{
   border-bottom: 1px solid black;
  }


答:
According to your code, your pattern is this:

```<code>'SENDER=(.*)\\s*RECEIVER=(.*)\\s*OBJ_CLASS=(.*)\\s*JOBN_PAR=(.*)\\s*CONVTAB=(.*)\\s'
</code>```

Here you can see that you full match is the whole string up to message_to_convert_document.cfg. For (.*), as ROLLBACK is not in the field list and space is also goes into . it attached with the value of JOBN_PAR

I did some improvement in your code to get the proper output. I went through one by one field.

```<code>import re
with open("in.txt", "r") as f:
    s = f.read().replace('"','')

field_labels = [
                'SENDER',
                'RECEIVER',
                'OBJ_CLASS',
                'JOBN_PAR',
                'CONVTAB'
                ]
pat = '=(.*)\s*'.join(field_labels) + '=(.*)\s'
pat = re.compile(pat)
print(pat)
data = []

for field in field_labels: // it will also get the value if a field is present multiple time
    pat = field + '=([^=\s\n]*)' // added \n here otherwise if you want the value of last one you should not get
    pat = re.compile(pat)
    data += pat.findall(s)

print(data)
</code>```

Title: Regex expression to fetch correct value in python

Body:
I have below repeated pattern of data in a text file(info.txt). I need to read only 5 components from each block

SENDER

RECEIVER

OBJ_CLASS

JOBN_PAR

CONVTAB

SENDER=DEMO RECEIVER=REC OBJ_CLASS=message
  JOBN_PAR=JOB.NAME "ROLLBACK=NO" "CONVTAB=message_to_convert_document.cfg" "REST=NO"
  EVN_TYPE=USER
  JOB_SEQU=N
  JOB_PRIO=0
  TIME_WINDOW=
  HC_DIRECTION=1
  POP_ENABLE=Y

I have written below python code to read the above pattern of data, It reads all the values until 2nd Line and attaches the values to JOBN_PAR and CONVTAB, while I want only value corresponding to the CONVTAB="" and JOBN_PAR="" in my output

import re
with open("info.txt", "r") as f:
    s = f.read().replace('"','')

field_labels = [
                'SENDER',
                'RECEIVER',
                'OBJ_CLASS',
                'JOBN_PAR',
                'CONVTAB'
                ]

pat = '=(.*)\s*'.join(field_labels) + '=(.*)\s'
pat = re.compile(pat)

print(pat)
data = pat.findall(s)
print(data)

Outcome

[('DEMO ', 'REC ', 'message', 'JOB.NAME ROLLBACK=NO ',
  'message_to_convert_document.cfg  REST=NO')]

Expected Output
[('DEMO ', 'REC ', 'message', 'JOB.NAME', 'message_to_convert_document.cfg')]

Body:
According to your code, your pattern is this:

'SENDER=(.*)\\s*RECEIVER=(.*)\\s*OBJ_CLASS=(.*)\\s*JOBN_PAR=(.*)\\s*CONVTAB=(.*)\\s'

Here you can see that you full match is the whole string up to message_to_convert_document.cfg. For (.*), as ROLLBACK is not in the field list and space is also goes into . it attached with the value of JOBN_PAR

I did some improvement in your code to get the proper output. I went through one by one field.

import re
with open("in.txt", "r") as f:
    s = f.read().replace('"','')

field_labels = [
                'SENDER',
                'RECEIVER',
                'OBJ_CLASS',
                'JOBN_PAR',
                'CONVTAB'
                ]
pat = '=(.*)\s*'.join(field_labels) + '=(.*)\s'
pat = re.compile(pat)
print(pat)
data = []

for field in field_labels: // it will also get the value if a field is present multiple time
    pat = field + '=([^=\s\n]*)' // added \n here otherwise if you want the value of last one you should not get
    pat = re.compile(pat)
    data += pat.findall(s)

print(data)


问:
Using FP-Growth algorithm in Python to determine the most frequent pattern
I have used FP-Growth algorithm in python using the mlxtend.frequent_patterns fpgrowth library. I have followed the code that was mentioned in their page and I have generated the rules which I feel are recursive. I have formed a dataframe using those rules. Now I am trying to calculate support and lift using loops but it is taking a lot of time, which I am finding inefficient.

The code I have used are as follows:

```<code>records = []
for i in range(0, 13748):
    records.append([str(df.values[i,j]) for j in range(0, 12)])

patterns = pyfpgrowth. find_frequent_patterns(records, 10)

rules = pyfpgrowth. generate_association_rules(patterns,0.8)

def support_count(rhs):
    count=0
    rhs=set(rhs)
    for j in data_item['Items']:
        j=set(j)
        if(rhs.issubset(j)):
            count=count+1
    return count

rhs_support=[]
for i in df_r['Consequent']:
    a=support_count(i)
    rhs_support.append(a/len(data_item))
</code>```

Is there any other easier way to calculate support and lift using FPGrowth?

答:
These calculations require a lot of computation and can be slow on large data sets.  One of the best ways to solve for this is to simply run as many of these calculations in parallel as you can.  Your local machine may not be sufficient enough to provide the speed you are looking for.

If you have access to cloud computing, I would recommend using pySpark to achieve your goals.  The SparkML library has FPGrowth built in and I have used it to build a production recommendation system that processes millions of transactions with about half a million products and the entire process takes about 20 minutes including all of the metrics you are asking for.  This is of course using a rather large cluster, with about 200 cores total, so your own performance is going to be proportional to the amount of compute you are willing to pay for.

In any case, if you have never tried before, I'd recommend looking into DataBricks on the Azure platform.  You can get a free trial and the code to implement FPGrowth is very simple.

FPGrowth in SparkML

DataBricks

Body:
I have used FP-Growth algorithm in python using the mlxtend.frequent_patterns fpgrowth library. I have followed the code that was mentioned in their page and I have generated the rules which I feel are recursive. I have formed a dataframe using those rules. Now I am trying to calculate support and lift using loops but it is taking a lot of time, which I am finding inefficient.

The code I have used are as follows:

records = []
for i in range(0, 13748):
    records.append([str(df.values[i,j]) for j in range(0, 12)])

patterns = pyfpgrowth. find_frequent_patterns(records, 10)

rules = pyfpgrowth. generate_association_rules(patterns,0.8)

def support_count(rhs):
    count=0
    rhs=set(rhs)
    for j in data_item['Items']:
        j=set(j)
        if(rhs.issubset(j)):
            count=count+1
    return count

rhs_support=[]
for i in df_r['Consequent']:
    a=support_count(i)
    rhs_support.append(a/len(data_item))

Is there any other easier way to calculate support and lift using FPGrowth?


问:
< & <= not working in Python but when debug it opens some other files from root folder
< & <= not working in Python (Pycharm IDE) but when I debug it opens some other files from the JetBrains root folder. I'm a newbie, please help

This is my code:

```<code>j=1
x=1
for j<=100:
   print(x)
</code>```

And this shows when I debug:

```<code>#We must redefine it in Py3k if it's not already there
def execfile(file, glob=None, loc=None):
if glob is None:
    import sys
    glob = sys._getframe().f_back.f_globals
if loc is None:
    loc = glob

# It seems that the best way is using tokenize.open(): http://code.activestate.com/lists/python-dev/131251/
import tokenize
stream = tokenize.open(file)  # @UndefinedVariable
try:
    contents = stream.read()
finally:
    stream.close()

#execute the script (note: it's important to compile first to have the filename set in debug mode)
exec(compile(contents+"\n", file, 'exec'), glob, loc)
</code>```

答:
From what you mentioned, I understood that you want to print 100 times the value of x which is equal to 1.
If that's the case:

```<code>x = 1
for _ in range(100):
   print(x)
</code>```

I used _ as I am ignoring the value of it (not used).

Body:
< & <= not working in Python (Pycharm IDE) but when I debug it opens some other files from the JetBrains root folder. I'm a newbie, please help

This is my code:

j=1
x=1
for j<=100:
   print(x)

And this shows when I debug:

#We must redefine it in Py3k if it's not already there
def execfile(file, glob=None, loc=None):
if glob is None:
    import sys
    glob = sys._getframe().f_back.f_globals
if loc is None:
    loc = glob

# It seems that the best way is using tokenize.open(): http://code.activestate.com/lists/python-dev/131251/
import tokenize
stream = tokenize.open(file)  # @UndefinedVariable
try:
    contents = stream.read()
finally:
    stream.close()

#execute the script (note: it's important to compile first to have the filename set in debug mode)
exec(compile(contents+"\n", file, 'exec'), glob, loc)

Body:
From what you mentioned, I understood that you want to print 100 times the value of x which is equal to 1.
If that's the case:

x = 1
for _ in range(100):
   print(x)

I used _ as I am ignoring the value of it (not used).


答:
Using findIndex() and  startsWith()

var title = 'red title';

//test variables
testarray =["blue","top","110","in stock", "red","down","111","in stock"]

//function
function testfunction(array, variable){
    var varindex = array.findIndex(e => variable.startsWith(e))
    return array[varindex+2]
}
//calling the function
testfunction(testarray, title)

var finalvalue = testfunction(testarray, title);
console.log(finalvalue)```

Title: Compare the first word of a page title to an array in Javascript

Body:
the following code gets the page title, compares it with data in array and outputs me a final value

var title = (document.title);

//test variables
testarray =["blue","top","110","in stock", "red","down","111","in stock"]

//function
function testfunction(array, variable){
    var varindex = array.indexOf(variable)
    return array[varindex+2]
}
//calling the function
testfunction(testarray, title)

var finalvalue = testfunction(testarray, title);

So if my page title is Blue, it gives me the value 110 that is what I need.
It works fine but in this way the only valid title for my page has to be Blue, otherwise it won't work.

I would like to be able to have a longer page title like Blue Shoes .  I tried by adding the following variable at the beginning to get only the title first word

var fulltitle = (document.title);
var title = fulltitle.split(' ').slice(0,1);

but it doesn't work. What is wrong with my code ?
thanks