问:
Function doesn't return right array's values
I've started learning functions in C.

I have a task to convert numbers from imperial to metric, which are contained in the 2d Array.

Array:

```<code>{1300, 0}  [0][0] [0][1]

{2198, 0}  [1][0] [1][1]

{4199, 1}  [2][0] [2][1]

{2103, 0}  [3][0] [3][1]

{3104, 1}  [4][0] [4][1]

{1093, 1}  [5][0] [5][1]

{3204, 0}  [6][0] [6][1]
</code>```

So I am calling function with double return SortedArray[DATA_ROWS] = find_function(MixedData);

find_function logic:

0 is an indicator of the metric system  value and 1 is an indicator of imperial system value,
i is a row indexer and j is a column indexer.

So when for cycles find out that column value is 0 or 1 they save [j-1](an actual value that we need) into SortedArray.

It also converts value if finds out that column value is 1 SortedArray[i] = MixedData[i][j-1]*CONSTANT;

Just for a check, I did printf to see if values are correct and correctly converted if needed.
I got this output:

```<code>1300.00
2198.00
1301.69
2103.00
962.24
338.83
3204.00
</code>```

So, seems like correct, but in Task I have another task - use 2 functions to solve this task.
I've decided to make another function, which will sum all values in SortedArray[DATA_ROWS] and then calculate avg - average.
Then print them out.
And here comes the problem.

Calling function with no return total_AVG(SortedArray); with copied array SortedArray[DATA_ROWS]

Just to check made a printf and got this:

```<code>-1.#R
0.00
0.00
0.00
0.00
0.00
0.00
</code>```

It seems like my SortedArray[DATA_ROWS] did not copy into the second function total_AVG

Pointers are coming in the next task, so according to task's timeline I can't use them
*
(and even if I could, I have no idea how to use them still)*

Can you please tell me, what I am doing wrong.

NB:
Some comments and variables, which are not used just old ones, when I tried to correct my code.
And also I only need to understand why SortedArray[DATA_ROWS] did not copy into second function total_AVG. All further logic will be corrected after solving this problem.

Thank you! And sorry for broken English!

CODE:

```<code>#include <stdio.h>
#define DATA_ROWS 7
#define DATA_COLS 2
#define CONSTANT 0.31
#define MAX 3

double find_function(int MixedData[DATA_ROWS][DATA_COLS]);
void total_AVG(double SortedArray[DATA_ROWS]);

int main(void)
{
    int i;
    double SortedArray[DATA_ROWS];

    int MixedData[DATA_ROWS][DATA_COLS] = {
        {1300, 0},//[0][0] [0][1]
        {2198, 0},//[1][0] [1][1]
        {4199, 1},//[2][0] [2][1]
        {2103, 0},//[3][0] [3][1]
        {3104, 1},//[4][0] [4][1]
        {1093, 1},//[5][0] [5][1]
        {3204, 0}};//[6][0] [6][1]

    SortedArray[DATA_ROWS] = find_function(MixedData);
    total_AVG(SortedArray);

    return 0;
}

double find_function(int MixedData[DATA_ROWS][DATA_COLS])
{
    // imperial numbers from source array "mixedData" are 4199,3104,1093;

    int i,j; // indexers
    double SortedArray[DATA_ROWS];

    // 7 rows, each row suppose to contain only metric values
    // That means, if second for cycle with j indexer finds 0, it will contain j-1 value for example 1300 in SortedArray
    // If it finds in second for cycle with j indexer 1, it will converte the value from imperial to metric for example 4199*0.31
        /*  {1300, 0}  [0][0] [0][1]
            {2198, 0}  [1][0] [1][1]
            {4199, 1}  [2][0] [2][1]
            {2103, 0}  [3][0] [3][1]
            {3104, 1}  [4][0] [4][1]
            {1093, 1}  [5][0] [5][1]
            {3204, 0}  [6][0] [6][1] */

    // Probably problem in "double SortedArray and int MixedData"
    for(i=0;i<DATA_ROWS;i++)
    {
        for(j=0;j<DATA_COLS;j++)
        {
            if(MixedData[i][j]==0)
            {
                SortedArray[i] = MixedData[i][j-1];
            }
            else if(MixedData[i][j]==1)
            {
                SortedArray[i] = MixedData[i][j-1]*CONSTANT;

            }
        }
    }
    for(i=0;i<DATA_ROWS;i++)
    {
        //total += SortedArray[i];
        printf("%.2lf\n", SortedArray[i]);
    }

    return SortedArray[DATA_ROWS];
}

void total_AVG(double SortedArray[DATA_ROWS])
{
    double avg,total;
    int i;

    for(i=0;i<DATA_ROWS;i++)
    {
        printf("%.2lf\n", SortedArray[i]);
    }
    //avg = total/DATA_ROWS;
    //printf("Total by every worker: %.2lf\n",total);
    //printf("In average by every worker: %.2lf", avg);

    return;
}

</code>```

答:
The function you've defined is:

```<code>double find_function(int MixedData[DATA_ROWS][DATA_COLS]) { }
</code>```

It's return type is double whereas you're trying to return an array, assays can't be returned liked nor can be assigned.

```<code>return SortedArray[DATA_ROWS];
</code>```

Here you're trying to access the element which is equal to length, it's wrong.
What you can do is, pass array as function parameter (or as a pointer) and return void.
i.e:

```<code>void find_function(int MixedData[DATA_ROWS][DATA_COLS], double* SortedArray) { /*...*/ }
</code>```

or you may use dynamic memory allocations.. in case you want to return the base address from the function.

Body:
I've started learning functions in C.

I have a task to convert numbers from imperial to metric, which are contained in the 2d Array.

Array:

{1300, 0}  [0][0] [0][1]

{2198, 0}  [1][0] [1][1]

{4199, 1}  [2][0] [2][1]

{2103, 0}  [3][0] [3][1]

{3104, 1}  [4][0] [4][1]

{1093, 1}  [5][0] [5][1]

{3204, 0}  [6][0] [6][1]

So I am calling function with double return SortedArray[DATA_ROWS] = find_function(MixedData);

find_function logic:

0 is an indicator of the metric system  value and 1 is an indicator of imperial system value,
i is a row indexer and j is a column indexer.

So when for cycles find out that column value is 0 or 1 they save [j-1](an actual value that we need) into SortedArray.

It also converts value if finds out that column value is 1 SortedArray[i] = MixedData[i][j-1]*CONSTANT;

Just for a check, I did printf to see if values are correct and correctly converted if needed.
I got this output:

1300.00
2198.00
1301.69
2103.00
962.24
338.83
3204.00

So, seems like correct, but in Task I have another task - use 2 functions to solve this task.
I've decided to make another function, which will sum all values in SortedArray[DATA_ROWS] and then calculate avg - average.
Then print them out.
And here comes the problem.

Calling function with no return total_AVG(SortedArray); with copied array SortedArray[DATA_ROWS]

Just to check made a printf and got this:

-1.#R
0.00
0.00
0.00
0.00
0.00
0.00

It seems like my SortedArray[DATA_ROWS] did not copy into the second function total_AVG

Pointers are coming in the next task, so according to task's timeline I can't use them
*
(and even if I could, I have no idea how to use them still)*

Can you please tell me, what I am doing wrong.

NB:
Some comments and variables, which are not used just old ones, when I tried to correct my code.
And also I only need to understand why SortedArray[DATA_ROWS] did not copy into second function total_AVG. All further logic will be corrected after solving this problem.

Thank you! And sorry for broken English!

CODE:

#include <stdio.h>
#define DATA_ROWS 7
#define DATA_COLS 2
#define CONSTANT 0.31
#define MAX 3

double find_function(int MixedData[DATA_ROWS][DATA_COLS]);
void total_AVG(double SortedArray[DATA_ROWS]);

int main(void)
{
    int i;
    double SortedArray[DATA_ROWS];

    int MixedData[DATA_ROWS][DATA_COLS] = {
        {1300, 0},//[0][0] [0][1]
        {2198, 0},//[1][0] [1][1]
        {4199, 1},//[2][0] [2][1]
        {2103, 0},//[3][0] [3][1]
        {3104, 1},//[4][0] [4][1]
        {1093, 1},//[5][0] [5][1]
        {3204, 0}};//[6][0] [6][1]

    SortedArray[DATA_ROWS] = find_function(MixedData);
    total_AVG(SortedArray);

    return 0;
}

double find_function(int MixedData[DATA_ROWS][DATA_COLS])
{
    // imperial numbers from source array "mixedData" are 4199,3104,1093;

    int i,j; // indexers
    double SortedArray[DATA_ROWS];

    // 7 rows, each row suppose to contain only metric values
    // That means, if second for cycle with j indexer finds 0, it will contain j-1 value for example 1300 in SortedArray
    // If it finds in second for cycle with j indexer 1, it will converte the value from imperial to metric for example 4199*0.31
        /*  {1300, 0}  [0][0] [0][1]
            {2198, 0}  [1][0] [1][1]
            {4199, 1}  [2][0] [2][1]
            {2103, 0}  [3][0] [3][1]
            {3104, 1}  [4][0] [4][1]
            {1093, 1}  [5][0] [5][1]
            {3204, 0}  [6][0] [6][1] */

    // Probably problem in "double SortedArray and int MixedData"
    for(i=0;i<DATA_ROWS;i++)
    {
        for(j=0;j<DATA_COLS;j++)
        {
            if(MixedData[i][j]==0)
            {
                SortedArray[i] = MixedData[i][j-1];
            }
            else if(MixedData[i][j]==1)
            {
                SortedArray[i] = MixedData[i][j-1]*CONSTANT;

            }
        }
    }
    for(i=0;i<DATA_ROWS;i++)
    {
        //total += SortedArray[i];
        printf("%.2lf\n", SortedArray[i]);
    }

    return SortedArray[DATA_ROWS];
}

void total_AVG(double SortedArray[DATA_ROWS])
{
    double avg,total;
    int i;

    for(i=0;i<DATA_ROWS;i++)
    {
        printf("%.2lf\n", SortedArray[i]);
    }
    //avg = total/DATA_ROWS;
    //printf("Total by every worker: %.2lf\n",total);
    //printf("In average by every worker: %.2lf", avg);

    return;
}

Body:
The function you've defined is:

double find_function(int MixedData[DATA_ROWS][DATA_COLS]) { }

It's return type is double whereas you're trying to return an array, assays can't be returned liked nor can be assigned.

return SortedArray[DATA_ROWS];

Here you're trying to access the element which is equal to length, it's wrong.
What you can do is, pass array as function parameter (or as a pointer) and return void.
i.e:

void find_function(int MixedData[DATA_ROWS][DATA_COLS], double* SortedArray) { /*...*/ }

or you may use dynamic memory allocations.. in case you want to return the base address from the function.


来源: stackexchange

问:
Typescript require param if another param is passed, multiple times
I'm trying to do a distributed union type where the passing of one key, makes other keys required.

interface BaseArgs {
    title: string
}

interface FuncPagerArgs {
    enablePager: true
    limit: number
    count: number
}

type FuncArgs = (FuncPagerArgs & BaseArgs) | BaseArgs;

