问:
AG-GRID angular material component not working when using external html template
I am trying to implement an angular material select component in the AG-GRID as per the example described here

However when I click on the cell that should make the select appear, it does not appear and in the console the following error appears:

```<code>core.js:4002 ERROR TypeError: Cannot read property 'element' of undefined
at mat-select.component.ts:37
</code>```

This corresponds to the following method in the MatSelectComponent:

```<code>// dont use afterGuiAttached for post gui events - hook into ngAfterViewInit instead for this
ngAfterViewInit() {
    window.setTimeout(() => {
        this.group.element.nativeElement.focus();
    });
    this.selectFavouriteVegetableBasedOnSelectedIndex();
}
</code>```

This component has been copied exactly from the example given, except that I put the template and styles in their own HTML/SCSS files respectively.

```<code>@Component({
  selector: 'radio-cell',
  template: './mat-select.component.html'
  styles: ['./mat-slect.component.scss']
})
</code>```

However, when I include the HTML template within the component like in the example it works!

```<code>@Component({
  selector: 'radio-cell',
  template: `
  <mat-card>
    <div class="container" #group tabindex="0" (keydown)="onKeyDown($event)">
      <mat-form-field>
        <mat-select panelClass="ag-custom-component-popup" [(ngModel)]="favouriteVegetable">
          <mat-option *ngFor="let vegetable of vegetables" [value]="vegetable">
            {{ vegetable }}
          </mat-option>
        </mat-select>
      </mat-form-field>
    </div>
  </mat-card>
  `,
  styles: ['./mat-slect.component.scss']
})
</code>```

Is there any explaination of this behaviour or way around putting all this HTML into the component?

EDIT 1:
The component includes the 'group' template reference variable in the component like below, so should it not be available to the ngAfterViewInit() method?

```<code>    @ViewChild("group", { read: ViewContainerRef, static: true })
    public group;
</code>```

答: Your error Cannot read property 'element' of undefined comes from the fact that this.group is undefined because angular tries to query it in the template but doesn't find it <div class="container"#grouptabindex="0" (keydown)="onKeyDown($event)">

Body:
I am trying to implement an angular material select component in the AG-GRID as per the example described here

However when I click on the cell that should make the select appear, it does not appear and in the console the following error appears:

core.js:4002 ERROR TypeError: Cannot read property 'element' of undefined
at mat-select.component.ts:37

This corresponds to the following method in the MatSelectComponent:

// dont use afterGuiAttached for post gui events - hook into ngAfterViewInit instead for this
ngAfterViewInit() {
    window.setTimeout(() => {
        this.group.element.nativeElement.focus();
    });
    this.selectFavouriteVegetableBasedOnSelectedIndex();
}

This component has been copied exactly from the example given, except that I put the template and styles in their own HTML/SCSS files respectively.

@Component({
  selector: 'radio-cell',
  template: './mat-select.component.html'
  styles: ['./mat-slect.component.scss']
})

However, when I include the HTML template within the component like in the example it works!

@Component({
  selector: 'radio-cell',
  template: `
  <mat-card>

      <mat-form-field>
        <mat-select panelClass="ag-custom-component-popup" [(ngModel)]="favouriteVegetable">
          <mat-option *ngFor="let vegetable of vegetables" [value]="vegetable">
            {{ vegetable }}
          </mat-option>
        </mat-select>
      </mat-form-field>

  </mat-card>
  `,
  styles: ['./mat-slect.component.scss']
})

Is there any explaination of this behaviour or way around putting all this HTML into the component?

EDIT 1:
The component includes the 'group' template reference variable in the component like below, so should it not be available to the ngAfterViewInit() method?

    @ViewChild("group", { read: ViewContainerRef, static: true })
    public group;


来源: stackexchange

问:
Which is faster? Query to a local table, or a programmed value list in a combobox control
I have a series of combo boxes on a form - and I have connected them to lists of data in the past by using a pass-through query to a sql server, and while this performs well in most cases, many of my users have been accessing the database using a VPN, and the response to populate them seems slow.

I started programming the system to populate a local table from the pass through query on form load - then, used a local query to show results in the proper order.  Once they select the first combo box the second combobox filters from there, to the third, and the fourth (in some cases I have more than 4 too),

All of this is intended so I don't have to connect to the server each time they change selections.  However, I am thinking that having a value list that is hard coded might be faster in performance for the lists that don't change - such as the highest level in the selection hiearchy (think of 3 or 4 comboboxes that effect each other and filter the next ones results).

Does anyone know if using a hardcoded value list in a combobox has a performance gain over a local query to a local table in MS Access?  I am using MS Access 2016 if it helps.

答:
Rather than using tables linked from SQL server, consider using local tables for any values that rarely change, such as countries.

Have the master tables held within SQL server. When changes are needed, update the master table, and then import to your front end before deploying.

This way you will get better speed than from non-local tables, and are able to use these tables within queries and the like. And as the same data is held both within the Access front end and SQL Server back end, you can still create views within SQL server using the same data.

Regards,

ContentLicense: CC BY-SA 4.0


问:
Cycles in family tree software
I am the developer of some family tree software (written in C++ and Qt). I had no problems until one of my customers mailed me a bug report. The problem is that the customer has two children with their own daughter, and, as a result, he can't use my software because of errors.

Those errors are the result of my various assertions and invariants about the family graph being processed (for example, after walking a cycle, the program states that X can't be both father and grandfather of Y).

How can I resolve those errors without removing all data assertions?

答:
A few answers have shown ways to keep the assertions/invariants, but this seems like a misuse of assertions/invariant. Assertions are to make sure something that should be true is true, and invariants are to make sure something that shouldn't change doesn't change.

What you're asserting here is that incestuous relationships don't exist. Clearly they do exist, so your assertion is invalid. You can work around this assertion, but the real bug is in the assertion itself. The assertion should be removed.

ContentLicense: CC BY-SA 3.0

Title: Cycles in family tree software


问:
JS - Compare individual numerical values:
I am evaluating if a condition is met between one numeric value and another, but I don't know how to add individual values.

This example works for me:

```<code>$(document).ready(function(){
  alertone();
});

$(document).on('input','#enviara',alertone);

function alertone() {
  const total = Number($("#enviara").val().replace(".",""));

  if(total >= 52001 && total <= 52006) {
    $("#alerta-melilla,.layer-melilla").show();
  }
  else{
    $("#alerta-melilla,.layer-melilla").hide();
  };
};
</code>```

But between the values 52001 & 52006, I also want to check if the individual values are written:

```<code>52009, 52012, 52019
</code>```

I've tried these snippets, but it doesn't work for me:

```<code>if (total> = 52001 && total <= 52006 && 52009 && 52012 && 52019) { ...
</code>```

```<code>if (total> = 52001 && total <= 52006 || 52009 || 52012 || 52019) { ...
</code>```

What am I doing wrong here?

Thanks in advance!

Thanks @TopWebGhost

```<code>if (total >= 52001 && total <= 52006 || total === 52009 || total === 52012 || total === 52019)
</code>```

:)

答:
Define your other numbers in array and check if total exist in that array:

```<code>const total = 100;
let otherNumbers = [100, 200];

const otherNumbersMatches = otherNumbers.find(num => num === total);

if ((total >= 52001 && total <= 52006) || otherNumbersMatches) {
  // do something
  console.log('Matches')
}
</code>```

Body:
I am evaluating if a condition is met between one numeric value and another, but I don't know how to add individual values.

This example works for me:

$(document).ready(function(){
  alertone();
});

$(document).on('input','#enviara',alertone);

function alertone() {
  const total = Number($("#enviara").val().replace(".",""));

  if(total >= 52001 && total <= 52006) {
    $("#alerta-melilla,.layer-melilla").show();
  }
  else{
    $("#alerta-melilla,.layer-melilla").hide();
  };
};

But between the values 52001 & 52006, I also want to check if the individual values are written:

52009, 52012, 52019

I've tried these snippets, but it doesn't work for me:

if (total> = 52001 && total <= 52006 && 52009 && 52012 && 52019) { ...

if (total> = 52001 && total <= 52006 || 52009 || 52012 || 52019) { ...

What am I doing wrong here?

Thanks in advance!

Thanks @TopWebGhost

if (total >= 52001 && total <= 52006 || total === 52009 || total === 52012 || total === 52019)

:)

Body:
Define your other numbers in array and check if total exist in that array:

const total = 100;
let otherNumbers = [100, 200];

const otherNumbersMatches = otherNumbers.find(num => num === total);

if ((total >= 52001 && total <= 52006) || otherNumbersMatches) {
  // do something
  console.log('Matches')
}


问:
How can you use CaptureStackBackTrace to capture the exception stack, not the calling stack?
I marked up the following code:

```<code>#include "stdafx.h"
#include <process.h>
#include <iostream>
#include <Windows.h>
#include <dbghelp.h>

using namespace std;

#define TRACE_MAX_STACK_FRAMES 1024
#define TRACE_MAX_FUNCTION_NAME_LENGTH 1024

int printStackTrace()
{
    void *stack[TRACE_MAX_STACK_FRAMES];
    HANDLE process = GetCurrentProcess();
    SymInitialize(process, NULL, TRUE);
    WORD numberOfFrames = CaptureStackBackTrace(0, TRACE_MAX_STACK_FRAMES, stack, NULL);
    char buf[sizeof(SYMBOL_INFO)+(TRACE_MAX_FUNCTION_NAME_LENGTH - 1) * sizeof(TCHAR)];
    SYMBOL_INFO* symbol = (SYMBOL_INFO*)buf;
    symbol->MaxNameLen = TRACE_MAX_FUNCTION_NAME_LENGTH;
    symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
    DWORD displacement;
    IMAGEHLP_LINE64 line;
    line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
    for (int i = 0; i < numberOfFrames; i++)
    {
        DWORD64 address = (DWORD64)(stack[i]);
        SymFromAddr(process, address, NULL, symbol);
        if (SymGetLineFromAddr64(process, address, &displacement, &line))
        {
            printf("\tat %s in %s: line: %lu: address: 0x%0X\n", symbol->Name, line.FileName, line.LineNumber, symbol->Address);
        }
        else
        {
            printf("\tSymGetLineFromAddr64 returned error code %lu.\n", GetLastError());
            printf("\tat %s, address 0x%0X.\n", symbol->Name, symbol->Address);
        }
    }
    return 0;
}

void function2()
{
    int a = 0;
    int b = 0;
    throw new exception;
}

void function1()
{
    int a = 0;
    function2();
}

void function0()
{
    function1();
}

static void threadFunction(void *param)
{
    try
    {
        function0();
    }
    catch (...)
    {
        printStackTrace();
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    _beginthread(threadFunction, 0, NULL);
    printf("Press any key to exit.\n");
    cin.get();
    return 0;
}
</code>```

What it does is, it logs a stack trace, but the problem is that the stack trace it logs does not give me the line numbers that I want. I want it to log the line numbers of the places that threw the exception, on and up the call stack, kind of like in C#. But what it actually does right now, is it outputs the following:

```<code>        at printStackTrace in c:\users\<yourusername>\documents\visual studio 2013\pr
ojects\stacktracing\stacktracing\stacktracing.cpp: line: 17: address: 0x10485C0
        at threadFunction in c:\users\<yourusername>\documents\visual studio 2013\pro
jects\stacktracing\stacktracing\stacktracing.cpp: line: 68: address: 0x10457C0
        SymGetLineFromAddr64 returned error code 487.
        at beginthread, address 0xF9431E0.
        SymGetLineFromAddr64 returned error code 487.
        at endthread, address 0xF9433E0.
        SymGetLineFromAddr64 returned error code 487.
        at BaseThreadInitThunk, address 0x7590494F.
        SymGetLineFromAddr64 returned error code 487.
        at RtlInitializeExceptionChain, address 0x7713986A.
        SymGetLineFromAddr64 returned error code 487.
        at RtlInitializeExceptionChain, address 0x7713986A.
</code>```

The problem I am facing, once again, is that line: 68 in this trace corresponds to the line that calls the method printStackTrace();, while I would like it to give me line number 45, which corresponds to the line which throws the exception: throw new exception; and then continue further up the stack.

How can I achieve this sort of behavior and break into this thread exactly when it throws this exception in order to get a proper stack trace?

PS The code above was run for a console application using MSVC++ with unicode enabled on Windows 8.1 x64 machine, with the application being run as a Win32 application in Debug mode.

答:
do you miss the call to below?
SymInitialize(process, NULL, TRUE);
SymSetOptions(SYMOPT_LOAD_LINES);</p>

Body:
I marked up the following code:

#include "stdafx.h"
#include <process.h>
#include <iostream>
#include <Windows.h>
#include <dbghelp.h>

using namespace std;

#define TRACE_MAX_STACK_FRAMES 1024
#define TRACE_MAX_FUNCTION_NAME_LENGTH 1024

int printStackTrace()
{
    void *stack[TRACE_MAX_STACK_FRAMES];
    HANDLE process = GetCurrentProcess();
    SymInitialize(process, NULL, TRUE);
    WORD numberOfFrames = CaptureStackBackTrace(0, TRACE_MAX_STACK_FRAMES, stack, NULL);
    char buf[sizeof(SYMBOL_INFO)+(TRACE_MAX_FUNCTION_NAME_LENGTH - 1) * sizeof(TCHAR)];
    SYMBOL_INFO* symbol = (SYMBOL_INFO*)buf;
    symbol->MaxNameLen = TRACE_MAX_FUNCTION_NAME_LENGTH;
    symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
    DWORD displacement;
    IMAGEHLP_LINE64 line;
    line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
    for (int i = 0; i < numberOfFrames; i++)
    {
        DWORD64 address = (DWORD64)(stack[i]);
        SymFromAddr(process, address, NULL, symbol);
        if (SymGetLineFromAddr64(process, address, &displacement, &line))
        {
            printf("\tat %s in %s: line: %lu: address: 0x%0X\n", symbol->Name, line.FileName, line.LineNumber, symbol->Address);
        }
        else
        {
            printf("\tSymGetLineFromAddr64 returned error code %lu.\n", GetLastError());
            printf("\tat %s, address 0x%0X.\n", symbol->Name, symbol->Address);
        }
    }
    return 0;
}

void function2()
{
    int a = 0;
    int b = 0;
    throw new exception;
}

void function1()
{
    int a = 0;
    function2();
}

void function0()
{
    function1();
}

static void threadFunction(void *param)
{
    try
    {
        function0();
    }
    catch (...)
    {
        printStackTrace();
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    _beginthread(threadFunction, 0, NULL);
    printf("Press any key to exit.\n");
    cin.get();
    return 0;
}

What it does is, it logs a stack trace, but the problem is that the stack trace it logs does not give me the line numbers that I want. I want it to log the line numbers of the places that threw the exception, on and up the call stack, kind of like in C#. But what it actually does right now, is it outputs the following:

        at printStackTrace in c:\users\<yourusername>\documents\visual studio 2013\pr
ojects\stacktracing\stacktracing\stacktracing.cpp: line: 17: address: 0x10485C0
        at threadFunction in c:\users\<yourusername>\documents\visual studio 2013\pro
jects\stacktracing\stacktracing\stacktracing.cpp: line: 68: address: 0x10457C0
        SymGetLineFromAddr64 returned error code 487.
        at beginthread, address 0xF9431E0.
        SymGetLineFromAddr64 returned error code 487.
        at endthread, address 0xF9433E0.
        SymGetLineFromAddr64 returned error code 487.
        at BaseThreadInitThunk, address 0x7590494F.
        SymGetLineFromAddr64 returned error code 487.
        at RtlInitializeExceptionChain, address 0x7713986A.
        SymGetLineFromAddr64 returned error code 487.
        at RtlInitializeExceptionChain, address 0x7713986A.

The problem I am facing, once again, is that line: 68 in this trace corresponds to the line that calls the method printStackTrace();, while I would like it to give me line number 45, which corresponds to the line which throws the exception: throw new exception; and then continue further up the stack.

How can I achieve this sort of behavior and break into this thread exactly when it throws this exception in order to get a proper stack trace?

PS The code above was run for a console application using MSVC++ with unicode enabled on Windows 8.1 x64 machine, with the application being run as a Win32 application in Debug mode.


问:
Angular 9: passing param from url together a form params
I need to pass a url param to backend together form params. I get the token params from URL like this:

```<code>private initForm(): void {
    this.route.queryParams.subscribe(params => {
      const token = params['token']; // get the token from url
      console.log(token)
    });

    this.formGroup = this.formBuilder.group({
      password: ['', Validators.required],
      password_confirmation: ['', Validators.required],
      reminder: ['', Validators.required]
    });
  }
</code>```

On my onSubmit method, I have it:

```<code>public onSubmit(event: any): void {

    if (this.formGroup.invalid) {
      return this.formGroup.markAllAsTouched();
    }

    const { password, password_confirmation, reminder } = this.formGroup.value;

    const subscription = this.updatePasswordComponentService
      .updatePassword(password, password_confirmation, reminder)
      .subscribe(result => {
        console.log(result);
        subscription.unsubscribe();
      });
  }
</code>```

The updatePassword method

```<code>public updatePassword(password: string, password_confirmation: string, reminder: string): Observable<any> {
    return this.httpClient.post(url, {
      password, password_confirmation, reminder
    });
  }
</code>```

I need to pass params like that:

```<code>public updatePassword(password: string, password_confirmation: string, reminder: string, token: string): Observable<any> {
    return this.httpClient.post(url, {
      password, password_confirmation, reminder, token
    });
  }
</code>```

How can I include the token together password, password_confirmation and reminder params?

答:
You always can get queryParams from route snapshot like this

```<code>this.updatePasswordComponentService.updatePassword(
    password,
    password_confirmation,
    reminder,
    this.route.snapshot.queryParams.token)
</code>```

and pass it as request body

Body:
I need to pass a url param to backend together form params. I get the token params from URL like this:

private initForm(): void {
    this.route.queryParams.subscribe(params => {
      const token = params['token']; // get the token from url
      console.log(token)
    });

    this.formGroup = this.formBuilder.group({
      password: ['', Validators.required],
      password_confirmation: ['', Validators.required],
      reminder: ['', Validators.required]
    });
  }

On my onSubmit method, I have it:

public onSubmit(event: any): void {

    if (this.formGroup.invalid) {
      return this.formGroup.markAllAsTouched();
    }

    const { password, password_confirmation, reminder } = this.formGroup.value;

    const subscription = this.updatePasswordComponentService
      .updatePassword(password, password_confirmation, reminder)
      .subscribe(result => {
        console.log(result);
        subscription.unsubscribe();
      });
  }

The updatePassword method

public updatePassword(password: string, password_confirmation: string, reminder: string): Observable<any> {
    return this.httpClient.post(url, {
      password, password_confirmation, reminder
    });
  }

I need to pass params like that:

public updatePassword(password: string, password_confirmation: string, reminder: string, token: string): Observable<any> {
    return this.httpClient.post(url, {
      password, password_confirmation, reminder, token
    });
  }

How can I include the token together password, password_confirmation and reminder params?

Body:
You always can get queryParams from route snapshot like this

this.updatePasswordComponentService.updatePassword(
    password,
    password_confirmation,
    reminder,
    this.route.snapshot.queryParams.token)

and pass it as request body


问:
Error while trying to install website builder app on odoo 8
I was able to install that website builder app before, but it was long ago. And when I try to install it again, it gives me this error </p>

```<code>ParseError: "insert or update on table "website" violates foreign key constraint "website_user_id_fkey"
DETAIL:  Key (user_id)=(3) is not present in table "res_users"
</code>```

<p>Please let me know if I need to post the full error log. Thank you. </p>

答:
Had this error many times, the only way I was able to bypass the error was to delete the record causing the error.

The error message is pretty straight forward, there is a record in website module with user_id=3, while there is no user in res_users with the id 3. try to look up the record with user_id=3 in website and delete it.

Body:
I was able to install that website builder app before, but it was long ago. And when I try to install it again, it gives me this error

ParseError: "insert or update on table "website" violates foreign key constraint "website_user_id_fkey"
DETAIL:  Key (user_id)=(3) is not present in table "res_users"

Please let me know if I need to post the full error log. Thank you.


问:
Replace specific chinese words in every row of a Dataframe
I'm trying to split a long string of Chinese characters but when I try to replace the "headers" of each column, python does not make the replacement:</p>

```<code>data= pd.DataFrame({'DETAILS': ['厂名: 进口地扪玉米粒 厂址: 进口地扪玉米粒 厂家联系方式: 02081977626 配料.', '厂名: Hill View Packing Co. 厂址: 美国地们 厂家联系方式: 0', '厂名: 5 厂址: 5 厂家联系方式: 5 配料表: 5 储藏方法: 常温 保质期']
                       })
data.DETAILS.replace(['厂名:','厂址:'],'$',inplace=True)
</code>```

答:
Let us try adding regex=True,
From the document :

to_replacestr, regex, list, dict, Series, int, float, or None

```<code>data.DETAILS=data.DETAILS.replace(['厂名:','厂址:'],'$',regex=True)
Out[495]:
0    $ 进口地扪玉米粒 $ 进口地扪玉米粒 厂家联系方式: 02081977626 配料.
1       $ Hill View Packing Co. $ 美国地们 厂家联系方式: 0
2          $ 5 $ 5 厂家联系方式: 5 配料表: 5 储藏方法: 常温 保质期
Name: DETAILS, dtype: object
</code>```

Body:
I'm trying to split a long string of Chinese characters but when I try to replace the "headers" of each column, python does not make the replacement:

data= pd.DataFrame({'DETAILS': ['厂名: 进口地扪玉米粒 厂址: 进口地扪玉米粒 厂家联系方式: 02081977626 配料.', '厂名: Hill View Packing Co. 厂址: 美国地们 厂家联系方式: 0', '厂名: 5 厂址: 5 厂家联系方式: 5 配料表: 5 储藏方法: 常温 保质期']
                       })
data.DETAILS.replace(['厂名:','厂址:'],'$',inplace=True)

Body:
Let us try adding regex=True,
From the document :

to_replacestr, regex, list, dict, Series, int, float, or None

data.DETAILS=data.DETAILS.replace(['厂名:','厂址:'],'$',regex=True)
Out[495]:
0    $ 进口地扪玉米粒 $ 进口地扪玉米粒 厂家联系方式: 02081977626 配料.
1       $ Hill View Packing Co. $ 美国地们 厂家联系方式: 0
2          $ 5 $ 5 厂家联系方式: 5 配料表: 5 储藏方法: 常温 保质期
Name: DETAILS, dtype: object


问:
read specific range of index from char buffer in fprinft using format specifiers in C
I will try to describe by problem and solution that I have as of now in detail. The solution I currently have is not optimal and I want to make it better.

Note: char inputline[1024] has no specific format, it can have strings of any format. The char inputline[1024] reads lines one by one from a file with thousands of lines. So that is why optimization is very important for me.

```<code>FILE *outfile = fopen("tests.txt", "w");
int start_index = 1; //index from where I want to write the characters from the inputline array to the file
int prev_index = start_index; //keep track of last character position written to file

char inputline[1024] = {"12044 This is the test String 2019 to 2025 is another test& and 2050"};
int loop_count = 6; // This can vary as I have just hardcoded a value here for testing
int i;
for(i=0; i<loop_count; ++i)
{
    fprintf(outfile, "%c", inputline[prev_index + i]);
}
prev_index = prev_index + loop_count;// this keeps track of last position of character written to file at end
</code>```

```<code>Sample input in char inputline[1024] = {"This is my day in 2020 1230023"}

Desired output in tests.txt: (for loop will loop 6 times as loop_count is 6)
his is
</code>```

The issue is that I am reading "%c" and this is not very optimal and I want to use %s instead. But I am not able to understand how can I convert the fprintf(outfile, "%c", inputline[prev_index + i]); to use "%s" by specifying the prev_index + i in format specifier when writing to file as I only want to have the characters from inputline[prev_index + i] based on the loop to be written to the file.

答:
You can use the format specifier %.*s and pass in a length

https://ideone.com/UdC3aH

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

int main(void) {
    int start_index = 1;
    int length = 6;
    char inputline[] = "This is my day in 2020 1230023";

    printf("%.*s\n", length, inputline + start_index); //  you can use fprintf(outfile, "%.*s", length, inputline + start_index); here
    return 0;
}
</code>```

Output:

his is

Alternatively you could use strncpy() to make a substring and use that:

https://ideone.com/oyRJuG

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

int main(void) {
    int start_index = 1;
    int loop_count = 6;
    char inputline[] = "This is my day in 2020 1230023";
    char substr[1024];

    strncpy ( substr, inputline + start_index, loop_count);
    substr[loop_count] = '\0';
    printf("%s\n", substr); //  you can use fprintf(outfile, "%s", substr); here
    return 0;
}
</code>```

Note that you have to #include <string.h> in your code

Output:

his is

Body:
I will try to describe by problem and solution that I have as of now in detail. The solution I currently have is not optimal and I want to make it better.

Note: char inputline[1024] has no specific format, it can have strings of any format. The char inputline[1024] reads lines one by one from a file with thousands of lines. So that is why optimization is very important for me.

FILE *outfile = fopen("tests.txt", "w");
int start_index = 1; //index from where I want to write the characters from the inputline array to the file
int prev_index = start_index; //keep track of last character position written to file

char inputline[1024] = {"12044 This is the test String 2019 to 2025 is another test& and 2050"};
int loop_count = 6; // This can vary as I have just hardcoded a value here for testing
int i;
for(i=0; i<loop_count; ++i)
{
    fprintf(outfile, "%c", inputline[prev_index + i]);
}
prev_index = prev_index + loop_count;// this keeps track of last position of character written to file at end

Sample input in char inputline[1024] = {"This is my day in 2020 1230023"}

Desired output in tests.txt: (for loop will loop 6 times as loop_count is 6)
his is

The issue is that I am reading "%c" and this is not very optimal and I want to use %s instead. But I am not able to understand how can I convert the fprintf(outfile, "%c", inputline[prev_index + i]); to use "%s" by specifying the prev_index + i in format specifier when writing to file as I only want to have the characters from inputline[prev_index + i] based on the loop to be written to the file.

Body:
You can use the format specifier %.*s and pass in a length

https://ideone.com/UdC3aH

#include <stdio.h>

int main(void) {
    int start_index = 1;
    int length = 6;
    char inputline[] = "This is my day in 2020 1230023";

    printf("%.*s\n", length, inputline + start_index); //  you can use fprintf(outfile, "%.*s", length, inputline + start_index); here
    return 0;
}

Output:

his is

Alternatively you could use strncpy() to make a substring and use that:

https://ideone.com/oyRJuG

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

int main(void) {
    int start_index = 1;
    int loop_count = 6;
    char inputline[] = "This is my day in 2020 1230023";
    char substr[1024];

    strncpy ( substr, inputline + start_index, loop_count);
    substr[loop_count] = '\0';
    printf("%s\n", substr); //  you can use fprintf(outfile, "%s", substr); here
    return 0;
}

Note that you have to #include <string.h> in your code

Output:

his is


问:
I get the following error when running npm build
<pre class="lang-json prettyprint-override"><code>{
    "name": "confusion",
    "version": "1.0.0",
    "main": "index.js",
    "dependencies": {
        "bootstrap-social": "^5.1.1",
        "font-awesome": "^4.7.0",
        "jquery": "^3.3.1",
        "lite-server": "^2.4.0",
        "popper.js": "^1.12.9"
    },
    "devDependencies": {
        "cssmin": "^0.4.3",
        "htmlmin": "0.0.7",
        "node-sass": "^4.7.2",
        "onchange": "^3.3.0",
        "parallelshell": "^3.0.2",
        "rimraf": "^2.6.2",
        "uglifyjs": "^2.4.11",
        "usemin-cli": "^0.5.1"
    },
    "scripts": {
        "start": "npm run watch:all",
        "test": "echo \"Error: no test specified\" && exit 1",
        "lite": "lite-server",
        "scss": "node-sass -o css/ css/",
        "watch:scss": "onchange \"css/*.scss\" -- npm run scss",
        "watch:all": "parallelshell \"npm run watch:scss\" \"npm run lite\"",
        "clean": "rimraf dist",
        "copyfonts": "copyfiles -f node_modules/font-awesome/fonts/* dist/fonts",
        "imagemin": "imagemin img/* -o dist/img",
        "usemin": "usemin contactus.html -d dist --htmlmin -o dist/contactus.html && usemin aboutus.html -d dist --htmlmin -o dist/aboutus.html && usemin index.html -d dist --htmlmin -o dist/index.html",
        "build": "npm run clean && npm run imagemin && npm run copyfonts && npm run usemin"
    }
}

C:\Users\username\Documents\coursera\Bootstrap4\conFusion>npm run build

> confusion@1.0.0 build C:\Users\username\Documents\coursera\Bootstrap4\conFusion
> npm run clean && npm run imagemin && npm run copyfonts && npm run usemin

> confusion@1.0.0 clean C:\Users\username\Documents\coursera\Bootstrap4\conFusion
> rimraf dist

> confusion@1.0.0 imagemin C:\Users\username\Documents\coursera\Bootstrap4\conFusion
> imagemin img/* -o dist/img

4 images minified

> confusion@1.0.0 copyfonts C:\Users\username\Documents\coursera\Bootstrap4\conFusion
> copyfiles -f node_modules/font-awesome/fonts/* dist/fonts

> confusion@1.0.0 usemin C:\Users\username\Documents\coursera\Bootstrap4\conFusion
> usemin contactus.html -d dist --htmlmin -o dist/contactus.html && usemin aboutus.html -d dist --htmlmin -o dist/aboutus.html && usemin index.html -d dist --htmlmin -o dist/index.html

undefined:1625
    throw new JS_Parse_Error(message, filename, line, col, pos);
    ^
SyntaxError: Unexpected token: punc ({)
    at JS_Parse_Error.get (eval at <anonymous> (C:\Users\username\Documents\coursera\Bootstrap4\conFusion\node_modules\usemin\node_modules\uglify-js\tools\node.js:27:1), <anonymous>:86:23)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! confusion@1.0.0 usemin: `usemin contactus.html -d dist --htmlmin -o dist/contactus.html && usemin aboutus.html -d dist --htmlmin -o dist/aboutus.html && usemin index.html -d dist --htmlmin -o dist/index.html`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the confusion@1.0.0 usemin script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\username\AppData\Roaming\npm-cache\_logs\2018-09-24T21_38_01_183Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! confusion@1.0.0 build: `npm run clean && npm run imagemin && npm run copyfonts && npm run usemin`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the confusion@1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code>```

答:
I stuck to that error too for the same course task.
I was just able to fix it by only reinstalling usemin-cli, cssmin, uglify-js and htmlmin dev dependencies by the current versions without specify any by :

```<code>sudo npm install --save-dev usemin-cli cssmin uglify-js htmlmin
</code>```

then

```<code>npm run build
</code>```

then I found all the files including html which make the usemin problems inside dist folder.

Body:
I stuck to that error too for the same course task.
I was just able to fix it by only reinstalling usemin-cli, cssmin, uglify-js and htmlmin dev dependencies by the current versions without specify any by :

sudo npm install --save-dev usemin-cli cssmin uglify-js htmlmin

then

npm run build

then I found all the files including html which make the usemin problems inside dist folder.


问:
mutate date to create a column for all time less than a timestamp
I have some data which looks something like this:

```<code># A tibble: 754 x 2
   time                 v1
   <dttm>              <dbl>
 1 2020-04-16 09:45:00  175.
 2 2020-04-16 10:00:00  174.
 3 2020-04-16 10:15:00  174.
 4 2020-04-16 10:30:00  173.
 5 2020-04-16 10:45:00  174.
</code>```

I want to group_by a variable day from the lubridate package and apply an ifelse statement.

```<code>df %>%
  mutate(
    day = day(time)
    ) %>%
  group_by(day) %>%
  mutate(
    lessThanTenThirty = ifelse(time < "10:30", 1, 0)
  )
</code>```

So the expected output would have a 1 for all time (across all days) when the data is less than 10:30 and a 0 for all time after.

Data:

```<code>    df <- structure(list(time = structure(c(1587030300, 1587031200, 1587032100,
1587033000, 1587033900, 1587116700, 1587117600, 1587118500, 1587119400,
1587120300), tzone = "UTC", class = c("POSIXct", "POSIXt")),
    v1 = c(174.52, 174.25, 173.69, 173.07, 174.015, 179.578,
    178.41, 178.42, 178.98, 178.6)), row.names = c(NA, -10L), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

Body:
I have some data which looks something like this:

# A tibble: 754 x 2
   time                 v1
   <dttm>              <dbl>
 1 2020-04-16 09:45:00  175.
 2 2020-04-16 10:00:00  174.
 3 2020-04-16 10:15:00  174.
 4 2020-04-16 10:30:00  173.
 5 2020-04-16 10:45:00  174.

I want to group_by a variable day from the lubridate package and apply an ifelse statement.

df %>%
  mutate(
    day = day(time)
    ) %>%
  group_by(day) %>%
  mutate(
    lessThanTenThirty = ifelse(time < "10:30", 1, 0)
  )

So the expected output would have a 1 for all time (across all days) when the data is less than 10:30 and a 0 for all time after.

Data:

    df <- structure(list(time = structure(c(1587030300, 1587031200, 1587032100,
1587033000, 1587033900, 1587116700, 1587117600, 1587118500, 1587119400,
1587120300), tzone = "UTC", class = c("POSIXct", "POSIXt")),
    v1 = c(174.52, 174.25, 173.69, 173.07, 174.015, 179.578,
    178.41, 178.42, 178.98, 178.6)), row.names = c(NA, -10L), class = c("tbl_df",
"tbl", "data.frame"))

Body:
you don't have to group the data. Simply use format to reformat you time:

df %>%
  mutate(lessThanTenThirty = if_else(format(time, '%H:%M') < "10:30", 1, 0))

# A tibble: 754 x 3
   time                   v1 lessThanTenThirty
   <dttm>              <dbl>             <dbl>
 1 2020-04-16 09:45:00  175.                 1
 2 2020-04-16 10:00:00  174.                 1
 3 2020-04-16 10:15:00  174.                 1
 4 2020-04-16 10:30:00  173.                 0
 5 2020-04-16 10:45:00  174.                 0
 6 2020-04-16 11:00:00  175.                 0
 7 2020-04-16 11:15:00  175.                 0
 8 2020-04-16 11:30:00  175.                 0
 9 2020-04-16 11:45:00  176.                 0
10 2020-04-16 12:00:00  176.                 0


问:
Need helping in getting counts out of an array of objects in JavaScript
I'm working with an array of objects that looks something like this:

```<code>const fruits = [
 {
   Fruit: Apple,
   Count: 4
 },
 {
   Fruit: Orange,
   Count: 3
 },
 {
   Fruit: Apple,
   Count: 2
 }
]
</code>```

I like to end up with my array looking something like this:

```<code>const fruits = [
 {
  Fruit: Apple,
  Count: 6
 },
 {
  Fruit: Orange,
  Count: 3
 },
]
</code>```

Is there any help with this? I've tried to use Reduce but Reduce, needless to say, is my biggest weakness in JavaScript. I've looked at so many articles that get a close answer but nothing that can fully help me. Thank you for the help.

答:
const fruits = [{
    Fruit: "Apple",
    Count: 4
  },
  {
    Fruit: "Orange",
    Count: 3
  },
  {
    Fruit: "Apple",
    Count: 2
  }
];

// c => current value
// n => next value
const asObject = fruits.reduce((c, n) => ({ ...c,
  [n.Fruit]: (c[n.Fruit] || 0) + n.Count
}), {});

const result = Object.entries(asObject).map(([k, v]) => ({
  Fruit: k,
  Count: v
}));

console.log(asObject);
console.log(result);```

Body:
I'm working with an array of objects that looks something like this:

const fruits = [
 {
   Fruit: Apple,
   Count: 4
 },
 {
   Fruit: Orange,
   Count: 3
 },
 {
   Fruit: Apple,
   Count: 2
 }
]

I like to end up with my array looking something like this:

const fruits = [
 {
  Fruit: Apple,
  Count: 6
 },
 {
  Fruit: Orange,
  Count: 3
 },
]

Is there any help with this? I've tried to use Reduce but Reduce, needless to say, is my biggest weakness in JavaScript. I've looked at so many articles that get a close answer but nothing that can fully help me. Thank you for the help.


问:
Negative (database dependent) test cases in Spring Cloud Contract
I am writing spring contract for a simple API that receives account number and returns "good" response
if this account exists in the database or "bad" response otherwise. How do i specify "bad" response in the contract if the request that causes "bad" responses has the same format as "good" request?

My Java classes:

```<code>@PostMapping("/postrequest")
public AccountDto postMethod(@RequestBody FindAccountRequest rq){
  return service.findAccountByNumber(rq);
}

public class FindAccountRequest {
    String accountNumber;
}

public class AccountDto {
  Integer balance;
  Integer errorCode;
}
</code>```

Contracts:

```<code>Contract.make {
    request {
        description("Existing account — good response")
        method POST()
        url '/postrequest'
        headers { contentType(applicationJson()) }
        body( [ accountNumber: $( regex('[0-9]{20}') ) ] )
    }
    response {
        status 200
        headers { contentType(applicationJson()) }
        body( [balance: anyInteger()] )
    }
}

Contract.make {
    request {
        description("Nonexistent account — bad response")
        method POST()
        url '/postrequest'
        headers { contentType(applicationJson()) }
        body( [ accountNumber: $( regex('[0-9]{20}') ) ])
    }
    response {
        status 200
        headers { contentType(applicationJson()) }
        body( [errorCode: anyInteger()] )
    }
}
</code>```

Request:

```<code>{
    accountNumber: "12345678901234567890"
}
</code>```

答: Prepare two different account numbers one for the positive case and one for the negative one. Two different contracts </p>

Body:
I am writing spring contract for a simple API that receives account number and returns "good" response
if this account exists in the database or "bad" response otherwise. How do i specify "bad" response in the contract if the request that causes "bad" responses has the same format as "good" request?

My Java classes:

@PostMapping("/postrequest")
public AccountDto postMethod(@RequestBody FindAccountRequest rq){
  return service.findAccountByNumber(rq);
}

public class FindAccountRequest {
    String accountNumber;
}

public class AccountDto {
  Integer balance;
  Integer errorCode;
}

Contracts:

Contract.make {
    request {
        description("Existing account — good response")
        method POST()
        url '/postrequest'
        headers { contentType(applicationJson()) }
        body( [ accountNumber: $( regex('[0-9]{20}') ) ] )
    }
    response {
        status 200
        headers { contentType(applicationJson()) }
        body( [balance: anyInteger()] )
    }
}

Contract.make {
    request {
        description("Nonexistent account — bad response")
        method POST()
        url '/postrequest'
        headers { contentType(applicationJson()) }
        body( [ accountNumber: $( regex('[0-9]{20}') ) ])
    }
    response {
        status 200
        headers { contentType(applicationJson()) }
        body( [errorCode: anyInteger()] )
    }
}

Request:

{
    accountNumber: "12345678901234567890"
}


问:
Some more explanation of Hibernate's merge
I need some clarification on Hibernate merge method. How does it exactly work. When i have an entity that is detached, and I want it to get reatached, does Hibernate look only un current session for same entity, or in all Hibernate sessions?

Is there any way to use merge on transistent entity?

答:
it looks in the current hibernate session only, not all hibernate sessions. </p>

<p>for your second question, you cannot by definition of 'transient' (what i believe you meant, not 'tansistent').  Transient means the entity has not been saved.  Merge means nothing hear.  </p>

Body:
it looks in the current hibernate session only, not all hibernate sessions.

for your second question, you cannot by definition of 'transient' (what i believe you meant, not 'tansistent').  Transient means the entity has not been saved.  Merge means nothing hear.


问:
Undefined name 'context'. Try correcting the name to one that is defined, or defining the name

This is my code but i never change page . Error = Undefined name 'context'.

These are some of them:

Undefined name 'context'
Undefined name 'context' in flutter navigation

```<code>Try correcting the name to one that is defined, or defining the name.

class EntryItem extends StatelessWidget {
const EntryItem(this.entry);

enter code here

final Entry entry;

Widget _buildTiles(Entry root) {
if (root.children.isEmpty)
return ListTile(
title: Text(root.title, style: TextStyle(color: Colors.black)),
trailing: Icon(
Icons.keyboard_arrow_right,
color: Colors.white,
),
onTap: () {
### Navigator.of(context).pushNamedAndRemoveUntil('/gettingStarted', (route) => false)
},
selected: true,
);
return ExpansionTile(
key: PageStorageKey(root),
trailing: Icon(
Icons.keyboard_arrow_right,
),
title: Text(
root.title,
style: TextStyle(color: Color(0xFF2F6CE6)),
),
children: root.children.map(_buildTiles).toList(),
);
}

@override
Widget build(BuildContext context) {
return _buildTiles(entry);
}
}
</code>```

答:
You can pass the context from ListView.builder to EntryItem method when creating it and use it in OnClick to navigate to OtherPage.
    import 'package:flutter/material.dart';</p>

```<code>void main() => runApp(new ExpansionTileSample());

class ExpansionTileSample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('ExpansionTile'),
        ),
        body: new ListView.builder(
          itemBuilder: (BuildContext context, int index) =>
          new EntryItem(data[index], context),
          itemCount: data.length,
        ),
      ),
    );
  }
}

// One entry in the multilevel list displayed by this app.
class Entry {
  Entry(this.title, [this.children = const <Entry>[]]);

  final String title;
  final List<Entry> children;
}

// The entire multilevel list displayed by this app.
final List<Entry> data = <Entry>[
  new Entry(
    'Chapter A',
    <Entry>[
      new Entry(
        'Section A0',
        <Entry>[
          new Entry('Item A0.1'),
          new Entry('Item A0.2'),
          new Entry('Item A0.3'),
        ],
      ),
      new Entry('Section A1'),
      new Entry('Section A2'),
    ],
  ),
  new Entry(
    'Chapter B',
    <Entry>[
      new Entry('Section B0'),
      new Entry('Section B1'),
    ],
  ),
  new Entry(
    'Chapter C',
    <Entry>[
      new Entry('Section C0'),
      new Entry('Section C1'),
      new Entry(
        'Section C2',
        <Entry>[
          new Entry('Item C2.0'),
          new Entry('Item C2.1'),
          new Entry('Item C2.2'),
          new Entry('Item C2.3'),
        ],
      ),
    ],
  ),
];

// Displays one Entry. If the entry has children then it's displayed
// with an ExpansionTile.
class EntryItem extends StatelessWidget {
  const EntryItem(this.entry, this.context);

  final Entry entry;
  final BuildContext context;

  Widget _buildTiles(Entry root) {
    if (root.children.isEmpty) return new ListTile(
        onTap: () { print("I can be tapped but I dont't figure out how to navigate");
        Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
          return new OtherScreen();
        }));
        },
        title: new Text(root.title));
    return new ExpansionTile(
      key: new PageStorageKey<Entry>(root),
      title: new Text(root.title),
      children: root.children.map(_buildTiles).toList(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return _buildTiles(entry);
  }
}
</code>```

Body:
This is my code but i never change page . Error = Undefined name 'context'.

These are some of them:

Undefined name 'context'
Undefined name 'context' in flutter navigation

Try correcting the name to one that is defined, or defining the name.

class EntryItem extends StatelessWidget {
const EntryItem(this.entry);

enter code here

final Entry entry;

Widget _buildTiles(Entry root) {
if (root.children.isEmpty)
return ListTile(
title: Text(root.title, style: TextStyle(color: Colors.black)),
trailing: Icon(
Icons.keyboard_arrow_right,
color: Colors.white,
),
onTap: () {
### Navigator.of(context).pushNamedAndRemoveUntil('/gettingStarted', (route) => false)
},
selected: true,
);
return ExpansionTile(
key: PageStorageKey(root),
trailing: Icon(
Icons.keyboard_arrow_right,
),
title: Text(
root.title,
style: TextStyle(color: Color(0xFF2F6CE6)),
),
children: root.children.map(_buildTiles).toList(),
);
}

@override
Widget build(BuildContext context) {
return _buildTiles(entry);
}
}

Body:
You can pass the context from ListView.builder to EntryItem method when creating it and use it in OnClick to navigate to OtherPage.
    import 'package:flutter/material.dart';

void main() => runApp(new ExpansionTileSample());

class ExpansionTileSample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('ExpansionTile'),
        ),
        body: new ListView.builder(
          itemBuilder: (BuildContext context, int index) =>
          new EntryItem(data[index], context),
          itemCount: data.length,
        ),
      ),
    );
  }
}

// One entry in the multilevel list displayed by this app.
class Entry {
  Entry(this.title, [this.children = const <Entry>[]]);

  final String title;
  final List<Entry> children;
}

// The entire multilevel list displayed by this app.
final List<Entry> data = <Entry>[
  new Entry(
    'Chapter A',
    <Entry>[
      new Entry(
        'Section A0',
        <Entry>[
          new Entry('Item A0.1'),
          new Entry('Item A0.2'),
          new Entry('Item A0.3'),
        ],
      ),
      new Entry('Section A1'),
      new Entry('Section A2'),
    ],
  ),
  new Entry(
    'Chapter B',
    <Entry>[
      new Entry('Section B0'),
      new Entry('Section B1'),
    ],
  ),
  new Entry(
    'Chapter C',
    <Entry>[
      new Entry('Section C0'),
      new Entry('Section C1'),
      new Entry(
        'Section C2',
        <Entry>[
          new Entry('Item C2.0'),
          new Entry('Item C2.1'),
          new Entry('Item C2.2'),
          new Entry('Item C2.3'),
        ],
      ),
    ],
  ),
];

// Displays one Entry. If the entry has children then it's displayed
// with an ExpansionTile.
class EntryItem extends StatelessWidget {
  const EntryItem(this.entry, this.context);

  final Entry entry;
  final BuildContext context;

  Widget _buildTiles(Entry root) {
    if (root.children.isEmpty) return new ListTile(
        onTap: () { print("I can be tapped but I dont't figure out how to navigate");
        Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
          return new OtherScreen();
        }));
        },
        title: new Text(root.title));
    return new ExpansionTile(
      key: new PageStorageKey<Entry>(root),
      title: new Text(root.title),
      children: root.children.map(_buildTiles).toList(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return _buildTiles(entry);
  }
}


问:
Github Probot: why are pinned issues treated as style and marked as wont_fix?
Using Probot on Github and it is configured like this:

```<code>exemptLabels:
  - pinned
  - security
# Label to use when marking an issue as stale
staleLabel: wontfix
...
</code>```

yet Probot marks pinned issue as "stale" (example). The issue does not have an explicit "pinned" label though?

答: Seems this is simply not supported and has caused confusion before: https://github.com/probot/stale/issues/192</p>

Body:
Using Probot on Github and it is configured like this:

exemptLabels:
  - pinned
  - security
# Label to use when marking an issue as stale
staleLabel: wontfix
...

yet Probot marks pinned issue as "stale" (example). The issue does not have an explicit "pinned" label though?


问:
Why does the following snippet of multi-processing code output differently when running multiple times?
Intuitively, the output should always be 15. But sometimes, it generate 11 or 12 or something else. I tried add some delay, but didn't solve the problem.</p>

```<code>from multiprocessing import Pool, Manager
import time

def func(dic, c):
    dic['count'] += c
    # time.sleep(0.1)

if __name__=="__main__":
    d = Manager().dict()    # a manager to enable data sharing b
    d['count'] = 0
    args = [(d,1), (d,2), (d,3), (d,4), (d,5)]
    pool = Pool(5)
    pool.starmap(func, args)
    pool.close()
    pool.join()
    print(f'dic={d}')
</code>```

答:
The increment operator += is not atomic. This means that it is not safe to use in this way. When you invoke this operator the value is read and then replaced by the incremented value. If a second process changes the value between these two operations that change will be will be lost.

See this answer:
Is the += operator thread-safe in Python?

Body:
Intuitively, the output should always be 15. But sometimes, it generate 11 or 12 or something else. I tried add some delay, but didn't solve the problem.

from multiprocessing import Pool, Manager
import time

def func(dic, c):
    dic['count'] += c
    # time.sleep(0.1)

if __name__=="__main__":
    d = Manager().dict()    # a manager to enable data sharing b
    d['count'] = 0
    args = [(d,1), (d,2), (d,3), (d,4), (d,5)]
    pool = Pool(5)
    pool.starmap(func, args)
    pool.close()
    pool.join()
    print(f'dic={d}')


问:
calculating percent change month over month in SQL
i want to query one table to find the sum of charges for a good within the months of Jan - May of 2018 - 2019. i know how to conditionally sum to get the charges broken out by year, but i'm unsure how to also build out a subquery to calculate the month over month change in sums between the years.

here's what my query looks like now:

```<code>    SELECT
    "Month Bought" AS MONTH,
    SUM(
        CASE
            WHEN "Bought Year" = '2018'
            THEN "total charges"
            ELSE 0
        END) AS Charge_2018,
    SUM(
        CASE
            WHEN "Bought Year" = '2019'
            THEN "total charges"
            ELSE 0
        END) AS Charge_2019
FROM
    Sales_agg
WHERE
    "Month Bought" IS NOT NULL
AND "Month Bought" between '1' and '5'
GROUP BY
    "Month Bought"
ORDER BY
    "Month Bought";
</code>```

here's what the output looks like now:

```<code>Month | Charge_2018 | Charge_ 2019
1            5             7
2            7             8
3            7             10
4            6             8
5            5             6
</code>```

here's what i'd like the output to look like:

```<code>Month | Charge_2018 | Charge_ 2019 | Mom_Change
1            5             7            0.XX
2            7             8            0.XX
3            7             10           0.XX
4            6             8            0.XX
5            5             6            0.XX
</code>```

thanks so much for any help!

答:
Then it's this:</p>

```<code>WITH
sales_agg(yr,mth,charge) AS (
          SELECT 2018,  1, 5
UNION ALL SELECT 2018,  2, 7
UNION ALL SELECT 2018,  3, 7
UNION ALL SELECT 2018,  4, 6
UNION ALL SELECT 2018,  5, 5
UNION ALL SELECT 2019,  1, 7
UNION ALL SELECT 2019,  2, 8
UNION ALL SELECT 2019,  3,10
UNION ALL SELECT 2019,  4, 8
UNION ALL SELECT 2019,  5, 6
)
SELECT
  mth
, SUM(CASE yr WHEN 2018 THEN charge END) AS charge_2018
, SUM(CASE yr WHEN 2019 THEN charge END) AS charge_2019
, (
    SUM(CASE yr WHEN 2019 THEN charge END)
  / SUM(CASE yr WHEN 2018 THEN charge END)
  )::NUMERIC(5,3) - 1 AS yoy_change
FROM sales_agg
GROUP BY 1
ORDER BY 1;
-- out Time: First fetch (0 rows): 0.565 ms. All rows formatted: 0.580 ms
-- out  mth | charge_2018 | charge_2019 | yoy_change
-- out -----+-------------+-------------+------------
-- out    1 |           5 |           7 |      0.400
-- out    2 |           7 |           8 |      0.143
-- out    3 |           7 |          10 |      0.429
-- out    4 |           6 |           8 |      0.333
-- out    5 |           5 |           6 |      0.200
</code>```

Body:
i want to query one table to find the sum of charges for a good within the months of Jan - May of 2018 - 2019. i know how to conditionally sum to get the charges broken out by year, but i'm unsure how to also build out a subquery to calculate the month over month change in sums between the years.

here's what my query looks like now:

    SELECT
    "Month Bought" AS MONTH,
    SUM(
        CASE
            WHEN "Bought Year" = '2018'
            THEN "total charges"
            ELSE 0
        END) AS Charge_2018,
    SUM(
        CASE
            WHEN "Bought Year" = '2019'
            THEN "total charges"
            ELSE 0
        END) AS Charge_2019
FROM
    Sales_agg
WHERE
    "Month Bought" IS NOT NULL
AND "Month Bought" between '1' and '5'
GROUP BY
    "Month Bought"
ORDER BY
    "Month Bought";

here's what the output looks like now:

Month | Charge_2018 | Charge_ 2019
1            5             7
2            7             8
3            7             10
4            6             8
5            5             6

here's what i'd like the output to look like:

Month | Charge_2018 | Charge_ 2019 | Mom_Change
1            5             7            0.XX
2            7             8            0.XX
3            7             10           0.XX
4            6             8            0.XX
5            5             6            0.XX

thanks so much for any help!

Body:
Then it's this:

WITH
sales_agg(yr,mth,charge) AS (
          SELECT 2018,  1, 5
UNION ALL SELECT 2018,  2, 7
UNION ALL SELECT 2018,  3, 7
UNION ALL SELECT 2018,  4, 6
UNION ALL SELECT 2018,  5, 5
UNION ALL SELECT 2019,  1, 7
UNION ALL SELECT 2019,  2, 8
UNION ALL SELECT 2019,  3,10
UNION ALL SELECT 2019,  4, 8
UNION ALL SELECT 2019,  5, 6
)
SELECT
  mth
, SUM(CASE yr WHEN 2018 THEN charge END) AS charge_2018
, SUM(CASE yr WHEN 2019 THEN charge END) AS charge_2019
, (
    SUM(CASE yr WHEN 2019 THEN charge END)
  / SUM(CASE yr WHEN 2018 THEN charge END)
  )::NUMERIC(5,3) - 1 AS yoy_change
FROM sales_agg
GROUP BY 1
ORDER BY 1;
-- out Time: First fetch (0 rows): 0.565 ms. All rows formatted: 0.580 ms
-- out  mth | charge_2018 | charge_2019 | yoy_change
-- out -----+-------------+-------------+------------
-- out    1 |           5 |           7 |      0.400
-- out    2 |           7 |           8 |      0.143
-- out    3 |           7 |          10 |      0.429
-- out    4 |           6 |           8 |      0.333
-- out    5 |           5 |           6 |      0.200


问:
gcloud throws PERMISSION_DENIED when I try to deploy endpoint configuration
I am trying to deploy endpoint configuration by command:

```<code>gcloud endpoints services deploy openapi-functions.yaml \
    --project ESP_PROJECT_ID
</code>```

I got an error:

```<code>ERROR: (gcloud.endpoints.services.deploy) PERMISSION_DENIED: Ownership for domain name 'REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net' on project 'PROJECT_ID' cannot be verified.
</code>```

I logged in with command:

```<code>gcloud auth login
</code>```

This is output in terminal after log in:

```<code>Your browser has been opened to visit:

    https://accounts.google.com/o/oauth2/auth?code_challenge=...

You are now logged in as [user@gmail.com].
Your current project is [PROJECT_ID].  You can change this setting by running:
  $ gcloud config set project PROJECT_ID
</code>```

If I run deploy command again, I got the same error message. What's the issue? Why is PERMISSION_DENIED?

openapi-functions.yaml

```<code>swagger: "2.0"
info:
  description: "send email function."
  title: "send-email"
  version: "1.0.0"
host: "REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net"
security:
  - api_key: []
schemes:
  - https
produces:
  - application/json
paths:
  /send-email:
    get:
      summary: Greet a user
      operationId: hello
      x-google-backend:
        address: https://REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net/send-email
        protocol: h2
      responses:
        "200":
          description: A successful response
          schema:
            type: string
securityDefinitions:
  # This section configures basic authentication with an API key.
  api_key:
    type: "apiKey"
    name: "key"
    in: "query"
</code>```

If I run:

```<code>gcloud endpoints services deploy openapi-functions.yaml --project ESP_PROJECT_ID --verbosity='debug'
</code>```

the output is:

```<code>DEBUG: Running [gcloud.endpoints.services.deploy] with arguments: [--project: "PROJECT_ID", --verbosity: "debug", SERVICE_CONFIG_FILE:1: "[u'openapi-functions.yaml']"]
INFO: No JSON detected in service config. Trying YAML...
DEBUG: (gcloud.endpoints.services.deploy) PERMISSION_DENIED: Ownership for domain name 'us-central1-PROJECT_ID.cloudfunctions.net' on project 'PROJECT_ID' cannot be verified.
Traceback (most recent call last):
  File "/dev/google-cloud-sdk/lib/googlecloudsdk/calliope/cli.py", line 983, in Execute
    resources = calliope_command.Run(cli=self, args=args)
  File "/dev/google-cloud-sdk/lib/googlecloudsdk/calliope/backend.py", line 807, in Run
    resources = command_instance.Run(args)
  File "/dev/google-cloud-sdk/lib/surface/endpoints/services/deploy.py", line 350, in Run
    services_util.CreateService(self.service_name, project_id)
  File "/dev/google-cloud-sdk/lib/googlecloudsdk/api_lib/endpoints/services_util.py", line 432, in CreateService
    result = client.services.Create(create_request)
  File "/dev/google-cloud-sdk/lib/googlecloudsdk/third_party/apis/servicemanagement/v1/servicemanagement_v1_client.py", line 657, in Create
    config, request, global_params=global_params)
  File "/dev/google-cloud-sdk/lib/third_party/apitools/base/py/base_api.py", line 731, in _RunMethod
    return self.ProcessHttpResponse(method_config, http_response, request)
  File "/dev/google-cloud-sdk/lib/third_party/apitools/base/py/base_api.py", line 737, in ProcessHttpResponse
    self.__ProcessHttpResponse(method_config, http_response, request))
  File "/dev/google-cloud-sdk/lib/third_party/apitools/base/py/base_api.py", line 604, in __ProcessHttpResponse
    http_response, method_config=method_config, request=request)
HttpForbiddenError: HttpError accessing <https://servicemanagement.googleapis.com/v1/services?alt=json>: response: <{'status': '403', 'content-length': '218', 'x-xss-protection': '0', 'x-content-type-options': 'nosniff', 'transfer-encoding': 'chunked', 'vary': 'Origin, X-Origin, Referer', 'server': 'ESF', '-content-encoding': 'gzip', 'cache-control': 'private', 'date': 'Sun, 31 May 2020 20:41:07 GMT', 'x-frame-options': 'SAMEORIGIN', 'alt-svc': 'h3-27=":443"; ma=2592000,h3-25=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"', 'content-type': 'application/json; charset=UTF-8'}>, content <{
  "error": {
    "code": 403,
    "message": "Ownership for domain name 'us-central1-PROJECT_ID.cloudfunctions.net' on project 'PROJECT_ID' cannot be verified.",
    "status": "PERMISSION_DENIED"
  }
}
</code>```

答:
You are providing the wrong host, the documentation says that the host should be the CLOUD_RUN_HOSTNAME:

In the host field, specify CLOUD_RUN_HOSTNAME, the hostname portion of the URL that Cloud Run created when you deployed ESPv2 Beta above in Deploying ESPv2 Beta. Don't include the protocol identifier, https://

And you are using host: "REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net" instead.

Body:
I am trying to deploy endpoint configuration by command:

gcloud endpoints services deploy openapi-functions.yaml \
    --project ESP_PROJECT_ID

I got an error:

ERROR: (gcloud.endpoints.services.deploy) PERMISSION_DENIED: Ownership for domain name 'REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net' on project 'PROJECT_ID' cannot be verified.

I logged in with command:

gcloud auth login

This is output in terminal after log in:

Your browser has been opened to visit:

    https://accounts.google.com/o/oauth2/auth?code_challenge=...

You are now logged in as [user@gmail.com].
Your current project is [PROJECT_ID].  You can change this setting by running:
  $ gcloud config set project PROJECT_ID

If I run deploy command again, I got the same error message. What's the issue? Why is PERMISSION_DENIED?

openapi-functions.yaml

swagger: "2.0"
info:
  description: "send email function."
  title: "send-email"
  version: "1.0.0"
host: "REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net"
security:
  - api_key: []
schemes:
  - https
produces:
  - application/json
paths:
  /send-email:
    get:
      summary: Greet a user
      operationId: hello
      x-google-backend:
        address: https://REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net/send-email
        protocol: h2
      responses:
        "200":
          description: A successful response
          schema:
            type: string
securityDefinitions:
  # This section configures basic authentication with an API key.
  api_key:
    type: "apiKey"
    name: "key"
    in: "query"

If I run:

gcloud endpoints services deploy openapi-functions.yaml --project ESP_PROJECT_ID --verbosity='debug'

the output is:

DEBUG: Running [gcloud.endpoints.services.deploy] with arguments: [--project: "PROJECT_ID", --verbosity: "debug", SERVICE_CONFIG_FILE:1: "[u'openapi-functions.yaml']"]
INFO: No JSON detected in service config. Trying YAML...
DEBUG: (gcloud.endpoints.services.deploy) PERMISSION_DENIED: Ownership for domain name 'us-central1-PROJECT_ID.cloudfunctions.net' on project 'PROJECT_ID' cannot be verified.
Traceback (most recent call last):
  File "/dev/google-cloud-sdk/lib/googlecloudsdk/calliope/cli.py", line 983, in Execute
    resources = calliope_command.Run(cli=self, args=args)
  File "/dev/google-cloud-sdk/lib/googlecloudsdk/calliope/backend.py", line 807, in Run
    resources = command_instance.Run(args)
  File "/dev/google-cloud-sdk/lib/surface/endpoints/services/deploy.py", line 350, in Run
    services_util.CreateService(self.service_name, project_id)
  File "/dev/google-cloud-sdk/lib/googlecloudsdk/api_lib/endpoints/services_util.py", line 432, in CreateService
    result = client.services.Create(create_request)
  File "/dev/google-cloud-sdk/lib/googlecloudsdk/third_party/apis/servicemanagement/v1/servicemanagement_v1_client.py", line 657, in Create
    config, request, global_params=global_params)
  File "/dev/google-cloud-sdk/lib/third_party/apitools/base/py/base_api.py", line 731, in _RunMethod
    return self.ProcessHttpResponse(method_config, http_response, request)
  File "/dev/google-cloud-sdk/lib/third_party/apitools/base/py/base_api.py", line 737, in ProcessHttpResponse
    self.__ProcessHttpResponse(method_config, http_response, request))
  File "/dev/google-cloud-sdk/lib/third_party/apitools/base/py/base_api.py", line 604, in __ProcessHttpResponse
    http_response, method_config=method_config, request=request)
HttpForbiddenError: HttpError accessing <https://servicemanagement.googleapis.com/v1/services?alt=json>: response: <{'status': '403', 'content-length': '218', 'x-xss-protection': '0', 'x-content-type-options': 'nosniff', 'transfer-encoding': 'chunked', 'vary': 'Origin, X-Origin, Referer', 'server': 'ESF', '-content-encoding': 'gzip', 'cache-control': 'private', 'date': 'Sun, 31 May 2020 20:41:07 GMT', 'x-frame-options': 'SAMEORIGIN', 'alt-svc': 'h3-27=":443"; ma=2592000,h3-25=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"', 'content-type': 'application/json; charset=UTF-8'}>, content <{
  "error": {
    "code": 403,
    "message": "Ownership for domain name 'us-central1-PROJECT_ID.cloudfunctions.net' on project 'PROJECT_ID' cannot be verified.",
    "status": "PERMISSION_DENIED"
  }
}


问:
echoing text field value in a while loop
```<code>echo " <table bgcolor='#d3fcfe'   align='center'>  ";

while ($row = mysql_fetch_array($result)) {

echo '</div> <tr onmouseout="this.bgColor=\'#d3fcfe\';"  onmouseover= "this   .bgColor=\'#fffdcd\';" >  ';
 $numq2=$row['username'] ;

{
echo '<td ><div class="iddiv"> <input name="" type="text" value="$numq2" />   <div>    </td> ';
}

echo '  </table>';
}
</code>```

<p>i want to output $numq2 Var's data into the value of the textfield.but something is wrong with my code.it prinout   the value of textfield as "$numq2".what's wrong with my script? </p>

答:
You are using single quotes around your string.

Anything wrapped in single quotes gets output as is, and does not get parsed.

Double quotes runs your string through the parser and any variables get replaced with their values.

You need to either break out of the single quotes and concatenate your variable as follows:

```<code>echo 'My value ' . $value . ' is the best value';
</code>```

Or you need to wrap your string in double quotes and wrap your variable in { } as follows:

```<code>echo "My value {$value} is the best value";
</code>```

Body:
echo "
  ";

while ($row = mysql_fetch_array($result)) {

echo '

  ';
 $numq2=$row['username'] ;

{
echo '
 <input name="" type="text" value="$numq2" />
    	 ';
}

echo '
';
}

i want to output $numq2 Var's data into the value of the textfield.but something is wrong with my code.it prinout   the value of textfield as "$numq2".what's wrong with my script?

Body:
You are using single quotes around your string.

Anything wrapped in single quotes gets output as is, and does not get parsed.

Double quotes runs your string through the parser and any variables get replaced with their values.

You need to either break out of the single quotes and concatenate your variable as follows:

echo 'My value ' . $value . ' is the best value';

Or you need to wrap your string in double quotes and wrap your variable in { } as follows:

echo "My value {$value} is the best value";


问:
merge multiple table to CSV powershell
Hi there are two tables below

```<code>Computer A
------------
20.03
20.02
20.01
</code>```

```<code>Computer B
------------
20.03
20.02
20.01
XXX
XXX
</code>```

Hi I have a question is I want to merge into a CSV,so I need to achieve first below as :

```<code>Computer A      Computer B
------------    ------------
20.03           20.03
20.02           20.02
20.01           20.01
                XXX
                XXX
</code>```

How can I do?  I have many something like those tables that need to merge
I tried some many time, just can't be able to do that

答:
Start by turning both arrays into hashtables - this way we can quickly lookup whether a value exists in one or both:

```<code>$ComputerATable = @{}
$AObjects |ForEach-Object { $ComputerATable[$_.'Computer A'] = $_ }

$ComputerBTable = @{}
$AObjects |ForEach-Object { $ComputerATable[$_.'Computer B'] = $_ }
</code>```

Now we just need to loop through all distinct computer names to build our "merged table":

$merged = $ComputerATable.Keys,$ComputerBTable.Keys |Sort-Object |ForEach-Object {
  # Create a new object with the value (if present) from either table
  [pscustomobject]@{
    'Computer A' = if($ComputerATable.ContainsKey($_)){ $_ }
    'Computer B' = if($ComputerBTable.ContainsKey($_)){ $_ }
  }
}
```

Title: merge multiple table to CSV powershell

Body:
Hi there are two tables below

Computer A
------------
20.03
20.02
20.01

Computer B
------------
20.03
20.02
20.01
XXX
XXX

Hi I have a question is I want to merge into a CSV,so I need to achieve first below as :

Computer A      Computer B
------------    ------------
20.03           20.03
20.02           20.02
20.01           20.01
                XXX
                XXX

How can I do?  I have many something like those tables that need to merge
I tried some many time, just can't be able to do that

Body:
Start by turning both arrays into hashtables - this way we can quickly lookup whether a value exists in one or both:

$ComputerATable = @{}
$AObjects |ForEach-Object { $ComputerATable[$_.'Computer A'] = $_ }

$ComputerBTable = @{}
$AObjects |ForEach-Object { $ComputerATable[$_.'Computer B'] = $_ }

Now we just need to loop through all distinct computer names to build our "merged table":

$merged = $ComputerATable.Keys,$ComputerBTable.Keys |Sort-Object |ForEach-Object {
  # Create a new object with the value (if present) from either table
  [pscustomobject]@{
    'Computer A' = if($ComputerATable.ContainsKey($_)){ $_ }
    'Computer B' = if($ComputerBTable.ContainsKey($_)){ $_ }
  }
}


问:
.NET Core 32-bit (x86) version's HTTP Error 500.31 - ANCM Failed to Find Native Dependencies Common solutions to this issue Error:
What steps should I take to build and run .net core Web API application in 32-bit environment/runtime?

This is kind of a continuation of the previous question posting that I placed.

We developed an a .NET Core Web API application using the following technologies:

-NET Core (3.1)

-Visual Studio 2019

Unfortunately, we have to deploy said application to the following environment:

-32-bit Environment

-Windows Server 2008 R2 Enterprise (Service Pack 1)

-IIS Version 7.5

-8 GB RAM

( Also, it needs to be an In-Process because we Only want the .NET Core Web API Application to be within IIS Server )*

On my Development Computer that uses Visual Studio 2019, I installed Net Core 3.1 x86 sdk version ( i.e., the .NET Core 32-Bit version )

Also, within Windows 10 environment variable's Path variable, I ensured that the .NET Core 32-Bit version directory path is specified  above the .NET Core 64-bit version directory path:

Therefore, within my Visual Studio 2019, I brought up the application.
Also, within the Properties of the .NET Core Web Api Web Application’s Section, I’ve ensured that I selected x86 settings values:
Force x86 in VS go to the Properties > Build and change Platform target from Any CPU to x86

and also for the Debug Section, I have:

Also, within Visual Studio 2019 Enterprises  --->Tools ( in the Main Menu)
We Unticked the “Use the 64-bit version of IIS Express for web sites and projects”

The application’s blabhblah.csproj file has the following settings:

```<code> < Project Sdk="Microsoft.NET.Sdk.Web" >

   < PropertyGroup >
     < TargetFramework >netcoreapp3.1 < /TargetFramework >

     < AspNetCoreHostingModel > InProcess < /AspNetCoreHostingModel >

     < PlatformTarget > x86 < /PlatformTarget >

  < /PropertyGroup >

   < PropertyGroup Condition="'$(MSBuildRuntimeType)' == 'Core'" >

      < GenerateResourceMSBuildArchitecture > CurrentArchitecture <  /GenerateResourceMSBuildArchitecture >

     < GenerateResourceMSBuildRuntime > CurrentRuntime < /GenerateResourceMSBuildRuntime >

   < /PropertyGroup >……………..

  < ItemGroup >

    < PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.7" / >

    < PackageReference Include="Microsoft.Data.SqlClient" Version="1.1.3" / >

    < PackageReference Include="Swashbuckle.AspNetCore" Version="5.4.1" / >

    < PackageReference Include="Swashbuckle.Core" Version="5.6.0" / >

  < /ItemGroup >
</code>```

Also, I created a Directory.Build.targets file in the root directory of the Web Application:

```<code>< Project >
    < PropertyGroup
      Condition="'$(OS)' == 'Windows_NT' and
                 '$(PlatformTarget)' == 'x86' and
                 '$(TargetFrameworkIdentifier)' == '.NETCoreApp' and
                 '$(SelfContained)' != 'true'"
                   >

    < RunCommand >$(MSBuildProgramFiles32)\dotnet\dotnet< /RunCommand >

< /PropertyGroup >

< /Project >
</code>```

However, when I run the application, I get the following error:

HTTP Error 500.31 - ANCM Failed to Find Native Dependencies  Common
  solutions to this issue:  The specified version of
  Microsoft.NetCore.App or Microsoft.AspNetCore.App was not found.
  Specific error detected by ANCM: Could not execute because the
  specified command or file was not found. Possible reasons for this
  include: * You misspelled a built-in dotnet command. * You intended to
  execute a .NET Core program, but dotnet-%LAUNCHER_ARGS% does not
  exist. * You intended to run a global tool, but a dotnet-prefixed
  executable with this name could not be found on the PATH.
  Troubleshooting steps:  Check the system event log for error messages
  Enable logging the application process' stdout messages  Attach a
  debugger to the application process and inspect  For more information
  visit: https://go.microsoft.com/fwlink/?LinkID=2028526

Could someone please help me determine how to resovle the aforementioned "dotnet" missing error?
Are there any other modifications to settings/configurations that I need to make?

答:
@akseli @omajid @perry-qian-msft @yongqing-yu Sorry, this failed to work, we had to move away from using .NET Core technology( and had to migrate over to .NET Framework 4.7.2) because it would work properly for a little while, and then give us 500 error, and then later some 401 error.  I think it has something to do with the configuration because we are using:

-NET Core (3.1)

-In-Process within IIS Server

therefore, Within the standalone IIS Server, we should Not have to run  the .NET Core (3.1) application within it's own application pool as "Not Managed Code" because it's all In-Process and .NET Core (3.1) can run on IIS.  In any case, we do Not have time to resolve this problem so we migrate over to .NET Framework 4.7.2

@akseli @omajid @perry-qian-msft @yongqing-yu All Thank you for all your responses.

My Team Tech Lead found the solution  by specifying the .NET Core Web API Application's Build Settings to "Any CPU" Within Visual Studio 2019
( Within Visual Studio 2019, Right-click on .NET Core Web API Application, and then choose properties from the drop-down context menu, and then when the window pane shows up on, you select the Build Tab. )

Also, on the IIS Server, my Team Tech Lead ensured that that deployed .NET Core Web API Application's Application pool had the following settings( important to keep in mind that it is "Not Managed Code":

Body:
What steps should I take to build and run .net core Web API application in 32-bit environment/runtime?

This is kind of a continuation of the previous question posting that I placed.

We developed an a .NET Core Web API application using the following technologies:

-NET Core (3.1)

-Visual Studio 2019

Unfortunately, we have to deploy said application to the following environment:

-32-bit Environment

-Windows Server 2008 R2 Enterprise (Service Pack 1)

-IIS Version 7.5

-8 GB RAM

( Also, it needs to be an In-Process because we Only want the .NET Core Web API Application to be within IIS Server )*

On my Development Computer that uses Visual Studio 2019, I installed Net Core 3.1 x86 sdk version ( i.e., the .NET Core 32-Bit version )

Also, within Windows 10 environment variable's Path variable, I ensured that the .NET Core 32-Bit version directory path is specified  above the .NET Core 64-bit version directory path:

Therefore, within my Visual Studio 2019, I brought up the application.
Also, within the Properties of the .NET Core Web Api Web Application’s Section, I’ve ensured that I selected x86 settings values:
Force x86 in VS go to the Properties > Build and change Platform target from Any CPU to x86

and also for the Debug Section, I have:

Also, within Visual Studio 2019 Enterprises  --->Tools ( in the Main Menu)
We Unticked the “Use the 64-bit version of IIS Express for web sites and projects”

The application’s blabhblah.csproj file has the following settings:

 < Project Sdk="Microsoft.NET.Sdk.Web" >

   < PropertyGroup >
     < TargetFramework >netcoreapp3.1 < /TargetFramework >

     < AspNetCoreHostingModel > InProcess < /AspNetCoreHostingModel >

     < PlatformTarget > x86 < /PlatformTarget >

  < /PropertyGroup >

   < PropertyGroup Condition="'$(MSBuildRuntimeType)' == 'Core'" >

      < GenerateResourceMSBuildArchitecture > CurrentArchitecture <  /GenerateResourceMSBuildArchitecture >

     < GenerateResourceMSBuildRuntime > CurrentRuntime < /GenerateResourceMSBuildRuntime >

   < /PropertyGroup >……………..

  < ItemGroup >

    < PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.7" / >

    < PackageReference Include="Microsoft.Data.SqlClient" Version="1.1.3" / >

    < PackageReference Include="Swashbuckle.AspNetCore" Version="5.4.1" / >

    < PackageReference Include="Swashbuckle.Core" Version="5.6.0" / >

  < /ItemGroup >

Also, I created a Directory.Build.targets file in the root directory of the Web Application:

< Project >
    < PropertyGroup
      Condition="'$(OS)' == 'Windows_NT' and
                 '$(PlatformTarget)' == 'x86' and
                 '$(TargetFrameworkIdentifier)' == '.NETCoreApp' and
                 '$(SelfContained)' != 'true'"
                   >

    < RunCommand >$(MSBuildProgramFiles32)\dotnet\dotnet< /RunCommand >

< /PropertyGroup >

< /Project >

However, when I run the application, I get the following error:

HTTP Error 500.31 - ANCM Failed to Find Native Dependencies  Common
  solutions to this issue:  The specified version of
  Microsoft.NetCore.App or Microsoft.AspNetCore.App was not found.
  Specific error detected by ANCM: Could not execute because the
  specified command or file was not found. Possible reasons for this
  include: * You misspelled a built-in dotnet command. * You intended to
  execute a .NET Core program, but dotnet-%LAUNCHER_ARGS% does not
  exist. * You intended to run a global tool, but a dotnet-prefixed
  executable with this name could not be found on the PATH.
  Troubleshooting steps:  Check the system event log for error messages
  Enable logging the application process' stdout messages  Attach a
  debugger to the application process and inspect  For more information
  visit: https://go.microsoft.com/fwlink/?LinkID=2028526

Could someone please help me determine how to resovle the aforementioned "dotnet" missing error?
Are there any other modifications to settings/configurations that I need to make?


问:
Could not dropna from a dataframe after filling some column missing values with a pipeline
My data has 75130 rows × 36 columns, I plan to fill some column's 'NA' with mode filling and some with median. I just learned about the imputer and starts to practice it on my dataset.

```<code>An example of my dataFrame:
           y1   y2    y3    y4
    0      2    Nan   1     0.3
    1      Nan  Nan   2     0.4
    2      2    Nan   3     1.0
    3      3    Nan   4     2.0
    4      4    Nan   Nan   Nan
    5      5    Nan   Nan   Nan
</code>```

After running a pipeline that carried out mode filling on y1 and median filling on y3, I want to dropna on y2 and y4  but the result I am getting is an empty dataframe with no values in rows and column

Please what can i do apart from running a long line of code to fillna.

答:
Use df.dropna with how=all:

This will drop only columns which has Nan in all rows.

```<code>In [111]: df.dropna(axis=1, how='all')
Out[111]:
    y1   y3   y4
0    2    1  0.3
1  NaN    2  0.4
2    2    3  1.0
3    3    4  2.0
4    4  NaN  NaN
5    5  NaN  NaN
</code>```

Body:
My data has 75130 rows × 36 columns, I plan to fill some column's 'NA' with mode filling and some with median. I just learned about the imputer and starts to practice it on my dataset.

An example of my dataFrame:
           y1   y2    y3    y4
    0      2    Nan   1     0.3
    1      Nan  Nan   2     0.4
    2      2    Nan   3     1.0
    3      3    Nan   4     2.0
    4      4    Nan   Nan   Nan
    5      5    Nan   Nan   Nan

After running a pipeline that carried out mode filling on y1 and median filling on y3, I want to dropna on y2 and y4  but the result I am getting is an empty dataframe with no values in rows and column

Please what can i do apart from running a long line of code to fillna.

Body:
Use df.dropna with how=all:

This will drop only columns which has Nan in all rows.

In [111]: df.dropna(axis=1, how='all')
Out[111]:
    y1   y3   y4
0    2    1  0.3
1  NaN    2  0.4
2    2    3  1.0
3    3    4  2.0
4    4  NaN  NaN
5    5  NaN  NaN


问:
How to force the downstream project to be built only once in jenkins?
I'm using jenkins declarative pipeline for building my projects. There are 3 projects: A, B and C. Project A is the immediate downstream of B and C. Each time that projects B or C get triggered (via commits in Subversion), they produce an artifact (an SNAPSHOT), which will be then used by project A. For performance reasons I'd like to force the project A to be built only once, when projects B and C are being built or when they are waiting in the queue.

How could I achieve that using the declaritive pipelines?

Here are my pipeline source codes:

A:

```<code>pipeline {
  agent any
  tools {
    maven "maven"
  }
  stages {
    stage('Build') {
      steps {
        sh "mvn clean install"
      }
    }
  }
}
</code>```

B:

```<code>pipeline {
  agent any
  tools {
    maven "maven"
  }
  stages {
    stage('Build') {
      steps {
        sh "mvn clean install"
      }
    }
  }
  post {
    success {
      build job: 'A', wait: false
    }
  }
}
</code>```

C:

```<code>pipeline {
  agent any
  tools {
    maven "maven"
  }
  stages {
    stage('Build') {
      steps {
        sh "mvn clean install"
      }
    }
  }
  post {
    success {
      build job: 'A', wait: false
    }
  }
}
</code>```

答:
As discussed in comments, posting basic code snippet of wrapper pipeline :

```<code>pipeline {
    stages {
        stage('Trigger'){
            // Initial trigger if needed
        }
        stage('Build B and C'){
            parallel BuildB: {
                when{
                    // Condition to evaluate
                }
                steps {
                    // Trigger pipeline B
                }
            },
            BuildC: {
                when{
                    // Condition to evaluate
                }
                steps {
                    // // Trigger pipeline C
                }
            }
        }
        stage('Build A'){
            // Trigger pipeline A
        }
    }
}
</code>```

This wrapper pipeline will execute B and C in parallel, and only upon completion of both, will trigger A.

Body:
I'm using jenkins declarative pipeline for building my projects. There are 3 projects: A, B and C. Project A is the immediate downstream of B and C. Each time that projects B or C get triggered (via commits in Subversion), they produce an artifact (an SNAPSHOT), which will be then used by project A. For performance reasons I'd like to force the project A to be built only once, when projects B and C are being built or when they are waiting in the queue.

How could I achieve that using the declaritive pipelines?

Here are my pipeline source codes:

A:

pipeline {
  agent any
  tools {
    maven "maven"
  }
  stages {
    stage('Build') {
      steps {
        sh "mvn clean install"
      }
    }
  }
}

B:

pipeline {
  agent any
  tools {
    maven "maven"
  }
  stages {
    stage('Build') {
      steps {
        sh "mvn clean install"
      }
    }
  }
  post {
    success {
      build job: 'A', wait: false
    }
  }
}

C:

pipeline {
  agent any
  tools {
    maven "maven"
  }
  stages {
    stage('Build') {
      steps {
        sh "mvn clean install"
      }
    }
  }
  post {
    success {
      build job: 'A', wait: false
    }
  }
}

Body:
As discussed in comments, posting basic code snippet of wrapper pipeline :

pipeline {
    stages {
        stage('Trigger'){
            // Initial trigger if needed
        }
        stage('Build B and C'){
            parallel BuildB: {
                when{
                    // Condition to evaluate
                }
                steps {
                    // Trigger pipeline B
                }
            },
            BuildC: {
                when{
                    // Condition to evaluate
                }
                steps {
                    // // Trigger pipeline C
                }
            }
        }
        stage('Build A'){
            // Trigger pipeline A
        }
    }
}

This wrapper pipeline will execute B and C in parallel, and only upon completion of both, will trigger A.


问:
Adding shadow to inside of text field Flutter
I have this design that I'd like to use for my app but I'm not quite sure on how to add the box shadow. The shadow is on the inside of a TextField.. please can someone give me some assistance and point me in the right direction on how to do this?

(the box shadow at the top of the TextField)

Cheers,
Jack

答:
You can achieve that using a container as a background, for example using a Linear
Gradient you can get something like this:

```<code>Container(
      decoration: ShapeDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFFe6dfd8), Color(0xFFf7f5ec)],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          stops: [0.0, 0.4],
          tileMode: TileMode.clamp,
        ),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(32.0)),
        ),
      ),
      child: TextField(
          expands: false,
            style: TextStyle(fontSize: 20.0, color: Colors.black54),
            decoration: InputDecoration(
              contentPadding: EdgeInsets.all(12.0),
              prefixIcon: Icon(
                Icons.email,
                color: Colors.black54,
              ),
              hintText: 'email',
              hintStyle: TextStyle(color: Colors.black54),
              focusedBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Colors.white),
                borderRadius: BorderRadius.circular(32.0),
              ),
              enabledBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.white),
                borderRadius: BorderRadius.circular(32.0),
              ),
            ),
          ),
    );
</code>```

You can improve the effect using a Radial Gradient, a Box Shadow or as @Jakk said a Neumorphic shape.

Hope it helps.

Body:
You can achieve that using a container as a background, for example using a Linear
Gradient you can get something like this:

Container(
      decoration: ShapeDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFFe6dfd8), Color(0xFFf7f5ec)],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          stops: [0.0, 0.4],
          tileMode: TileMode.clamp,
        ),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(32.0)),
        ),
      ),
      child: TextField(
          expands: false,
            style: TextStyle(fontSize: 20.0, color: Colors.black54),
            decoration: InputDecoration(
              contentPadding: EdgeInsets.all(12.0),
              prefixIcon: Icon(
                Icons.email,
                color: Colors.black54,
              ),
              hintText: 'email',
              hintStyle: TextStyle(color: Colors.black54),
              focusedBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Colors.white),
                borderRadius: BorderRadius.circular(32.0),
              ),
              enabledBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.white),
                borderRadius: BorderRadius.circular(32.0),
              ),
            ),
          ),
    );

You can improve the effect using a Radial Gradient, a Box Shadow or as @Jakk said a Neumorphic shape.

Hope it helps.


问:
Updating UI when working with OperationQueue
I have an operation queue setup as follows:

```<code>let queue = OperationQueue()
queue.name = "com.company.myQueue"
queue.qualityOfService = .userInitiated
queue.maxConcurrentOperationCount = 64
...
var current = 0
var totalCount = someArray.count
for i in someArray {
...
   let op = BlockOperation {
   ... // do some database queries
   current += 1
   }

   op.completionBlock = {
     DispatchQueue.main.async {
     let nData: [String: CGFloat] = ["value": CGFloat(current/totalCount)]
     NotificationCenter.default.post(name:Notification.Name(rawValue: "update"), object: nil, userInfo: nData)
   }

   queue.addOperation(op)
}
</code>```

In my ViewController I listen for the notification and update a UILabel with the percentage. Problem is though I don't get any intermediate values... it jumps from being 0 directly to 100 once all the operations are done.

What am I doing wrong?

Thanks

答: The problem is CGFloat(current / totalCount). That does the integer math first, and then converts it to a float. You should flip that around to CGFloat(current) / CGFloat(totalCount).

Body:
I have an operation queue setup as follows:

let queue = OperationQueue()
queue.name = "com.company.myQueue"
queue.qualityOfService = .userInitiated
queue.maxConcurrentOperationCount = 64
...
var current = 0
var totalCount = someArray.count
for i in someArray {
...
   let op = BlockOperation {
   ... // do some database queries
   current += 1
   }

   op.completionBlock = {
     DispatchQueue.main.async {
     let nData: [String: CGFloat] = ["value": CGFloat(current/totalCount)]
     NotificationCenter.default.post(name:Notification.Name(rawValue: "update"), object: nil, userInfo: nData)
   }

   queue.addOperation(op)
}

In my ViewController I listen for the notification and update a UILabel with the percentage. Problem is though I don't get any intermediate values... it jumps from being 0 directly to 100 once all the operations are done.

What am I doing wrong?

Thanks


问:
"None of [Float64Index([nan, nan], dtype='float64')] are in the [index]" setting col A value if col B contains string
I have a dataframe (called corpus) with one column (tweet) and 2 rows:

```<code>['check, tihs, out, this, bear, love, jumping, on, this, plant']
['i, can, t, bear, the, noise, from, that, power, plant, it, make, me, jump']
</code>```

I have a list (called vocab) of unique words in the column:

```<code>['check',
 'tihs',
 'out',
 'this',
 'bear',
 'love',
 'jumping',
 'on',
 'plant',
 'i',
 'can',
 't',
 'the',
 'noise',
 'from',
 'that',
 'power',
 'it',
 'make',
 'me',
 'jump']
</code>```

I want to add a new column for each word in vocab. I want all values for the new columns to be zero, except for when the tweet contains the word, in which case I want the value of the word column to be 1.

So I tried running the code below:

```<code>for word in vocab:
    corpus[word] = 0
    corpus.loc[corpus["tweet"].str.contains(word), word] = 1
</code>```

...and the following error was displayed:

```<code>"None of [Float64Index([nan, nan], dtype='float64')] are in the [index]"
</code>```

How can I check to see if the tweet contains the word, and then if so, set the value of the new column for the word to 1?

答:
Your corpus['tweet'] is list type, each is a skeleton. So .str.contains would returns NaN. You may want to do:

```<code># turn tweets into strings
corpus["tweet"] = [x[0] for x in corpus['tweet']]

# one-hot-encode
for word in vocab:
    corpus[word] = 0
    corpus.loc[corpus["tweet"].str.contains(word), word] = 1
</code>```

But then this may not be what you want, because contains will search for all substrings, e.g. this girl goes to school will returns 1 in both columns is and this.

Based on your data, you can do:

```<code>corpus["tweet"] = [x[0] for x in corpus['tweet']]

corpus = corpus.join(corpus['tweet'].str.get_dummies(', ')
                         .reindex(vocab, axis=1, fill_value=0)
                    )
</code>```

Body:
I have a dataframe (called corpus) with one column (tweet) and 2 rows:

['check, tihs, out, this, bear, love, jumping, on, this, plant']
['i, can, t, bear, the, noise, from, that, power, plant, it, make, me, jump']

I have a list (called vocab) of unique words in the column:

['check',
 'tihs',
 'out',
 'this',
 'bear',
 'love',
 'jumping',
 'on',
 'plant',
 'i',
 'can',
 't',
 'the',
 'noise',
 'from',
 'that',
 'power',
 'it',
 'make',
 'me',
 'jump']

I want to add a new column for each word in vocab. I want all values for the new columns to be zero, except for when the tweet contains the word, in which case I want the value of the word column to be 1.

So I tried running the code below:

for word in vocab:
    corpus[word] = 0
    corpus.loc[corpus["tweet"].str.contains(word), word] = 1

...and the following error was displayed:

"None of [Float64Index([nan, nan], dtype='float64')] are in the [index]"

How can I check to see if the tweet contains the word, and then if so, set the value of the new column for the word to 1?

Body:
Your corpus['tweet'] is list type, each is a skeleton. So .str.contains would returns NaN. You may want to do:

# turn tweets into strings
corpus["tweet"] = [x[0] for x in corpus['tweet']]

# one-hot-encode
for word in vocab:
    corpus[word] = 0
    corpus.loc[corpus["tweet"].str.contains(word), word] = 1

But then this may not be what you want, because contains will search for all substrings, e.g. this girl goes to school will returns 1 in both columns is and this.

Based on your data, you can do:

corpus["tweet"] = [x[0] for x in corpus['tweet']]

corpus = corpus.join(corpus['tweet'].str.get_dummies(', ')
                         .reindex(vocab, axis=1, fill_value=0)
                    )