function func(args: FuncArgs) {
    if ("enablePager" in args) {
        pager({ limit: args.limit, count: args.count });
    }
}

interface PagerArgs {
    limit: number
    count: number
}

function pager(args: PagerArgs) {

}

func({
    title: "something",
    enablePager: true
})
```

https://www.typescriptlang.org/play/index.html?ssl=1&ssc=1&pln=31&pc=3#code/JYOwLgpgTgZghgYwgAgEJwM4QIJQOYbIDeAUMucmMGADYQBcyGYUoeJAviSaJLIigBiAVxAIACnDzRcBYmQoQQcAEZ1J0qIxbCIC8jWABbaoxDCjK6PuQIA9qLBmLVqJ25gAngAchohLKEALzIABQiYhoy+IQAZGiYODEAlMgAPglYgQDc3DD+VHYgyPlioXAxjBEBKfIUyMAwYQBESqrqUtDNDcUVBKmk9fXenVChRMiGJk7IfRgAdFPUADS2DuCMc-P2jsgcybn1XFw84NDwSMhRUIF1FEsz5pbW9TsbyE+u7iSlCIXFI005UqV1GgQG3BOv3GNiotAYyGaGDsRggYAAFmxmssbG01BBrtooLpOMkgA

To me, that code should not pass validation because I'm calling func while passing enablePager, but I did not pass limit or count when both are required when enablePager is true. In my real world example, I was trying to do this pattern for 3 or 4 different feature booleans, each which will alter the contract to require some more fields. Unfortunately I can't even the first feature boolean to work, let alone multiple.

答:
The issue we are seeing here is related to not having proper discriminant between elements of the union. We have overlap between two members  (FuncPagerArgs & BaseArgs) | BaseArgs, the overlap is equal BaseArgs. What is very important is also behavior of function argument types in TS:

When comparing the types of function parameters, assignment succeeds if either the source parameter is assignable to the target parameter, or vice versa.

What does it mean - if our type is assignable to the wanted type, or wanted type is assignable to our argument type you can pass it. Consider the test:

```<code>type ArgType = {
    title: "something",
    enablePager: true
}
type IsAssignable = ArgType extends FuncArgs ? true : false; // true, can be passed
</code>```

So type you are passing is assignable to the wanted type, then TS allows it to be passed. Not ask me why, this is design decisions, and you can understand it as a compromise, being more strict would block many wanted behaviors, at least that is stated in the TS docs I have linked above. For sure there is now the issue inside the code which will make us the runtime error.

In order to fix it we need to create proper discriminated union without overlap.

```<code>interface BaseArgs {
    title: string
}

interface OnlyTitle extends BaseArgs {
    kind: 'TITLE'
}

interface FuncPagerArgs extends BaseArgs {
    kind: 'PAGER'
    enablePager: true
    limit: number
    count: number
}

type FuncArgs = OnlyTitle | FuncPagerArgs;

function func(args: FuncArgs) {
    if (args.kind === 'PAGER') {
        pager({ limit: args.limit, count: args.count });
    }
}

interface PagerArgs {
    limit: number
    count: number
}

function pager(args: PagerArgs) {

}

func({
    kind: "TITLE",
    enablePager: true
}) // error

func({
    kind: "TITLE",
    title: 'title'
}) // correct
</code>```

What I did is discriminant in form of kind property which will allow on proper members without any overlap. It means now you can only use or one or another variant, the type never overlap.

Edit after the comment

In the comment author has stated he needs to combine all options togethere, but when something is enabled all options related to that should go within. Such kind of structure we can do by separation of options in groups + joining them. Consider:

```<code>interface Base {
    title: string
}
interface Pager  {
  pager?: {
    limit: number
    count: number
  }
}

interface Sort {
  sorter?: {
    columns: string[] // example property
  }
}

type Options = Pager & Sort & Base;

function func(args: Options) {
    if (args.pager) {
        pager({ limit: args.pager.limit, count: args.pager.count });
    }
    if (args.sorter) {
       sorter(args.sorter.columns)
    }
}

func({
  title: 'title',
  pager: {count: 2, limit: 10} // all fields its ok
})

func({
  title: 'title',
  pager: {count: 2} // error limit is missing
})

</code>```

Now we can have pager and sorter together, when you have pager you need to put all options related to it as they are required.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to do a distributed union type where the passing of one key, makes other keys required.

interface BaseArgs {
    title: string
}

interface FuncPagerArgs {
    enablePager: true
    limit: number
    count: number
}

type FuncArgs = (FuncPagerArgs & BaseArgs) | BaseArgs;

function func(args: FuncArgs) {
    if ("enablePager" in args) {
        pager({ limit: args.limit, count: args.count });
    }
}

interface PagerArgs {
    limit: number
    count: number
}

function pager(args: PagerArgs) {

}

func({
    title: "something",
    enablePager: true
})

https://www.typescriptlang.org/play/index.html?ssl=1&ssc=1&pln=31&pc=3#code/JYOwLgpgTgZghgYwgAgEJwM4QIJQOYbIDeAUMucmMGADYQBcyGYUoeJAviSaJLIigBiAVxAIACnDzRcBYmQoQQcAEZ1J0qIxbCIC8jWABbaoxDCjK6PuQIA9qLBmLVqJ25gAngAchohLKEALzIABQiYhoy+IQAZGiYODEAlMgAPglYgQDc3DD+VHYgyPlioXAxjBEBKfIUyMAwYQBESqrqUtDNDcUVBKmk9fXenVChRMiGJk7IfRgAdFPUADS2DuCMc-P2jsgcybn1XFw84NDwSMhRUIF1FEsz5pbW9TsbyE+u7iSlCIXFI005UqV1GgQG3BOv3GNiotAYyGaGDsRggYAAFmxmssbG01BBrtooLpOMkgA

To me, that code should not pass validation because I'm calling func while passing enablePager, but I did not pass limit or count when both are required when enablePager is true. In my real world example, I was trying to do this pattern for 3 or 4 different feature booleans, each which will alter the contract to require some more fields. Unfortunately I can't even the first feature boolean to work, let alone multiple.

Body:
The issue we are seeing here is related to not having proper discriminant between elements of the union. We have overlap between two members  (FuncPagerArgs & BaseArgs) | BaseArgs, the overlap is equal BaseArgs. What is very important is also behavior of function argument types in TS:

When comparing the types of function parameters, assignment succeeds if either the source parameter is assignable to the target parameter, or vice versa.

What does it mean - if our type is assignable to the wanted type, or wanted type is assignable to our argument type you can pass it. Consider the test:

type ArgType = {
    title: "something",
    enablePager: true
}
type IsAssignable = ArgType extends FuncArgs ? true : false; // true, can be passed

So type you are passing is assignable to the wanted type, then TS allows it to be passed. Not ask me why, this is design decisions, and you can understand it as a compromise, being more strict would block many wanted behaviors, at least that is stated in the TS docs I have linked above. For sure there is now the issue inside the code which will make us the runtime error.

In order to fix it we need to create proper discriminated union without overlap.

interface BaseArgs {
    title: string
}

interface OnlyTitle extends BaseArgs {
    kind: 'TITLE'
}

interface FuncPagerArgs extends BaseArgs {
    kind: 'PAGER'
    enablePager: true
    limit: number
    count: number
}

type FuncArgs = OnlyTitle | FuncPagerArgs;

function func(args: FuncArgs) {
    if (args.kind === 'PAGER') {
        pager({ limit: args.limit, count: args.count });
    }
}

interface PagerArgs {
    limit: number
    count: number
}

function pager(args: PagerArgs) {

}

func({
    kind: "TITLE",
    enablePager: true
}) // error

func({
    kind: "TITLE",
    title: 'title'
}) // correct

What I did is discriminant in form of kind property which will allow on proper members without any overlap. It means now you can only use or one or another variant, the type never overlap.

Edit after the comment

In the comment author has stated he needs to combine all options togethere, but when something is enabled all options related to that should go within. Such kind of structure we can do by separation of options in groups + joining them. Consider:

interface Base {
    title: string
}
interface Pager  {
  pager?: {
    limit: number
    count: number
  }
}

interface Sort {
  sorter?: {
    columns: string[] // example property
  }
}

type Options = Pager & Sort & Base;

function func(args: Options) {
    if (args.pager) {
        pager({ limit: args.pager.limit, count: args.pager.count });
    }
    if (args.sorter) {
       sorter(args.sorter.columns)
    }
}

func({
  title: 'title',
  pager: {count: 2, limit: 10} // all fields its ok
})

func({
  title: 'title',
  pager: {count: 2} // error limit is missing
})

Now we can have pager and sorter together, when you have pager you need to put all options related to it as they are required.


问:
How to pass django authtoken using ajax
How to pass djangorest authtoken from AJAX request
I tried following code.but not working</p>

```<code>$({
    type: 'POST',
    url: 'menu/menu/,
    beforeSend: function (request) {
        request.setRequestHeader("Authorization ", "Token " + token);
    },
});
</code>```

答:
Try serialize your authtoken</p>

```<code>$.ajax({
        type: "POST",
        url: "/menu/menu/",
        data: JSON.stringify(data),
        sucess: function() { //do something },
        contentType: "application/json; charset=utf-8",
        //content type: application/x-www-form-urlencoded; charset=UTF-8
        dataType: "json",
        crossDomain:false,
        beforeSend: function(xhr, settings) {
          xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    });
</code>```

Title: How to pass django authtoken using ajax

Body:
How to pass djangorest authtoken from AJAX request
I tried following code.but not working

$({
    type: 'POST',
    url: 'menu/menu/,
    beforeSend: function (request) {
        request.setRequestHeader("Authorization ", "Token " + token);
    },
});

Body:
Try serialize your authtoken

$.ajax({
        type: "POST",
        url: "/menu/menu/",
        data: JSON.stringify(data),
        sucess: function() { //do something },
        contentType: "application/json; charset=utf-8",
        //content type: application/x-www-form-urlencoded; charset=UTF-8
        dataType: "json",
        crossDomain:false,
        beforeSend: function(xhr, settings) {
          xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    });


问:
Incrementing alphabet from a specific input
I am new to JavaScript. Here is my task

I want to generate a Serial number starting with 'A' and with numbers in increment manner.
Example : A000001, A000002,...,A000010  and so on.
I want to generate this serial number according to the current year I am giving as an input.
Example :
If current year is 2020, then A000001, A000002,...,A000010  and so on
If current year is 2021, then B000001, B000002,...,B000010  and so on
If current year is 2046, then it should be like AA000001, AA000002,...,AA000010  and so on . Because 26 letters, it should start from AA. Same way for 2047 - AB, 2048 - AC and so on.

```<code>function colName(n) {
    var ordA = 'A'.charCodeAt(0);
    var ordZ = 'Z'.charCodeAt(0);
    var len = ordZ - ordA + 1;
    var year = 2020;

    var s = "";
    while(n >= 0) {
        s = String.fromCharCode(n % len + ordA) + s;
        n = Math.floor(n / len) - 1;
    }
    return s;
}
</code>```

Here I have a code that will generate alphabets in the manner of A,B,C,....Z,AA. But when I call the function colName(n), the value of 'n' should be given from 0 to start from 'A'. I want to give the value as my current year. If I give n value 2020, then it should show 'A'.

I am stuck here and not getting idea about how to do this and how to add incrementing number with this. Here I am giving an image of my concept

Thank you.

答:
You need to subtract n by 2020, to make it starting point (think of it as offset).
Also 2027 will be H not AA, since 2020=A, and 26 characters from there will be Z.

function colName(n) {
    var ordA = 'A'.charCodeAt(0);
    var ordZ = 'Z'.charCodeAt(0);
    var len = ordZ - ordA + 1;
  n -= 2020;

    var s = "";
    while(n >= 0) {
        s = String.fromCharCode(n % len + ordA) + s;
        n = Math.floor(n / len) - 1;
    }
    return s;
}
document.write(colName(2020));```

Body:
I am new to JavaScript. Here is my task

I want to generate a Serial number starting with 'A' and with numbers in increment manner.
Example : A000001, A000002,...,A000010  and so on.
I want to generate this serial number according to the current year I am giving as an input.
Example :
If current year is 2020, then A000001, A000002,...,A000010  and so on
If current year is 2021, then B000001, B000002,...,B000010  and so on
If current year is 2046, then it should be like AA000001, AA000002,...,AA000010  and so on . Because 26 letters, it should start from AA. Same way for 2047 - AB, 2048 - AC and so on.

function colName(n) {
    var ordA = 'A'.charCodeAt(0);
    var ordZ = 'Z'.charCodeAt(0);
    var len = ordZ - ordA + 1;
    var year = 2020;

    var s = "";
    while(n >= 0) {
        s = String.fromCharCode(n % len + ordA) + s;
        n = Math.floor(n / len) - 1;
    }
    return s;
}

Here I have a code that will generate alphabets in the manner of A,B,C,....Z,AA. But when I call the function colName(n), the value of 'n' should be given from 0 to start from 'A'. I want to give the value as my current year. If I give n value 2020, then it should show 'A'.

I am stuck here and not getting idea about how to do this and how to add incrementing number with this. Here I am giving an image of my concept

Thank you.


问:
Could you use the YouTube-Data-API without a redirect_uri, how?
I've created a command line NodeJS application to upload videos to a YouTube channel.

The problem I face is, with every upload, I get directed to the specified redirect_uri - which is required according to the Google Docs.

I've managed to bypass user authorization/sign-in by passing the following:
prompt: 'none'
when authenticating the YouTube API

I'm now looking to bypass visiting a URI altogether, so it just runs in the command line.

Any ideas?

let oauth = Youtube.authenticate({

```<code>type: 'oauth',
client_id: CREDENTIALS.web.client_id,
client_secret: CREDENTIALS.web.client_secret,
redirect_url: CREDENTIALS.web.redirect_uris[0]
</code>```

});

opn(oauth.generateAuthUrl({

```<code>access_type: 'offline',
scope: ['https://www.googleapis.com/auth/youtube.upload'],
prompt: 'none'
</code>```

}));

The redirect uri originally gets specified when creating the app in the Google Developer's console.

Then you download the JSON file, add it to your working directory and call upon the Client_id, client_secret and redirect_uri from the JSON file to authenticate YouTube using oauth2.0.

When I comment out redirect_uri, I receive an error of invalid request - redirect_uri required.

I'm looking for a potential workaround, like just redirecting once, for example, rather than for each upload I make when running node file.js in the terminal.

答: You should read the relevant part of the official documentation. A Loopback IP address could be used, so I guess something like "http://127.0.0.1:80" or "urn:ietf:wg:oauth:2.0:oob" may work. Don't forget to set the other required parameters though.</p>

Body:
I've created a command line NodeJS application to upload videos to a YouTube channel.

The problem I face is, with every upload, I get directed to the specified redirect_uri - which is required according to the Google Docs.

I've managed to bypass user authorization/sign-in by passing the following:
prompt: 'none'
when authenticating the YouTube API

I'm now looking to bypass visiting a URI altogether, so it just runs in the command line.

Any ideas?

let oauth = Youtube.authenticate({

type: 'oauth',
client_id: CREDENTIALS.web.client_id,
client_secret: CREDENTIALS.web.client_secret,
redirect_url: CREDENTIALS.web.redirect_uris[0]

});

opn(oauth.generateAuthUrl({

access_type: 'offline',
scope: ['https://www.googleapis.com/auth/youtube.upload'],
prompt: 'none'

}));

The redirect uri originally gets specified when creating the app in the Google Developer's console.

Then you download the JSON file, add it to your working directory and call upon the Client_id, client_secret and redirect_uri from the JSON file to authenticate YouTube using oauth2.0.

When I comment out redirect_uri, I receive an error of invalid request - redirect_uri required.

I'm looking for a potential workaround, like just redirecting once, for example, rather than for each upload I make when running node file.js in the terminal.


问:
How to add Header name and Icon on my MainTabHome
Below is the code of my MainTopTab and MainTabScreen is called on my another Navigation => "createStackNavigator" on my App. As it is my Second main tab. I am not able set icon and Change the name as well. Because it is not a class component, so I am not able to use below code

```<code> static navigationOptions = {
    title: 'Home' }
</code>```

Is there anyway to Set Title and Icon without using class component. ?

```<code>import { createMaterialTopTabNavigator } from 'react-navigation-tabs';
import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from 'react-navigation';
//components
import All from './All';
import MostView from './MostView';
import Reco from './Reco';
import Recent from './Recent';

const MainTabScreen = createMaterialTopTabNavigator(
    {
        All: { screen: All },
        MostView: { screen: MostView },
        Reco: { screen: Reco },
        Recent: { screen: Recent },
    },
    {
        initialRouteName: 'All',
        tabBarPosition: 'top',
        swipeEnabled: true,
        animationEnabled: true,
        tabBarOptions: {
            activeTintColor: '#744DD2',
            inactiveTintColor: '#4f4955',
            style: {
                backgroundColor: '#fff',
                //height: 150
            },
            labelStyle: {
                textAlign: 'center',
            },
            indicatorStyle: {
                borderBottomColor: '#744DD2',
                borderBottomWidth: 2.6,
            },
        },
    },
);

const TopTab = createStackNavigator({
    MainTabScreen: {
        screen: MainTabScreen,
        navigationOptions: {
            headerStyle: {
                backgroundColor: '#744DD2',
            },
            headerTintColor: '#FFFFFF',
            title: 'Clubs',
        },
    },
});

const MainTopTab = createAppContainer(MainTabScreen);

export default MainTopTab;

</code>```

答:
Depends which version of react-navigation you are using, if you are using the latest version 5.x , you can do as below:

```<code>const TopTab = createStackNavigator({
    MainTabScreen: {
        component: MainTabScreen,
        options={{
          headerTitle: <Text>Home</Text>,
          headerRight: () => (
            <Image source={{ uri: ''}} />
          ),
        }},
    },
});
</code>```

Body:
Below is the code of my MainTopTab and MainTabScreen is called on my another Navigation => "createStackNavigator" on my App. As it is my Second main tab. I am not able set icon and Change the name as well. Because it is not a class component, so I am not able to use below code

 static navigationOptions = {
    title: 'Home' }

Is there anyway to Set Title and Icon without using class component. ?

import { createMaterialTopTabNavigator } from 'react-navigation-tabs';
import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from 'react-navigation';
//components
import All from './All';
import MostView from './MostView';
import Reco from './Reco';
import Recent from './Recent';

const MainTabScreen = createMaterialTopTabNavigator(
    {
        All: { screen: All },
        MostView: { screen: MostView },
        Reco: { screen: Reco },
        Recent: { screen: Recent },
    },
    {
        initialRouteName: 'All',
        tabBarPosition: 'top',
        swipeEnabled: true,
        animationEnabled: true,
        tabBarOptions: {
            activeTintColor: '#744DD2',
            inactiveTintColor: '#4f4955',
            style: {
                backgroundColor: '#fff',
                //height: 150
            },
            labelStyle: {
                textAlign: 'center',
            },
            indicatorStyle: {
                borderBottomColor: '#744DD2',
                borderBottomWidth: 2.6,
            },
        },
    },
);

const TopTab = createStackNavigator({
    MainTabScreen: {
        screen: MainTabScreen,
        navigationOptions: {
            headerStyle: {
                backgroundColor: '#744DD2',
            },
            headerTintColor: '#FFFFFF',
            title: 'Clubs',
        },
    },
});

const MainTopTab = createAppContainer(MainTabScreen);

export default MainTopTab;

Body:
Depends which version of react-navigation you are using, if you are using the latest version 5.x , you can do as below:

const TopTab = createStackNavigator({
    MainTabScreen: {
        component: MainTabScreen,
        options={{
          headerTitle: <Text>Home</Text>,
          headerRight: () => (
            <Image source={{ uri: ''}} />
          ),
        }},
    },
});


问:
InitialValue does not set in RequiredFieldValidator DDL
For some reason the dropdownlist's initial value doesnt get set. It always loads some random value instead. When I look into the markup I can see all the list items including the one with -1 value. I also tried clearing browser cache and explicitly setting the SelectedIndex/Value in code to 0/"-1", but cant seem to figure out what is going on. Any idea?

Here is how I am doing it:

```<code><asp:DropDownList ID="ddlGender" runat="server" CssClass="select_Box" OnPreRender="LoadGenders">
                            </asp:DropDownList>
                            <div class="error">
                                <asp:RequiredFieldValidator
                                    ID="RequiredFieldValidatorGender"
                                    Runat="server"
                                    Enabled="true"
                                    InitialValue="-1"
                                    ControlToValidate="ddlGender"
                                    SetFocusOnError="true"
                                    Display="Dynamic">Gender Required</asp:RequiredFieldValidator>
                            </div>
</code>```

Generated HTML:

```<code><select name="pagecolumns_0$pagecontent_1$contentleftcol_0$ctl00$ddlGender" id="pagecolumns_0_pagecontent_1_contentleftcol_0_ctl00_ddlGender" class="select_Box">
<option value="-1">--Select Gender--</option>
<option selected="selected" value="M">Male</option>
<option value="F">Female</option></select>
</code>```

as you can see, it is randomly selecting Male. Alsow, I notice that, last time I fill the form I set it to Male before hitting submit. May be is it caching the selection?

Here is the .cs:

```<code>protected void LoadGenders(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            ((DropDownList)sender).Items.AddRange(Constants.GenderWithSelect);
        }
public static ListItem[] GenderWithSelect = (new[] { new ListItem("--Select Gender--", "-1") }).Concat(Gender).ToArray();
 public static ListItem[] Gender = new[]
                                              {
                                                  (new ListItem("Male","M")),
                                                  (new ListItem("Female","F"))
                                              };

</code>```

答:
I tried your code, and it appears that the generated html didn't have the correct field bound to the "value" of the select options.

What you must get must have this format :

```<code><select name="ctl00$MainContent$ddlGender" id="MainContent_ddlGender" class="select_Box">
  <option selected="selected" value="-1">not set</option>
  <option value="0">0</option>
  <option value="1">1</option>
</select>
</code>```

In order to have this, I had to set the DataValueField of the DropDownList:

```<code><asp:DropDownList ID="ddlGender" runat="server" CssClass="select_Box" OnPreRender="ddlGender_PreRender" DataValueField="Value" DataTextField="Text">
</code>```

(Just replace the DataTextField and DataValueField with the name of the properties of your class)

ContentLicense: CC BY-SA 3.0

Body:
For some reason the dropdownlist's initial value doesnt get set. It always loads some random value instead. When I look into the markup I can see all the list items including the one with -1 value. I also tried clearing browser cache and explicitly setting the SelectedIndex/Value in code to 0/"-1", but cant seem to figure out what is going on. Any idea?

Here is how I am doing it:

<asp:DropDownList ID="ddlGender" runat="server" CssClass="select_Box" OnPreRender="LoadGenders">
                            </asp:DropDownList>

                                <asp:RequiredFieldValidator
                                    ID="RequiredFieldValidatorGender"
                                    Runat="server"
                                    Enabled="true"
                                    InitialValue="-1"
                                    ControlToValidate="ddlGender"
                                    SetFocusOnError="true"
                                    Display="Dynamic">Gender Required</asp:RequiredFieldValidator>

Generated HTML:

<select name="pagecolumns_0$pagecontent_1$contentleftcol_0$ctl00$ddlGender" id="pagecolumns_0_pagecontent_1_contentleftcol_0_ctl00_ddlGender" class="select_Box">
<option value="-1">--Select Gender--</option>
<option selected="selected" value="M">Male</option>
<option value="F">Female</option></select>

as you can see, it is randomly selecting Male. Alsow, I notice that, last time I fill the form I set it to Male before hitting submit. May be is it caching the selection?

Here is the .cs:

protected void LoadGenders(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            ((DropDownList)sender).Items.AddRange(Constants.GenderWithSelect);
        }
public static ListItem[] GenderWithSelect = (new[] { new ListItem("--Select Gender--", "-1") }).Concat(Gender).ToArray();
 public static ListItem[] Gender = new[]
                                              {
                                                  (new ListItem("Male","M")),
                                                  (new ListItem("Female","F"))
                                              };

Body:
I tried your code, and it appears that the generated html didn't have the correct field bound to the "value" of the select options.

What you must get must have this format :

<select name="ctl00$MainContent$ddlGender" id="MainContent_ddlGender" class="select_Box">
  <option selected="selected" value="-1">not set</option>
  <option value="0">0</option>
  <option value="1">1</option>
</select>

In order to have this, I had to set the DataValueField of the DropDownList:

<asp:DropDownList ID="ddlGender" runat="server" CssClass="select_Box" OnPreRender="ddlGender_PreRender" DataValueField="Value" DataTextField="Text">

(Just replace the DataTextField and DataValueField with the name of the properties of your class)


问:
How to list all files in a folder which end with ".dat" with recent changes (datetime)
```<code>private static void listofRecentFile() {

        try (Stream<Path> walk = Files.walk(Paths.get("C:\\DEV\\PrismaGateway\\Service\\"))) {

            List<Path> result = walk.filter(f -> f.toString().endsWith(".dat")).filter(Files::getLastModifiedTime).collect(Collectors.toList());

            result.forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
</code>```

What I want to achieve is I want to list all .dat file that just changed or recent changes, if in the folder there are 10 files but just 3 that I change that means it will show that 3 files only.

example:

```<code>|folder_a|   date   |<br>
|  a.dat |22/01/2020|<br>
|  b.dat |20/01/2020|<br>
|  c.dat |20/01/2020|<br>
|  d.dat |22/01/2020|<br>
|  e.dat |13/01/2020|<br>
|  f.txt |22/01/2020|<br>
</code>```

the program will find .dat the file that has recent date change which is 22 January 2020 like below:

```<code>a.dat 22/01/2020 <br>
d.dat 22/01/2020
</code>```

until now I just could list .dat file but still figuring out how to show the date/recent changes. can someone help me:")

答:
```<code>List<Object> result = walk.filter(f -> f.toString().endsWith(".dat")).collect(Collectors.toList());
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            for (int i = 0; i < result.size(); i++) {
                File file = new File(result.get(i).toString());
                for (Date date = day; !date.after(localDate); date = DateUtils.addDays(date, 1)) {
                    if (sdf.format(file.lastModified()).equals(sdf.format(date))) {
                        temp.append(file.getAbsolutePath() + ";");
                        totalDat++;
                    }
                }
            }
</code>```

this could be more good just compare it and use temp string builder in it

Body:
private static void listofRecentFile() {

        try (Stream<Path> walk = Files.walk(Paths.get("C:\\DEV\\PrismaGateway\\Service\\"))) {

            List<Path> result = walk.filter(f -> f.toString().endsWith(".dat")).filter(Files::getLastModifiedTime).collect(Collectors.toList());

            result.forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

What I want to achieve is I want to list all .dat file that just changed or recent changes, if in the folder there are 10 files but just 3 that I change that means it will show that 3 files only.

example:

|folder_a|   date   |

|  a.dat |22/01/2020|

|  b.dat |20/01/2020|

|  c.dat |20/01/2020|

|  d.dat |22/01/2020|

|  e.dat |13/01/2020|

|  f.txt |22/01/2020|

the program will find .dat the file that has recent date change which is 22 January 2020 like below:

a.dat 22/01/2020

d.dat 22/01/2020

until now I just could list .dat file but still figuring out how to show the date/recent changes. can someone help me:")

Body:
List<Object> result = walk.filter(f -> f.toString().endsWith(".dat")).collect(Collectors.toList());
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            for (int i = 0; i < result.size(); i++) {
                File file = new File(result.get(i).toString());
                for (Date date = day; !date.after(localDate); date = DateUtils.addDays(date, 1)) {
                    if (sdf.format(file.lastModified()).equals(sdf.format(date))) {
                        temp.append(file.getAbsolutePath() + ";");
                        totalDat++;
                    }
                }
            }

this could be more good just compare it and use temp string builder in it


问:
CSS Label background Color setting - Only apply background color to Label Length
Need help with Label background setting. Below is my code which I am using . Please help me to get expected output as below mentioned image.

$header=@"

"@

ConvertTo-Html -body "

 Database Consolidated Health Check Report
" |`
 Out-File  C:\Temp\ConsolidatedReport.html ```

Current Output:

Expecting Output:

答:
Its due to block property of h1 tag ,Using display:table you can
  achieve desire result

$header=@"

"@

ConvertTo-Html -body "

 Database Consolidated Health Check Report
" |`
 Out-File  C:\Temp\ConsolidatedReport.html```

Body:
Need help with Label background setting. Below is my code which I am using . Please help me to get expected output as below mentioned image.

$header=@"

"@

ConvertTo-Html -body "

 Database Consolidated Health Check Report
" |`
 Out-File  C:\Temp\ConsolidatedReport.html

Current Output:

Expecting Output:

Body:
Its due to block property of h1 tag ,Using display:table you can
  achieve desire result

$header=@"
<style>
@charset "UTF-8";
table
{
font-family:Arial;font-size:1em;width:45%;margin-left:1px; margin-bottom:5px;
border-collapse:collapse;
}
td
{
font-size:1em;text-align:center;font-family:Arial;font-weight:normal;
border:0.8px solid MignightBlue;
padding:0px 0px 0px 0px;padding-bottom:5px;
}
th
{
font-size:1.2em;font-weight:normal;
text-align:center;
margin-bottom:0px;
padding-top:0px;
padding-bottom:0px;
padding-right:0px;
padding-left:0px;
background-color:DarkslateGray;
color:snow;
}
name tr
{
color:#F00000;
background-color:snow;font-size:0.8em;font-family:Arial;
}
h1{
 display: table;
 padding: 0 10px;
}
</style>
"@

ConvertTo-Html -body "<H1 style=color:snow;font-weight:normal;background-color:DarkslateGray;font-size:1.5em;font-family:Arial;text-align:left;background-repeat:no-repeat;background-size:100%>
 Database Consolidated Health Check Report </H1>" |`
 Out-File  C:\Temp\ConsolidatedReport.html


问:
Build ASP.NET Web Api to a different output directory
I have a ASP.NET web api project, the api has lot of dependencies to other dlls so we have placed all the dlls in a specific folder. If I point output path of the web api to that output directory and execute in IISExpress it gives following error

Parser Error Message: The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" could not be located.

If we see file location of the error it is still pointing to WebAPI_SourceCode_Directory\web.config and not my output folder. But output folder has web.config file. How can I make the web app to run from output folder using IISExpress

答:
do not use IIS express for development, use a proper IIS instead. This way you will iron out any production issues from the beginning.

Whether your API has a lot of dll dependencies or not, it makes no difference. The API needs to know where to get them from and I wouldn't change the default behavior. They will be in the bin folder like all the other dependencies when you build the project.

To deploy the API even in a local environment, use the Publish method to a local folder, then build an IIS application pointing to that folder.

That's all you need to do, so why complicate things? You can still publish in debug mode, you can still connect your Visual studio to it and debug it properly. There is literally zero need to fight the default way of doing things.


问:
Emgucv ver 4.2 on Azure Function
I want to use EmguCv ver 4.2 in an Azure Function V3

I have created an Azure Function v3(.Net Core) application

Installed Emgu.Cv ver 4.2.0.3636 from Nuget

Installed Emgu.CV.Runtime.windows ver 4.2.0.3636 also from Nuget

```<code>[FunctionName("Function1")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        try
        {
            SetPathOfEmgu();
            var image = new Image<Bgr, byte>(256, 256);
        }
        catch (Exception ee)
        {
            return (ActionResult)new BadRequestObjectResult(ee.Message);
            throw;
        }

        return (ActionResult)new OkObjectResult($"All is well");
    }

    public static void SetPathOfEmgu()
    {
        string pathValue = System.Environment.GetEnvironmentVariable("PATH");
        string emguPath = @"D:\home\site\wwwroot\x64";
        var paths = pathValue.Split(';').Where(o => o != "").ToList();
        paths.Add(emguPath);
        pathValue = string.Join(";", paths.Distinct().ToArray()) + ";";

        System.Environment.SetEnvironmentVariable("PATH", pathValue);
    }
</code>```

Running in Debug i get:"All is well"

Running on Azure i get:"Unable to load DLL 'cvextern' or one of its dependencies: The specified module could not be found. (0x8007007E)"
at line "var image = new Image(256, 256);"

Question: How do I run Emgucv from Azure Function V3?

@Stuard:
From:Emgu 42 Function V3.deps.json

```<code>{
  "runtimeTarget": {
    "name": ".NETCoreApp,Version=v3.0",
    "signature": ""
  },
  "compilationOptions": {},
  "targets": {
    ".NETCoreApp,Version=v3.0": {
      "Emgu 42 Function V3/1.0.0": {
        "dependencies": {
          "Emgu.CV": "4.2.0.3636",
          "Emgu.CV.runtime.windows": "4.2.0.3636",
          "Microsoft.NET.Sdk.Functions": "3.0.1"
        },
        "runtime": {
          "Emgu 42 Function V3.dll": {}
        }
      },
      "Emgu.CV/4.2.0.3636": {
        "runtime": {
          "lib/netstandard2.0/Emgu.CV.World.NetStandard.dll": {
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "1.0.0.0"
          }
        }
      },
      "Emgu.CV.runtime.windows/4.2.0.3636": {
        "dependencies": {
          "Emgu.CV": "4.2.0.3636"
        }
      },
</code>```

答:
It seems Azure function doesn't support Emgu well, but according to some test I found a workaround which may help your problem. Please refer to the steps below and have a try.

1. Go to this link (you may need to register an account and then sign in), it will download a sample of project(which named "A_Basic_Program_x86").

2. Create a new azure function on Azure portal and open "kudu" by clicking "Advanced tools (Kudu)"

3. Then in kudu page, click "Debug console" --> "CMD" -- "site" --> "wwwroot" then create a new folder named "bin" under the "wwwroot" directory.

4. Open the project sample which we downloaded above, we can find some dll files in the directory of A_Basic_Program_x86\My Simple EMGU Program x86\My Simple EMGU Program\My EMGU Program\bin\Debug. In this directory, there are three dll files which are helpful to us. They are Emgu.CV.dll, Emgu.CV.UI.dll and Emgu.Util.dll.

5. Now, go to the "bin" folder which we create under the "wwwroot" directory and drag these three dll files from local into it.(shown as below screenshot)

6. Come back to the project sample and go to the directory of A_Basic_Program_x86\My Simple EMGU Program x86\My Simple EMGU Program\My EMGU Program. We can find two dll files named opencv_core231.dll and opencv_imgproc231.dll. Repeat the step5 above, drag these two dll files to the "bin" folder. These two dll files are also shown in the screenshot I provided above.

7. Create a http trigger function in your function app and please refer to my code below (please notice the code in red box):

Here provide the code same with the screenshot above for you to copy.

```<code>#r "Newtonsoft.Json"
#r "..\bin\Emgu.CV.dll"
#r "..\bin\Emgu.CV.UI.dll"
#r "..\bin\Emgu.Util.dll"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Emgu.CV;
using Emgu.Util;
using Emgu.CV.Structure;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    Image<Bgr, byte> image = new Image<Bgr, byte>(256, 256);

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    return name != null
        ? (ActionResult)new OkObjectResult($"Hello, {name}")
        : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
</code>```

Now we can use "Image" and "Bgr" in azure function without any error message.

Hope it helps~

Title: Emgucv ver 4.2 on Azure Function

Body:
I want to use EmguCv ver 4.2 in an Azure Function V3

I have created an Azure Function v3(.Net Core) application

Installed Emgu.Cv ver 4.2.0.3636 from Nuget

Installed Emgu.CV.Runtime.windows ver 4.2.0.3636 also from Nuget

[FunctionName("Function1")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        try
        {
            SetPathOfEmgu();
            var image = new Image<Bgr, byte>(256, 256);
        }
        catch (Exception ee)
        {
            return (ActionResult)new BadRequestObjectResult(ee.Message);
            throw;
        }

        return (ActionResult)new OkObjectResult($"All is well");
    }

    public static void SetPathOfEmgu()
    {
        string pathValue = System.Environment.GetEnvironmentVariable("PATH");
        string emguPath = @"D:\home\site\wwwroot\x64";
        var paths = pathValue.Split(';').Where(o => o != "").ToList();
        paths.Add(emguPath);
        pathValue = string.Join(";", paths.Distinct().ToArray()) + ";";

        System.Environment.SetEnvironmentVariable("PATH", pathValue);
    }

Running in Debug i get:"All is well"

Running on Azure i get:"Unable to load DLL 'cvextern' or one of its dependencies: The specified module could not be found. (0x8007007E)"
at line "var image = new Image(256, 256);"

Question: How do I run Emgucv from Azure Function V3?

@Stuard:
From:Emgu 42 Function V3.deps.json

{
  "runtimeTarget": {
    "name": ".NETCoreApp,Version=v3.0",
    "signature": ""
  },
  "compilationOptions": {},
  "targets": {
    ".NETCoreApp,Version=v3.0": {
      "Emgu 42 Function V3/1.0.0": {
        "dependencies": {
          "Emgu.CV": "4.2.0.3636",
          "Emgu.CV.runtime.windows": "4.2.0.3636",
          "Microsoft.NET.Sdk.Functions": "3.0.1"
        },
        "runtime": {
          "Emgu 42 Function V3.dll": {}
        }
      },
      "Emgu.CV/4.2.0.3636": {
        "runtime": {
          "lib/netstandard2.0/Emgu.CV.World.NetStandard.dll": {
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "1.0.0.0"
          }
        }
      },
      "Emgu.CV.runtime.windows/4.2.0.3636": {
        "dependencies": {
          "Emgu.CV": "4.2.0.3636"
        }
      },

Body:
It seems Azure function doesn't support Emgu well, but according to some test I found a workaround which may help your problem. Please refer to the steps below and have a try.

1. Go to this link (you may need to register an account and then sign in), it will download a sample of project(which named "A_Basic_Program_x86").

2. Create a new azure function on Azure portal and open "kudu" by clicking "Advanced tools (Kudu)"

3. Then in kudu page, click "Debug console" --> "CMD" -- "site" --> "wwwroot" then create a new folder named "bin" under the "wwwroot" directory.

4. Open the project sample which we downloaded above, we can find some dll files in the directory of A_Basic_Program_x86\My Simple EMGU Program x86\My Simple EMGU Program\My EMGU Program\bin\Debug. In this directory, there are three dll files which are helpful to us. They are Emgu.CV.dll, Emgu.CV.UI.dll and Emgu.Util.dll.

5. Now, go to the "bin" folder which we create under the "wwwroot" directory and drag these three dll files from local into it.(shown as below screenshot)

6. Come back to the project sample and go to the directory of A_Basic_Program_x86\My Simple EMGU Program x86\My Simple EMGU Program\My EMGU Program. We can find two dll files named opencv_core231.dll and opencv_imgproc231.dll. Repeat the step5 above, drag these two dll files to the "bin" folder. These two dll files are also shown in the screenshot I provided above.

7. Create a http trigger function in your function app and please refer to my code below (please notice the code in red box):

Here provide the code same with the screenshot above for you to copy.

#r "Newtonsoft.Json"
#r "..\bin\Emgu.CV.dll"
#r "..\bin\Emgu.CV.UI.dll"
#r "..\bin\Emgu.Util.dll"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Emgu.CV;
using Emgu.Util;
using Emgu.CV.Structure;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    Image<Bgr, byte> image = new Image<Bgr, byte>(256, 256);

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    return name != null
        ? (ActionResult)new OkObjectResult($"Hello, {name}")
        : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}

Now we can use "Image" and "Bgr" in azure function without any error message.

Hope it helps~


答:
Simplest solution is Use span inside h1 tag

h1 span{
background: #e3e3e3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1><span>Database Consolidated Health Check Report</span></h1></code>```

Title: CSS Label background Color setting - Only apply background color to Label Length

Body:
Simplest solution is Use span inside h1 tag

h1 span{
background: #e3e3e3;
}

<h1><span>Database Consolidated Health Check Report</span></h1>


问:
Laravel stripe validation
Hello i am using stripe package(composer require stripe/stripe-php) for integrate stripe payment getaway in my website. I am using this code for charge user.

```<code>   public function stripe(Request $request){
    $customer = json_decode(Session::get('customer'));
    if (Cart::getContent() == null || $customer == null){
        return redirect()->back();
    }
    $cartCollection = Cart::getContent();
    $shippingCost=0;
    foreach ($cartCollection as $getSingleCartProduct){
        $shippingCost += $getSingleCartProduct->attributes->unit_charge;
    }
    $total_price =Cart::getSubTotal()+$shippingCost;

    $error = '';
    $success = '';
    $currency = Currency::find('1');

    Stripe::setApiKey("sk_live_xxxxxxxxxxxxxxxxxxxxxxxx");
    if (Cart::getContent()){
        $charge = Charge::create([
            'amount' => $total_price * 100,
            'currency' => 'usd',
            'source' => $request->stripeToken,
            'receipt_email' => $request->email,
        ]);
    }

    $cartCollections= Cart::getContent();
    foreach ($cartCollections as $cartCollection){
        $order = new Order();
        $order->name = $cartCollection->name;
        $order->price = $cartCollection->price;
        $order->quantity = $cartCollection->quantity;
        $order->image = $cartCollection->attributes->image;
        $order->product_id = $cartCollection->attributes->product_id;
        $order->unit_charge = $cartCollection->attributes->unit_charge;
        $order->curier_id = $cartCollection->attributes->curier_id;
        $order->seller_id = $cartCollection->attributes->seller_id;
        $order->buyer_id = \Illuminate\Support\Facades\Auth::user()->id;
        $order->color = $cartCollection->attributes->color;
        $order->size = $cartCollection->attributes->size;
        $order->color_image = $cartCollection->attributes->color_image;

        $order->first_name = $customer->first_name;
        $order->last_name = $customer->last_name;
        $order->email = $customer->email;
        $order->address1 = $customer->address1;
        $order->address2 = $customer->address2;
        $order->country = $customer->country;
        $order->state = $customer->state;
        $order->zip = $customer->zip;
        $order->payment_status = $customer->payment_status;
        $order->status ='0';
        $order->save();
    }
    if ($order->save()){
        $delete_carts = Cart::getContent();
        foreach ($delete_carts as $delete_cart){
            Cart::remove($delete_cart->id);
        }
        return redirect()->route('charge.complete')->with('success', 'Yor order successfully placed');
    }else{
        return redirect()->route('charge.complete')->with('success', 'Invalid Activity!');
    }
}
</code>```

It will work when the card is valid, have sufficient amount. But when the card is invalid i can't show it. Laravel showing it's default error(card not have sufficient balance)
here is my full code

答:
I have refactored some of your code, reused the fetched Cart::getContent and added some error handling. Hopefully this error handling will give you more control when it comes to displaying the errors the way you like.

```<code>public function stripe(Request $request) {
    $cartCollections = Cart::getContent();
    $customer = json_decode(Session::get('customer'));

    if ($cartCollections == null || $customer == null) {
        return redirect()->back()->withErrors(['msg', 'Your session has expired']);
    }

    $shippingCost = 0;

    foreach ($cartCollections as $cartCollection) {
        $shippingCost += $cartCollection->attributes->unit_charge;
    }

    $total_price = Cart::getSubTotal() + $shippingCost;

    $currency = Currency::find(1);

    Stripe::setApiKey("XXXXXXXXXXXXXXXXXXXXXXXX");

    try {
        $charge = Charge::create([
            'amount' => $total_price * 100,
            'currency' => 'usd',
            'source' => $request->stripeToken,
            'receipt_email' => $request->email,
        ]);

        foreach ($cartCollections as $cartCollection) {
            $order = new Order();
            $order->name = $cartCollection->name;
            $order->price = $cartCollection->price;
            $order->quantity = $cartCollection->quantity;
            $order->image = $cartCollection->attributes->image;
            $order->product_id = $cartCollection->attributes->product_id;
            $order->unit_charge = $cartCollection->attributes->unit_charge;
            $order->curier_id = $cartCollection->attributes->curier_id;
            $order->seller_id = $cartCollection->attributes->seller_id;
            $order->buyer_id = \Illuminate\Support\Facades\Auth::user()->id;
            $order->color = $cartCollection->attributes->color;
            $order->size = $cartCollection->attributes->size;
            $order->color_image = $cartCollection->attributes->color_image;

            $order->first_name = $customer->first_name;
            $order->last_name = $customer->last_name;
            $order->email = $customer->email;
            $order->address1 = $customer->address1;
            $order->address2 = $customer->address2;
            $order->country = $customer->country;
            $order->state = $customer->state;
            $order->zip = $customer->zip;
            $order->payment_status = $customer->payment_status;
            $order->status ='0';
            $order->save();
        }

        if ($order->save()) {
            foreach ($cartCollections as $cartCollection) {
                Cart::remove($cartCollection->id);
            }

            return redirect()->route('charge.complete')->with('success', 'Yor order successfully placed');
        }

        return redirect()->route('charge.complete')->withErrors(['msg', 'Invalid Activity!']);

    } catch (Error\Base $e) {
        // change to the route you want to display error
        return redirect()->route('charge.complete')->withErrors(['msg', $e->getMessage()]);

    } catch (Exception $e) {
        // change to the route you want to display error
        return redirect()->route('charge.complete')->withErrors(['msg', $e->getMessage()]);
    }
}
</code>```

In your view, add the following snippet to display the error message:

```<code>@if($errors->any())
<p>Error: {{$errors->first()}}</p>
@endif
</code>```

If you want to handle more possible exceptions, you can take a look at the available exception types in Stripe's documentation: https://stripe.com/docs/api/errors/handling

Title: Laravel stripe validation

Body:
Hello i am using stripe package(composer require stripe/stripe-php) for integrate stripe payment getaway in my website. I am using this code for charge user.

   public function stripe(Request $request){
    $customer = json_decode(Session::get('customer'));
    if (Cart::getContent() == null || $customer == null){
        return redirect()->back();
    }
    $cartCollection = Cart::getContent();
    $shippingCost=0;
    foreach ($cartCollection as $getSingleCartProduct){
        $shippingCost += $getSingleCartProduct->attributes->unit_charge;
    }
    $total_price =Cart::getSubTotal()+$shippingCost;

    $error = '';
    $success = '';
    $currency = Currency::find('1');

    Stripe::setApiKey("sk_live_xxxxxxxxxxxxxxxxxxxxxxxx");
    if (Cart::getContent()){
        $charge = Charge::create([
            'amount' => $total_price * 100,
            'currency' => 'usd',
            'source' => $request->stripeToken,
            'receipt_email' => $request->email,
        ]);
    }

    $cartCollections= Cart::getContent();
    foreach ($cartCollections as $cartCollection){
        $order = new Order();
        $order->name = $cartCollection->name;
        $order->price = $cartCollection->price;
        $order->quantity = $cartCollection->quantity;
        $order->image = $cartCollection->attributes->image;
        $order->product_id = $cartCollection->attributes->product_id;
        $order->unit_charge = $cartCollection->attributes->unit_charge;
        $order->curier_id = $cartCollection->attributes->curier_id;
        $order->seller_id = $cartCollection->attributes->seller_id;
        $order->buyer_id = \Illuminate\Support\Facades\Auth::user()->id;
        $order->color = $cartCollection->attributes->color;
        $order->size = $cartCollection->attributes->size;
        $order->color_image = $cartCollection->attributes->color_image;

        $order->first_name = $customer->first_name;
        $order->last_name = $customer->last_name;
        $order->email = $customer->email;
        $order->address1 = $customer->address1;
        $order->address2 = $customer->address2;
        $order->country = $customer->country;
        $order->state = $customer->state;
        $order->zip = $customer->zip;
        $order->payment_status = $customer->payment_status;
        $order->status ='0';
        $order->save();
    }
    if ($order->save()){
        $delete_carts = Cart::getContent();
        foreach ($delete_carts as $delete_cart){
            Cart::remove($delete_cart->id);
        }
        return redirect()->route('charge.complete')->with('success', 'Yor order successfully placed');
    }else{
        return redirect()->route('charge.complete')->with('success', 'Invalid Activity!');
    }
}

It will work when the card is valid, have sufficient amount. But when the card is invalid i can't show it. Laravel showing it's default error(card not have sufficient balance)
here is my full code

Body:
I have refactored some of your code, reused the fetched Cart::getContent and added some error handling. Hopefully this error handling will give you more control when it comes to displaying the errors the way you like.

public function stripe(Request $request) {
    $cartCollections = Cart::getContent();
    $customer = json_decode(Session::get('customer'));

    if ($cartCollections == null || $customer == null) {
        return redirect()->back()->withErrors(['msg', 'Your session has expired']);
    }

    $shippingCost = 0;

    foreach ($cartCollections as $cartCollection) {
        $shippingCost += $cartCollection->attributes->unit_charge;
    }

    $total_price = Cart::getSubTotal() + $shippingCost;

    $currency = Currency::find(1);

    Stripe::setApiKey("XXXXXXXXXXXXXXXXXXXXXXXX");

    try {
        $charge = Charge::create([
            'amount' => $total_price * 100,
            'currency' => 'usd',
            'source' => $request->stripeToken,
            'receipt_email' => $request->email,
        ]);

        foreach ($cartCollections as $cartCollection) {
            $order = new Order();
            $order->name = $cartCollection->name;
            $order->price = $cartCollection->price;
            $order->quantity = $cartCollection->quantity;
            $order->image = $cartCollection->attributes->image;
            $order->product_id = $cartCollection->attributes->product_id;
            $order->unit_charge = $cartCollection->attributes->unit_charge;
            $order->curier_id = $cartCollection->attributes->curier_id;
            $order->seller_id = $cartCollection->attributes->seller_id;
            $order->buyer_id = \Illuminate\Support\Facades\Auth::user()->id;
            $order->color = $cartCollection->attributes->color;
            $order->size = $cartCollection->attributes->size;
            $order->color_image = $cartCollection->attributes->color_image;

            $order->first_name = $customer->first_name;
            $order->last_name = $customer->last_name;
            $order->email = $customer->email;
            $order->address1 = $customer->address1;
            $order->address2 = $customer->address2;
            $order->country = $customer->country;
            $order->state = $customer->state;
            $order->zip = $customer->zip;
            $order->payment_status = $customer->payment_status;
            $order->status ='0';
            $order->save();
        }

        if ($order->save()) {
            foreach ($cartCollections as $cartCollection) {
                Cart::remove($cartCollection->id);
            }

            return redirect()->route('charge.complete')->with('success', 'Yor order successfully placed');
        }

        return redirect()->route('charge.complete')->withErrors(['msg', 'Invalid Activity!']);

    } catch (Error\Base $e) {
        // change to the route you want to display error
        return redirect()->route('charge.complete')->withErrors(['msg', $e->getMessage()]);

    } catch (Exception $e) {
        // change to the route you want to display error
        return redirect()->route('charge.complete')->withErrors(['msg', $e->getMessage()]);
    }
}

In your view, add the following snippet to display the error message:

@if($errors->any())
<p>Error: {{$errors->first()}}</p>
@endif

If you want to handle more possible exceptions, you can take a look at the available exception types in Stripe's documentation: https://stripe.com/docs/api/errors/handling


问:
Laravel update eloquent not updating the record
I am using Laravel eloquent to update the record. The problem is the update method returns the integer equal to number of records should be updated but this update is not being reflected in database.

I inserted some records to check there is no database mismatch.

I am even using fillable method and defined every column into it.

Here is my code.

Modal

```<code>protected $fillable = [
        'id',
        'user_id',
        'ticket_no',
        'partner_id',
        'partner_user_name',
        'partner_user_email',
        'partner_user_contact',
        'contacted_for_id',
        'issue_type_id',
        'comm_mode_id',
        'opened_by_id',
        'assigned_to_id',
        'team_id',
        'priority_id',
        'opened_date',
        'tat_id',
        'resolved_date',
        'status_id',
        'description',
    ];
</code>```

Controller

```<code>public function update(Request $request)
    {
        $validators = Validator::make($request->all(), [
            'assigned_to_id' => 'required',
            'team_id' => 'required',
            'resolve_date' => 'required',
            'status_id' => 'required',
            'description' => 'required',
        ]);

        if ($validators->fails()) {
            $data['result'] = false;
            $data['messages'] = $validators->errors()->first();

            return json_encode($data);
        }

        $assigned_to_id = $request->assigned_to_id;
        $team_id = $request->team_id;
        $resolve_date = $request->resolve_date;
        $status_id = $request->status_id;
        $description = $request->description;

        $ticket_row_id = $request->ticket_row_id;

        $updated = TICKET_TRACKER::where('id', $ticket_row_id)
            ->update(
                ['assigned_to_id' => $assigned_to_id],
                ['team_id' => $team_id],
                ['resolve_date' => $resolve_date],
                ['status_id' => $status_id],
                ['description' => $description]
            );
    }
</code>```

I am not getting any error that's the most frustrated thing.

答:
In order to make your model to be updated change:

 $updated = TICKET_TRACKER::where('id', $ticket_row_id)
            ->update(
                ['assigned_to_id' => $assigned_to_id],
                ['team_id' => $team_id],
                ['resolve_date' => $resolve_date],
                ['status_id' => $status_id],
                ['description' => $description]
            );
```

<p>By:</p>

<pre class="lang-php prettyprint-override"><code> $updated = TICKET_TRACKER::where('id', $ticket_row_id)
       ->update([
                 'assigned_to_id' => $assigned_to_id,
                 'team_id' => $team_id,
                 'resolve_date' => $resolve_date,
                 'status_id' => $status_id,
                 'description' => $description
          ]);
</code>```

In fact you need to have only one array with keys and values in order to view your model updated.

[EDIT 1]

As said in the comments in Laravel you need to take care about naming conventions,

If the name of the model is TicketTracker, the name of the table should be plural. So it will be ticket_trackers.

or if you want to have a custom name for your table you can configure in your model the $table property as follows:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class TicketTracker extends Model
{
    protected $table = "other_table_name"
}
```

Body:
I am using Laravel eloquent to update the record. The problem is the update method returns the integer equal to number of records should be updated but this update is not being reflected in database.

I inserted some records to check there is no database mismatch.

I am even using fillable method and defined every column into it.

Here is my code.

Modal

protected $fillable = [
        'id',
        'user_id',
        'ticket_no',
        'partner_id',
        'partner_user_name',
        'partner_user_email',
        'partner_user_contact',
        'contacted_for_id',
        'issue_type_id',
        'comm_mode_id',
        'opened_by_id',
        'assigned_to_id',
        'team_id',
        'priority_id',
        'opened_date',
        'tat_id',
        'resolved_date',
        'status_id',
        'description',
    ];

Controller

public function update(Request $request)
    {
        $validators = Validator::make($request->all(), [
            'assigned_to_id' => 'required',
            'team_id' => 'required',
            'resolve_date' => 'required',
            'status_id' => 'required',
            'description' => 'required',
        ]);

        if ($validators->fails()) {
            $data['result'] = false;
            $data['messages'] = $validators->errors()->first();

            return json_encode($data);
        }

        $assigned_to_id = $request->assigned_to_id;
        $team_id = $request->team_id;
        $resolve_date = $request->resolve_date;
        $status_id = $request->status_id;
        $description = $request->description;

        $ticket_row_id = $request->ticket_row_id;

        $updated = TICKET_TRACKER::where('id', $ticket_row_id)
            ->update(
                ['assigned_to_id' => $assigned_to_id],
                ['team_id' => $team_id],
                ['resolve_date' => $resolve_date],
                ['status_id' => $status_id],
                ['description' => $description]
            );
    }

I am not getting any error that's the most frustrated thing.

Body:
In order to make your model to be updated change:

 $updated = TICKET_TRACKER::where('id', $ticket_row_id)
            ->update(
                ['assigned_to_id' => $assigned_to_id],
                ['team_id' => $team_id],
                ['resolve_date' => $resolve_date],
                ['status_id' => $status_id],
                ['description' => $description]
            );

By:

 $updated = TICKET_TRACKER::where('id', $ticket_row_id)
       ->update([
                 'assigned_to_id' => $assigned_to_id,
                 'team_id' => $team_id,
                 'resolve_date' => $resolve_date,
                 'status_id' => $status_id,
                 'description' => $description
          ]);

In fact you need to have only one array with keys and values in order to view your model updated.

[EDIT 1]

As said in the comments in Laravel you need to take care about naming conventions,

If the name of the model is TicketTracker, the name of the table should be plural. So it will be ticket_trackers.

or if you want to have a custom name for your table you can configure in your model the $table property as follows:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class TicketTracker extends Model
{
    protected $table = "other_table_name"
}


问:
Simulate memory warnings from the code, possible?
I know i can simulate a memory warning on the simulator by selecting 'Simulate Memory Warning' from the drop down menu of the iPhone Simulator. I can even make a hot key for that.

But this is not what I'd like to achieve. I'd like to do that from the code by simply, lets say doing it every 5 seconds. Is that possible?

答:
Post a UIApplicationDidReceiveMemoryWarningNotification notification to the default notification center:

```<code>[[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidReceiveMemoryWarningNotification object:nil]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Post a UIApplicationDidReceiveMemoryWarningNotification notification to the default notification center:

[[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidReceiveMemoryWarningNotification object:nil]


问:
Camera is not working in android ionic react app
I have this code it is working in PC browser but in android it will not open the camera. The code is written in ionic framework using React components. The main component which opens camera is as below:

```<code>import React, { useRef, useState,useEffect } from 'react';
import './index.scss';

const CAPTURE_OPTIONS = {
  audio: true,
  video: { facingMode: "user" }
};

const Camera: React.FC = () => {
  const videoRef = useRef<any>(null);

  const [mediaStream, setMediaStream] = useState<any>(null);

  useEffect(() => {
    async function enableStream() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia(CAPTURE_OPTIONS);
        setMediaStream(stream);
      } catch (err) {
        // Removed for brevity
      }
    }

    if (!mediaStream) {
      enableStream();
    } else {
      return function cleanup() {
        mediaStream.getTracks().forEach((track: any) => {
          track.stop();
        });
      }
    }
  }, [mediaStream, CAPTURE_OPTIONS]);

  if (mediaStream && videoRef.current && !videoRef.current.srcObject) {
    videoRef.current.srcObject = mediaStream;
  }

  const handleCanPlay = () => {
    videoRef.current.play();
  }

  return (
    <div>
      <video ref={videoRef} onCanPlay={handleCanPlay} autoPlay playsInline loop muted className={"camera"} />
    </div>
  );
}

export default Camera;
</code>```

Does anyone knows that what is the problem  I have this problem for running the code on android capacitor and when I run ionic capacitor run android --livereload --external I cant get sth like below:

答:
When using webrtc and
    navigator.mediaDevices.getUserMedia()
you need to make sure that you are using the adapter.js file.

You can use https://www.npmjs.com/package/webrtc-adapter,
or copy the file from - https://github.com/webrtc/adapter/tree/master/release.
If you want it globally put it in your public folder of your ionic project.

Body:
I have this code it is working in PC browser but in android it will not open the camera. The code is written in ionic framework using React components. The main component which opens camera is as below:

import React, { useRef, useState,useEffect } from 'react';
import './index.scss';

const CAPTURE_OPTIONS = {
  audio: true,
  video: { facingMode: "user" }
};

const Camera: React.FC = () => {
  const videoRef = useRef<any>(null);

  const [mediaStream, setMediaStream] = useState<any>(null);

  useEffect(() => {
    async function enableStream() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia(CAPTURE_OPTIONS);
        setMediaStream(stream);
      } catch (err) {
        // Removed for brevity
      }
    }

    if (!mediaStream) {
      enableStream();
    } else {
      return function cleanup() {
        mediaStream.getTracks().forEach((track: any) => {
          track.stop();
        });
      }
    }
  }, [mediaStream, CAPTURE_OPTIONS]);

  if (mediaStream && videoRef.current && !videoRef.current.srcObject) {
    videoRef.current.srcObject = mediaStream;
  }

  const handleCanPlay = () => {
    videoRef.current.play();
  }

  return (

      <video ref={videoRef} onCanPlay={handleCanPlay} autoPlay playsInline loop muted className={"camera"} />

  );
}

export default Camera;

Does anyone knows that what is the problem  I have this problem for running the code on android capacitor and when I run ionic capacitor run android --livereload --external I cant get sth like below:


问:
How to display filenames of word documents in a folder using python?
I want to display the filenames of word document present in a specified path using python.</p>

答:
An alternative for @sxeros approach :)</p>

```<code>import os

PATH = "your path"

files = list(filter(lambda s: ".doc" in s or ".docx" in s, os.listdir(PATH)))

print(files)
</code>```

Body:
An alternative for @sxeros approach :)

import os

PATH = "your path"

files = list(filter(lambda s: ".doc" in s or ".docx" in s, os.listdir(PATH)))

print(files)


问:
gcloud snapshot all disks attached to an instance
I'm using the gcloud cli api and I'm trying to write a script that creates a snapshot of all disks attached to an instance.

My problem is that the snapshot cli command requires the name of the disk however when I ask gcloud for a list of disks attached to an instance it doesn't (directly) give me the disk name.

If I run:
gcloud compute instances list  --format=json

I get a json array of disks which includes the deviceName but not the name.
I do note that the array includes a 'source' attribute which contains a url which does end with the diskname.
However I'm concerned that parsing the diskname from the url won't provide a stable solution.

So what is the correct way to obtain the disk names?

答:
Did you tired:

```<code>gcloud compute disks list --format=json ?
</code>```

I don't know if it can be listed by instance, but it contains information by which instance particular disc is used (reference)

I hope it will help!

Body:
Did you tired:

gcloud compute disks list --format=json ?

I don't know if it can be listed by instance, but it contains information by which instance particular disc is used (reference)

I hope it will help!


问:
No NSEntityDescriptions in any model claim the NSManagedObject subclass
I am new to CoreData and I'm trying to create a caching mechanism wherein after parsing objects from the API, I save them to the data model then fetch it again to show it on the tableview. I'm trying to fetch it using NSFetchedResultsController. Upon initialization of the NSFetchedResultsController, I'm encountering this runtime exception:

```<code>2018-12-09 15:03:20.493509+0800 [5184:148001] [error] error:
No NSEntityDescriptions in any model claim the NSManagedObject subclass
'Product' so +entity is confused.  Have you loaded your
NSManagedObjectModel yet ?
CoreData: error: No NSEntityDescriptions in any model claim the
NSManagedObject subclass 'Product' so +entity is confused.  Have you
loaded your NSManagedObjectModel yet ?
2018-12-09 15:03:20.493718+0800[5184:148001] [error] error: +
[Product entity] Failed to find a unique match for an
NSEntityDescription to a managed object subclass
CoreData: error: +[Product entity] Failed to find a unique match for an
NSEntityDescription to a managed object subclass
</code>```

What could be the reason why?

答:
If you ever encounter an issue similar to this using SwiftUI, you can try changing the entity's class module from Global Namespace to Current Product Module.

Go to your xcdatamodeld file and select the problematic entity. Then in the data model inspector, change the Module field from the default Global namespace to available value "Current Product Module" by clicking on the arrow at the right of the field.

This allowed my app to compile without encountering the error.

Body:
I am new to CoreData and I'm trying to create a caching mechanism wherein after parsing objects from the API, I save them to the data model then fetch it again to show it on the tableview. I'm trying to fetch it using NSFetchedResultsController. Upon initialization of the NSFetchedResultsController, I'm encountering this runtime exception:

2018-12-09 15:03:20.493509+0800 [5184:148001] [error] error:
No NSEntityDescriptions in any model claim the NSManagedObject subclass
'Product' so +entity is confused.  Have you loaded your
NSManagedObjectModel yet ?
CoreData: error: No NSEntityDescriptions in any model claim the
NSManagedObject subclass 'Product' so +entity is confused.  Have you
loaded your NSManagedObjectModel yet ?
2018-12-09 15:03:20.493718+0800[5184:148001] [error] error: +
[Product entity] Failed to find a unique match for an
NSEntityDescription to a managed object subclass
CoreData: error: +[Product entity] Failed to find a unique match for an
NSEntityDescription to a managed object subclass

What could be the reason why?


问:
Trigger an action after selection of certain option from select2 dropdown
I'm using a Select2 dropdown. I want to trigger an event on selection of the Patient option. Right now it fires an event regardless which option is clicked.

```<code>  <div class="col-md-3">
    {!!($errors->has('name')) ? '<div class="form-group has-error">' : '<div class="form-group">'!!}
    {{Form::label('based on', 'Based on:')}}<br>
    {!! Form::select('type', ['' => 'Select type'] + ['0' => 'Image', '1' => 'Patient'], null, ['class' => 'form-control select2', 'id' => 'type',  'style' => 'width: 100%;']) !!}
  </div>
</div>
<div class="col-md-3" id="timeframe-div" style="display: none;">
  {!!($errors->has('name')) ? '<div class="form-group has-error">' : '<div class="form-group">'!!}
  {{Form::label('based on', 'Timeframe:')}}<br>
  {!! Form::select('timeframe', ['' => 'Select type'] + ['0' => 'Daily', '1' => 'Weekly', '2' => 'Monthly'], null, ['class' => 'form-control select2', 'id' => 'timeframe',  'style' => 'width: 100%;']) !!}
</div>
</code>```

$('#type').on("select2:selecting", function(e) {
  $("#timeframe-div").css("display", "block");
});
```

答:
Try this:</p>

```<code>$('#type').change(function() {
  if($('#type option:selected').text() == 'Patient') {
   $("#timeframe-div").css("display", "block");
  }
});
</code>```

Body:
I'm using a Select2 dropdown. I want to trigger an event on selection of the Patient option. Right now it fires an event regardless which option is clicked.

    {!!($errors->has('name')) ? '
' : '
'!!}
    {{Form::label('based on', 'Based on:')}}

    {!! Form::select('type', ['' => 'Select type'] + ['0' => 'Image', '1' => 'Patient'], null, ['class' => 'form-control select2', 'id' => 'type',  'style' => 'width: 100%;']) !!}

  {!!($errors->has('name')) ? '
' : '
'!!}
  {{Form::label('based on', 'Timeframe:')}}

  {!! Form::select('timeframe', ['' => 'Select type'] + ['0' => 'Daily', '1' => 'Weekly', '2' => 'Monthly'], null, ['class' => 'form-control select2', 'id' => 'timeframe',  'style' => 'width: 100%;']) !!}

$('#type').on("select2:selecting", function(e) {
  $("#timeframe-div").css("display", "block");
});

Body:
Try this:

$('#type').change(function() {
  if($('#type option:selected').text() == 'Patient') {
   $("#timeframe-div").css("display", "block");
  }
});


问:
How do I grab an element with jQuery without a way to reference it via class, ID, etc
I have a table like so:

```<code><table>
<thead>
    <tr>
        <th>Hostname</th>
        <th>Action</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>127.0.0.1</td>
        <td><a name="delete" onclick="remove_host('127.0.0.1')">Remove</a></td>
    </tr>
    <tr>
        <td>127.0.0.2</td>
        <td><a name="delete" onclick="remove_host('127.0.0.2')">Remove</a></td>
    </tr>
    <tr>
        <td>127.0.0.3</td>
        <td><a name="delete" onclick="remove_host('127.0.0.3')">Remove</a></td>
    </tr>
</tbody>
</code>```

What I'm trying to do is, when a user clicks on Remove, that the link is replaced with one of those loading images so the user can't repeatedly hit the link.

How do I get the a element, so to speak, so I can set the HTML accordingly with jQuery?

On other parts of the site, I'm able to attach a rel="host-1" (or similar) to the link, so I can easily reference it to change out the HTML.

答:
```<code>$('a[name="delete"]').click(function() {

});
</code>```

EDIT

Don't use inline JS. writing the following is much cleaner.

```<code>$('a[name="delete"]').click(function() {
    var thehost = $(this).parent().prev().html();
    remove_host(thehost);
});
</code>```

Body:
I have a table like so:

        Hostname
        Action

        127.0.0.1
        Remove

        127.0.0.2
        Remove

        127.0.0.3
        Remove

What I'm trying to do is, when a user clicks on Remove, that the link is replaced with one of those loading images so the user can't repeatedly hit the link.

How do I get the a element, so to speak, so I can set the HTML accordingly with jQuery?

On other parts of the site, I'm able to attach a rel="host-1" (or similar) to the link, so I can easily reference it to change out the HTML.

Body:
$('a[name="delete"]').click(function() {

});

EDIT

Don't use inline JS. writing the following is much cleaner.

$('a[name="delete"]').click(function() {
    var thehost = $(this).parent().prev().html();
    remove_host(thehost);
});


问:
When composer connects to GitHub I receive a warning about a deprecation authentication method. What authentication configuration should I use?
GitHub has started sending emails about deprecated authentication but I have not yet found a resource for detailing what composer's auth.json should look like under the new regime.

My requirements are relatively simple - using composer to update a Symfony application in development and occasionally experimenting with other repos.

With this, my original configuration (automatically built)...

```<code>{
    "github-oauth": {
        "github.com": "(a string)"
    }
}
</code>```

... I receive this warning:

...your personal access token...was used as part of a query parameter
  to access an endpoint through the GitHub API...Please use the
  Authorization HTTP header instead...

But when I try with this other configuration:

```<code>{
    "http-basic": {
        "github.com": {
            "username": " my email address",
            "password": " my password "
        }    }
}
</code>```

I receive this other warning:

You recently used a password to access an endpoint through the GitHub
  API using Composer/1.9.1 ...We recommend using a personal access token
  (PAT) with the appropriate scope to access this endpoint instead.

What should it really look like and why am I getting these deprecation warnings?

答:
Update composer and the error will disappear

```<code>php composer.phar self-update
</code>```

or

```<code>composer self-update
</code>```

Body:
GitHub has started sending emails about deprecated authentication but I have not yet found a resource for detailing what composer's auth.json should look like under the new regime.

My requirements are relatively simple - using composer to update a Symfony application in development and occasionally experimenting with other repos.

With this, my original configuration (automatically built)...

{
    "github-oauth": {
        "github.com": "(a string)"
    }
}

... I receive this warning:

...your personal access token...was used as part of a query parameter
  to access an endpoint through the GitHub API...Please use the
  Authorization HTTP header instead...

But when I try with this other configuration:

{
    "http-basic": {
        "github.com": {
            "username": " my email address",
            "password": " my password "
        }    }
}

I receive this other warning:

You recently used a password to access an endpoint through the GitHub
  API using Composer/1.9.1 ...We recommend using a personal access token
  (PAT) with the appropriate scope to access this endpoint instead.

What should it really look like and why am I getting these deprecation warnings?

Body:
Update composer and the error will disappear

php composer.phar self-update

or

composer self-update


问:
MyBatis - No constructor found
I have a problem with MyBatis mapping.
I have a domain class like this:

```<code>public class MyClass
{
   private Long id;
   private Date create;
   private String content;

   MyClass (Long id, Date create, String content)
   {
       this.id = id;
       this.create = create;
       this.content = content;
   }

   //getters and setters
</code>```

A mapper class with a method like this:

```<code>   @Select("SELECT * FROM MyTable WHERE id=#{id}")
   MyClass getMyClass (@Param("id") Long id);
</code>```

In the database the three columns are of type Number, Timestamp and Clob and have the same name as in the class fields.

When I use this method I get a:
ExecutorException: No constructor found in [MyClass; matching [java.math.BigDecimal, java.sql.Timestamp, oracle.jdbc.OracleClob]

But if I remove the constructor from Myclass, then there is no problem at all. I would like to have the constructor, how can I fix it?
I tried adding the @Results annotation in the mapper like so, but it didn't make any difference:

```<code>   @Results(value = {
      @Result(column = "id", property = "id", javaType = Long.class),
      @Result(column = "create", property = "create", javaType = Date.class),
      @Result(column = "content", property = "content", javaType = String.class)
   })
</code>```

答:
Just completing the answer of @Kazuki Shimizu.

If you want to use the primitive type long instead of the wrapper Long in the constructor you need to change the binding to:

```<code>@ConstructorArgs({
   @Arg(column = "id", javaType = long.class)
   ,@Arg(column = "create", javaType = Date.class)
   ,@Arg(column = "content", javaType = String.class)
})
</code>```

Title: MyBatis - No constructor found

Body:
I have a problem with MyBatis mapping.
I have a domain class like this:

public class MyClass
{
   private Long id;
   private Date create;
   private String content;

   MyClass (Long id, Date create, String content)
   {
       this.id = id;
       this.create = create;
       this.content = content;
   }

   //getters and setters

A mapper class with a method like this:

   @Select("SELECT * FROM MyTable WHERE id=#{id}")
   MyClass getMyClass (@Param("id") Long id);

In the database the three columns are of type Number, Timestamp and Clob and have the same name as in the class fields.

When I use this method I get a:
ExecutorException: No constructor found in [MyClass; matching [java.math.BigDecimal, java.sql.Timestamp, oracle.jdbc.OracleClob]

But if I remove the constructor from Myclass, then there is no problem at all. I would like to have the constructor, how can I fix it?
I tried adding the @Results annotation in the mapper like so, but it didn't make any difference:

   @Results(value = {
      @Result(column = "id", property = "id", javaType = Long.class),
      @Result(column = "create", property = "create", javaType = Date.class),
      @Result(column = "content", property = "content", javaType = String.class)
   })

Body:
Just completing the answer of @Kazuki Shimizu.

If you want to use the primitive type long instead of the wrapper Long in the constructor you need to change the binding to:

@ConstructorArgs({
   @Arg(column = "id", javaType = long.class)
   ,@Arg(column = "create", javaType = Date.class)
   ,@Arg(column = "content", javaType = String.class)
})


问:
Generate all combinations of an unknown number of variables
I have a list of variables, the number of which can change. Each variable has a lower limit, upper limit and an increment value. For example:

```<code>variables = {
   "a": [1, 10, 1],
   "b": [50, 200, 5],
   "c": [50, 300, 10]
}
</code>```

Where for key "a", 1 is the lower limit, 10 is the upper limit and 1 is the increment amount.

```<code>"a" would go from 1 through 10, incrementing by 1
"b" would go from 50 through 200, incrementing by 5
"c" would go from 50 through 300, incrementing by 10
... there can be more or less such keys.
</code>```

I need to create a list of all possible combinations of a, b and c, without hard coding nested loops, as there are an unknown number of variables/keys, and just cannot wrap my head around it. I'm using Python 3.7

The output would ideally be a table of combinations of each variable, perhaps comma separated values. For example.

```<code>a  b  c
x  y  z
x  y  z
x  y  z
x  y  z
</code>```

However, anything will do, as long as I can collate the output into a format where each combination can be accessed as a set. Such as a list of tuples.

```<code>[
  (x, y, z)
  (x, y, z)
]
...
</code>```

答:
Here, assuming:

```<code>variables = {
   "a": [1, 10, 1],
   "b": [50, 200, 5],
   "c": [50, 300, 10]
}
</code>```

Then you can create an iterator using itertools:

```<code>from itertools import product, starmap
cartesian_product = product(*starmap(range, variables.values()))
</code>```

Or, just to show you what starmap is doing:

```<code>cartesian_product = product(*(range(*v) for v in variables.values()))
</code>```

Body:
I have a list of variables, the number of which can change. Each variable has a lower limit, upper limit and an increment value. For example:

variables = {
   "a": [1, 10, 1],
   "b": [50, 200, 5],
   "c": [50, 300, 10]
}

Where for key "a", 1 is the lower limit, 10 is the upper limit and 1 is the increment amount.

"a" would go from 1 through 10, incrementing by 1
"b" would go from 50 through 200, incrementing by 5
"c" would go from 50 through 300, incrementing by 10
... there can be more or less such keys.

I need to create a list of all possible combinations of a, b and c, without hard coding nested loops, as there are an unknown number of variables/keys, and just cannot wrap my head around it. I'm using Python 3.7

The output would ideally be a table of combinations of each variable, perhaps comma separated values. For example.

a  b  c
x  y  z
x  y  z
x  y  z
x  y  z

However, anything will do, as long as I can collate the output into a format where each combination can be accessed as a set. Such as a list of tuples.

[
  (x, y, z)
  (x, y, z)
]
...

Body:
Here, assuming:

variables = {
   "a": [1, 10, 1],
   "b": [50, 200, 5],
   "c": [50, 300, 10]
}

Then you can create an iterator using itertools:

from itertools import product, starmap
cartesian_product = product(*starmap(range, variables.values()))

Or, just to show you what starmap is doing:

cartesian_product = product(*(range(*v) for v in variables.values()))