问:
Cumulative Sum of 2 Columns
I am using Postgresql 11.

I have 2 tables - txn_table and summary_table

```<code>create table txn_table(id int, txn_date timestamp, amount decimal);

create table summary_table(id int, txn_date date, day_Total decimal, Cumulative_Total decimal);
</code>```

Sample data for txn_table is

```<code>insert into txn_table values (1, '2020-05-28 10:05:05', 100.00);
insert into txn_table values(2, '2020-05-28 11:45:10', 200.00);
insert into txn_table values(3, '2020-05-29 10:05:05', 300.00);
insert into txn_table values(4, '2020-05-29 12:10:01', 400.00);
</code>```

I want to insert the data in summary_table like below

day_total contains sum of particular day

Cumulative_total contains cumulative sum of day_total

```<code>| id  | txn_date                 | day_total | cumulative_total |
| --- | ------------------------ | --------- | ---------------- |
| 1   | 2020-05-28               | 300       | 300              |
| 2   | 2020-05-29               | 700       | 1000             |
</code>```

答:
I guess this select could solve your problem:

```<code>insert into summary_table
select row_number() over w as id
     , txn_date
     , day_total
     , sum(day_total) over w as cumulative_total
from (
  select txn_date::date as txn_date, sum(amount) as day_total
  from txn_table
  group by txn_date::date
) d
window w as (order by txn_date)
order by txn_date
</code>```

(I worked it out in my head, didn't try. Perhaps prepare db fiddle or CTE with sample input.)

Title: Cumulative Sum of 2 Columns

Body:
I am using Postgresql 11.

I have 2 tables - txn_table and summary_table

create table txn_table(id int, txn_date timestamp, amount decimal);

create table summary_table(id int, txn_date date, day_Total decimal, Cumulative_Total decimal);

Sample data for txn_table is

insert into txn_table values (1, '2020-05-28 10:05:05', 100.00);
insert into txn_table values(2, '2020-05-28 11:45:10', 200.00);
insert into txn_table values(3, '2020-05-29 10:05:05', 300.00);
insert into txn_table values(4, '2020-05-29 12:10:01', 400.00);

I want to insert the data in summary_table like below

day_total contains sum of particular day

Cumulative_total contains cumulative sum of day_total

| id  | txn_date                 | day_total | cumulative_total |
| --- | ------------------------ | --------- | ---------------- |
| 1   | 2020-05-28               | 300       | 300              |
| 2   | 2020-05-29               | 700       | 1000             |

Body:
I guess this select could solve your problem:

insert into summary_table
select row_number() over w as id
     , txn_date
     , day_total
     , sum(day_total) over w as cumulative_total
from (
  select txn_date::date as txn_date, sum(amount) as day_total
  from txn_table
  group by txn_date::date
) d
window w as (order by txn_date)
order by txn_date

(I worked it out in my head, didn't try. Perhaps prepare db fiddle or CTE with sample input.)


来源: stackexchange

问:
How to extract values from pandas Series without index
I have the following when I print my data structure:

print(speed_tf)

44.0   -24.4
45.0   -12.2
46.0   -12.2
47.0   -12.2
48.0   -12.2
Name: Speed, dtype: float64
```

<p>I believe this is a pandas Series but not sure</p>

<p>I do not want the first column at all I just want </p>

<pre class="lang-py prettyprint-override"><code>-24.4
-12.2
-12.2
-12.2
-12.2
</code>```

I tried speed_tf.reset_index()

  index  Speed
0 44.0   -24.4
1 45.0   -12.2
2 46.0   -12.2
3 47.0   -12.2
4 48.0   -12.2
```

How can I just get the Speed values with index starting at 0?

答:
Simply use Series.reset_index and Series.to_frame:

```<code>df = speed_tf.reset_index(drop=True).to_frame()
</code>```

Result:

```<code># print(df)

   Speed
0  -24.4
1  -12.2
2  -12.2
3  -12.2
4  -12.2
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following when I print my data structure:

print(speed_tf)

44.0   -24.4
45.0   -12.2
46.0   -12.2
47.0   -12.2
48.0   -12.2
Name: Speed, dtype: float64

I believe this is a pandas Series but not sure

I do not want the first column at all I just want

-24.4
-12.2
-12.2
-12.2
-12.2

I tried speed_tf.reset_index()

  index  Speed
0 44.0   -24.4
1 45.0   -12.2
2 46.0   -12.2
3 47.0   -12.2
4 48.0   -12.2

How can I just get the Speed values with index starting at 0?

Body:
Simply use Series.reset_index and Series.to_frame:

df = speed_tf.reset_index(drop=True).to_frame()

Result:

# print(df)

   Speed
0  -24.4
1  -12.2
2  -12.2
3  -12.2
4  -12.2


问:
Determine if a member call is virtual in the Clang AST
I'd like to write an analyzer that counts virtual function calls by looking at the C++ AST (output of -ast-dump), but I'm having difficulty determining which function calls are virtual and which are not. Here's an example piece of code:

struct A {
    A() {}
    virtual int foo() { return 0; }
};
struct B : public A {
    B() {}
    //virtual int foo() { return 3; }
};

struct C : public B {
    C() {}
    virtual int foo() { return 1; }
};

int test(C* c) {
    return c->foo() + c->B::foo() + c->A::foo();
}
```

<p>In my initial implementation, I simply check whether or not the function being called is <code>virtual</code> using <code>expr->getMethodDecl()->isVirtual()</code> but (from what I understand) the calls in <code>c->B::foo()</code> and <code>c->A::foo()</code> are not actually <code>virtual</code> so it isn't sufficient to ask if the function being called is <code>virtual</code>.</p>

<p>When I dump the AST from this piece of code, I get the following tree for <code>test</code>:</p>

````-FunctionDecl 0x1d33620 <line:19:1, line:21:1> line:19:5 test 'int (C *)'
  |-ParmVarDecl 0x1d33558 <col:10, col:13> col:13 used c 'C *'
  `-CompoundStmt 0x1d339f0 <col:16, line:21:1>
    `-ReturnStmt 0x1d339e0 <line:20:5, col:47>
      `-BinaryOperator 0x1d339c0 <col:12, col:47> 'int' '+'
        |-BinaryOperator 0x1d338a8 <col:12, col:33> 'int' '+'
        | |-CXXMemberCallExpr 0x1d33778 <col:12, col:19> 'int'
        | | `-MemberExpr 0x1d33748 <col:12, col:15> '<bound member function type>' ->foo 0x1d31c80
        | |   `-ImplicitCastExpr 0x1d33730 <col:12> 'C *' <LValueToRValue>
        | |     `-DeclRefExpr 0x1d33710 <col:12> 'C *' lvalue ParmVar 0x1d33558 'c' 'C *'
        | `-CXXMemberCallExpr 0x1d33848 <col:23, col:33> 'int'
        |   `-MemberExpr 0x1d33800 <col:23, col:29> '<bound member function type>' ->foo 0x1d02400
        |     `-ImplicitCastExpr 0x1d33888 <col:23> 'A *' <UncheckedDerivedToBase (A)>
        |       `-ImplicitCastExpr 0x1d33868 <col:23> 'B *' <UncheckedDerivedToBase (B)>
        |         `-ImplicitCastExpr 0x1d337d8 <col:23> 'C *' <LValueToRValue>
        |           `-DeclRefExpr 0x1d33798 <col:23> 'C *' lvalue ParmVar 0x1d33558 'c' 'C *'
        `-CXXMemberCallExpr 0x1d33978 <col:37, col:47> 'int'
          `-MemberExpr 0x1d33930 <col:37, col:43> '<bound member function type>' ->foo 0x1d02400
            `-ImplicitCastExpr 0x1d33998 <col:37> 'A *' <UncheckedDerivedToBase (B -> A)>
              `-ImplicitCastExpr 0x1d33908 <col:37> 'C *' <LValueToRValue>
                `-DeclRefExpr 0x1d338c8 <col:37> 'C *' lvalue ParmVar 0x1d33558 'c' 'C *'
```

<p>From looking this, it seems that the <code>UncheckedDerivedToBase</code> cast is marking places where the function call is non-<code>virtual</code>. Is this always the case? Should I always consider a call of the form <code>CXXMemberCallExpr (MemberExpr (ImplicitCastExpr<UncheckedDerivedToBase> e)))</code> to be a non-<code>virtual</code> call? Are there other patterns that would indicate non-<code>virtual</code> function calls? Is there any more robust way to determine this fact?</p>

<p><strong>EDIT</strong>: Some more investigation suggests that the above hypothesis that <code>UncheckedDerivedToBase</code> is not sufficient. This code:</p>

<pre class="lang-cpp prettyprint-override"><code>struct A {
    virtual int foo() { return 100; }
};
struct B : public A {
    virtual int foo() { return 10; }
};

int test(B* b) {
    return b->foo() + b->B::foo();
}
</code>```

seem to produce exactly the same AST node (at least indistinguishable on the console) for both calls, but the semantics should be different according to the standard if b is actually a derived class, e.g. C above.

答: The distinguishing factor is hasQualifier on the MemberExpr of the callee object. If hasQualifier is true, then the function call is non-virtual.

Body:
I'd like to write an analyzer that counts virtual function calls by looking at the C++ AST (output of -ast-dump), but I'm having difficulty determining which function calls are virtual and which are not. Here's an example piece of code:

struct A {
    A() {}
    virtual int foo() { return 0; }
};
struct B : public A {
    B() {}
    //virtual int foo() { return 3; }
};

struct C : public B {
    C() {}
    virtual int foo() { return 1; }
};

int test(C* c) {
    return c->foo() + c->B::foo() + c->A::foo();
}

In my initial implementation, I simply check whether or not the function being called is virtual using expr->getMethodDecl()->isVirtual() but (from what I understand) the calls in c->B::foo() and c->A::foo() are not actually virtual so it isn't sufficient to ask if the function being called is virtual.

When I dump the AST from this piece of code, I get the following tree for test:

`-FunctionDecl 0x1d33620 <line:19:1, line:21:1> line:19:5 test 'int (C *)'
  |-ParmVarDecl 0x1d33558 <col:10, col:13> col:13 used c 'C *'
  `-CompoundStmt 0x1d339f0 <col:16, line:21:1>
    `-ReturnStmt 0x1d339e0 <line:20:5, col:47>
      `-BinaryOperator 0x1d339c0 <col:12, col:47> 'int' '+'
        |-BinaryOperator 0x1d338a8 <col:12, col:33> 'int' '+'
        | |-CXXMemberCallExpr 0x1d33778 <col:12, col:19> 'int'
        | | `-MemberExpr 0x1d33748 <col:12, col:15> '<bound member function type>' ->foo 0x1d31c80
        | |   `-ImplicitCastExpr 0x1d33730 <col:12> 'C *' <LValueToRValue>
        | |     `-DeclRefExpr 0x1d33710 <col:12> 'C *' lvalue ParmVar 0x1d33558 'c' 'C *'
        | `-CXXMemberCallExpr 0x1d33848 <col:23, col:33> 'int'
        |   `-MemberExpr 0x1d33800 <col:23, col:29> '<bound member function type>' ->foo 0x1d02400
        |     `-ImplicitCastExpr 0x1d33888 <col:23> 'A *' <UncheckedDerivedToBase (A)>
        |       `-ImplicitCastExpr 0x1d33868 <col:23> 'B *' <UncheckedDerivedToBase (B)>
        |         `-ImplicitCastExpr 0x1d337d8 <col:23> 'C *' <LValueToRValue>
        |           `-DeclRefExpr 0x1d33798 <col:23> 'C *' lvalue ParmVar 0x1d33558 'c' 'C *'
        `-CXXMemberCallExpr 0x1d33978 <col:37, col:47> 'int'
          `-MemberExpr 0x1d33930 <col:37, col:43> '<bound member function type>' ->foo 0x1d02400
            `-ImplicitCastExpr 0x1d33998 <col:37> 'A *' <UncheckedDerivedToBase (B -> A)>
              `-ImplicitCastExpr 0x1d33908 <col:37> 'C *' <LValueToRValue>
                `-DeclRefExpr 0x1d338c8 <col:37> 'C *' lvalue ParmVar 0x1d33558 'c' 'C *'

From looking this, it seems that the UncheckedDerivedToBase cast is marking places where the function call is non-virtual. Is this always the case? Should I always consider a call of the form CXXMemberCallExpr (MemberExpr (ImplicitCastExpr<UncheckedDerivedToBase> e))) to be a non-virtual call? Are there other patterns that would indicate non-virtual function calls? Is there any more robust way to determine this fact?

EDIT: Some more investigation suggests that the above hypothesis that UncheckedDerivedToBase is not sufficient. This code:

struct A {
    virtual int foo() { return 100; }
};
struct B : public A {
    virtual int foo() { return 10; }
};

int test(B* b) {
    return b->foo() + b->B::foo();
}

seem to produce exactly the same AST node (at least indistinguishable on the console) for both calls, but the semantics should be different according to the standard if b is actually a derived class, e.g. C above.


问:
Is it possible to add custom filterfunction with PrimeNG DataTable?
Basicly all info is provided in the title.

It seems to me that I am bound to the filterMatchModes that are available ( contains, in, equals, endsWith, startsWith). In my usecase my column field is an array, and no single value.

My specified column looks like this:

```<code><p-column field="types" [filter]="true" header="{{'AIRPORTS.TYPES' | translate}}">
    <template let-airport="rowData" pTemplate="body">
        <span *ngFor="let type of airport.types; let isLast = last">
            {{('AIRPORTS.' + type) | translate}}{{isLast ? '' : ', '}}
        </span>
    </template>
    <template pTemplate="filter" let-col>
        <p-dropdown [options]="choices"
                    [style]="{'width':'100%'}"
                    (onChange)="airportsDataTable.filter($event.value,col.field,col.filterMatchMode)"
                    styleClass="ui-column-filter">
        </p-dropdown>
    </template>
</p-column>
</code>```

答:
As a simple workaround, you can directily change the FilterUtils: </p>

```<code>import { FilterUtils } from 'primeng/utils';

FilterUtils['filterTest'] = (value, filter) => value <= filter && value >= filter;

this.dt.filter(search, 'field', 'filterTest');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Basicly all info is provided in the title.

It seems to me that I am bound to the filterMatchModes that are available ( contains, in, equals, endsWith, startsWith). In my usecase my column field is an array, and no single value.

My specified column looks like this:

    <template let-airport="rowData" pTemplate="body">

            {{('AIRPORTS.' + type) | translate}}{{isLast ? '' : ', '}}

    </template>
    <template pTemplate="filter" let-col>

    </template>

Body:
As a simple workaround, you can directily change the FilterUtils:

import { FilterUtils } from 'primeng/utils';

FilterUtils['filterTest'] = (value, filter) => value <= filter && value >= filter;

this.dt.filter(search, 'field', 'filterTest');


问:
Split string each Nth character and join it back with different separators
I try to use text wrapping in a sentence with different separators. This is exactly what I would like to get as an output:

```<code>'here are third-party[SEPARATOR1]extensions like[SEPARATOR2]Scener that allow us[SEPARATOR3]to watch content.'
</code>```

Here is my first attempt with .join() and wrap(), unsuccessful:

```<code>[In] :
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

separator = '[SEPARATOR]'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR]extensions like[SEPARATOR]Scener that allow us[SEPARATOR]to watch content.'
</code>```

Then, I have tried a for loop inside the separator, but without success too... :

```<code>[In] :
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

for i in range(1, 4):
    separator = '[SEPARATOR' + str(i) + ']'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR3]extensions like[SEPARATOR3]Scener that allow us[SEPARATOR3]to watch content.'
</code>```

Maybe combining .split() and .join() function can be a better way to do what I would like, but I can't find how. Please, do you have any idea about how to achieve this?

答:
Wrap gives you an iterable of your text. If you can create an iterable with your separators you can join them with "".join(t for pair in zip(wrapped_chunks, separators) for t in pair)

You can create your separators with an infinite generator:

```<code>def inf_separators():
    index = 1
    while True:
        yield f"SEPARATOR{index}"
        index = index + 1
</code>```

This will give you one separator too many so you might want to delete it or append the last item of wrapped_chunks specially.

If you want to alternate between a few different separators you can use itertools.cycle(["SEP1", "SEP2", "SEP3"]) to generate a repetitive cycle of tokens.

Body:
I try to use text wrapping in a sentence with different separators. This is exactly what I would like to get as an output:

'here are third-party[SEPARATOR1]extensions like[SEPARATOR2]Scener that allow us[SEPARATOR3]to watch content.'

Here is my first attempt with .join() and wrap(), unsuccessful:

[In] :
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

separator = '[SEPARATOR]'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR]extensions like[SEPARATOR]Scener that allow us[SEPARATOR]to watch content.'

Then, I have tried a for loop inside the separator, but without success too... :

[In] :
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

for i in range(1, 4):
    separator = '[SEPARATOR' + str(i) + ']'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR3]extensions like[SEPARATOR3]Scener that allow us[SEPARATOR3]to watch content.'

Maybe combining .split() and .join() function can be a better way to do what I would like, but I can't find how. Please, do you have any idea about how to achieve this?

Body:
Wrap gives you an iterable of your text. If you can create an iterable with your separators you can join them with "".join(t for pair in zip(wrapped_chunks, separators) for t in pair)

You can create your separators with an infinite generator:

def inf_separators():
    index = 1
    while True:
        yield f"SEPARATOR{index}"
        index = index + 1

This will give you one separator too many so you might want to delete it or append the last item of wrapped_chunks specially.

If you want to alternate between a few different separators you can use itertools.cycle(["SEP1", "SEP2", "SEP3"]) to generate a repetitive cycle of tokens.


问:
How do I add hyphens to specific cells in a Pandas column
I have a DataFrame where dates have not all been filled in correctly. I need to clean some dates so that Pandas.to_datetime is able to parse the information.

This is my DataFrame:

```<code>import pandas
datums = {'Naam': ['Alfa', 'Beta', 'Gamma', 'Delta', 'Epsilon', 'Zieta', 'Icta', 'Thieta',
               'Jotta', 'Kappa', 'Lambda', 'Mu', 'Nu'],
   'Datum': ['2842001', '0952002', '1312003', '1112004', '1122005', '3122006', '2232007', '3112008',
             '1212009', '9102010', '3292011', '3302012', '4412013']}

df = pandas.DataFrame(datums, columns=['Naam', 'Datum'])
</code>```

The first row with Naam Alfa is clearly a typo of 28042001.

I'm able to filter the correct rows with str.contains('^[1|2][4-9[4-9]....$'

When I try to use str.replace to I'm not able to keep the existing data whilst only adding the hyphens in the correct place.

This is what I tried:

```<code>df.Datum.str.replace(r'^[1|2][4-9][4-9]....$', '\d\d-\d-\d\d\d\d', regex=True)
</code>```

This returns an error of bad escape \d at position 0

I also tried:

```<code>df.Datum.str.replace(r'^[1|2][4-9][4-9]....$', '{}-{}-{}'.format(df['Datum'][:2], df['Datum'][2:3], df['Datum'][3:]), regex=True)
</code>```

This runs but doesn't change anything.

I've tried to play around with the code without any luck. A pointer would be appreciated.

答:
You may use

```<code>df['Datum'] = df['Datum'].str.replace(r'^(\d{2})(\d)(\d+)$', r'\1-\2-\3')
</code>```

The ^(\d{2})(\d)(\d+)$ pattern will match:

^ - start of string

(\d{2}) - Group 1 (its value can be referenced to from the replacement pattern with the \1 replacement backreference): two digits

(\d) - Group 2 (\2): one digit

(\d+) - Group 3 (\3): any 0 or more digits

$ - till end of string.

Body:
I have a DataFrame where dates have not all been filled in correctly. I need to clean some dates so that Pandas.to_datetime is able to parse the information.

This is my DataFrame:

import pandas
datums = {'Naam': ['Alfa', 'Beta', 'Gamma', 'Delta', 'Epsilon', 'Zieta', 'Icta', 'Thieta',
               'Jotta', 'Kappa', 'Lambda', 'Mu', 'Nu'],
   'Datum': ['2842001', '0952002', '1312003', '1112004', '1122005', '3122006', '2232007', '3112008',
             '1212009', '9102010', '3292011', '3302012', '4412013']}

df = pandas.DataFrame(datums, columns=['Naam', 'Datum'])

The first row with Naam Alfa is clearly a typo of 28042001.

I'm able to filter the correct rows with str.contains('^[1|2][4-9[4-9]....$'

When I try to use str.replace to I'm not able to keep the existing data whilst only adding the hyphens in the correct place.

This is what I tried:

df.Datum.str.replace(r'^[1|2][4-9][4-9]....$', '\d\d-\d-\d\d\d\d', regex=True)

This returns an error of bad escape \d at position 0

I also tried:

df.Datum.str.replace(r'^[1|2][4-9][4-9]....$', '{}-{}-{}'.format(df['Datum'][:2], df['Datum'][2:3], df['Datum'][3:]), regex=True)

This runs but doesn't change anything.

I've tried to play around with the code without any luck. A pointer would be appreciated.

Body:
You may use

df['Datum'] = df['Datum'].str.replace(r'^(\d{2})(\d)(\d+)$', r'\1-\2-\3')

The ^(\d{2})(\d)(\d+)$ pattern will match:

^ - start of string

(\d{2}) - Group 1 (its value can be referenced to from the replacement pattern with the \1 replacement backreference): two digits

(\d) - Group 2 (\2): one digit

(\d+) - Group 3 (\3): any 0 or more digits

$ - till end of string.


问:
Read through an unstructured xls file
I have an .xls file which contains one column with 2,000 rows.

I want to iterate through the file and print out the data points
which start with "cheap". However, the following code doesn't work.

Help!

```<code>import xlrd
wb = xlrd.open_workbook("file.xls")

wb.sheet_names()

sh = wb.sheet_by_index(0)
lst = [sh]

for item in lst:
    print item.startswith("cheap")

    Traceback (most recent call last):
  File "C:\Python26\keywords.py", line 14, in <module>
    print item.startswith("cheap")
AttributeError: 'Sheet' object has no attribute 'startswith'
</code>```

答:
it should look like:</p>

```<code>import xlrd
wb = xlrd.open_workbook("file.xls")

wb.sheet_names()

sh = wb.sheet_by_index(0)

for item in sh.col(0):
    value = unicode(item.value)
    if value.startswith("cheap"):
        print value
</code>```

Title: Read through an unstructured xls file

Body:
I have an .xls file which contains one column with 2,000 rows.

I want to iterate through the file and print out the data points
which start with "cheap". However, the following code doesn't work.

Help!

import xlrd
wb = xlrd.open_workbook("file.xls")

wb.sheet_names()

sh = wb.sheet_by_index(0)
lst = [sh]

for item in lst:
    print item.startswith("cheap")

    Traceback (most recent call last):
  File "C:\Python26\keywords.py", line 14, in <module>
    print item.startswith("cheap")
AttributeError: 'Sheet' object has no attribute 'startswith'

Body:
it should look like:

import xlrd
wb = xlrd.open_workbook("file.xls")

wb.sheet_names()

sh = wb.sheet_by_index(0)

for item in sh.col(0):
    value = unicode(item.value)
    if value.startswith("cheap"):
        print value


问:
Webrtc error while initiating addIceCandidate
I am trying to initiate peer to peer connection in webrtc. I am using signalr as signaling server. I am getting error in all the browser when adding ice candidate. Below is the error and line of code. Please let me know how can i fix this.

Error in Firefox:

InvalidStateError: No remoteDescription.

Error in Chrome:

DOMException: Failed to execute 'addIceCandidate' on
  'RTCPeerConnection': Error processing ICE candidate

Code:

```<code>if (signal.ice) {
       console.log(signal.ice);
       peerConnections.addIceCandidate(new RTCIceCandidate(signal.ice)).catch(errorHandler.message);
}
</code>```

答:
You don't need to build a new ice candidate object. Just adding signal.ice as ice candidate is enough. Here is the example from the official webrtc guide</p>

```<code>signalingChannel.addEventListener('message', async message => {
    if (message.iceCandidate) {
        try {
            await peerConnection.addIceCandidate(message.iceCandidate);
        } catch (e) {
            console.error('Error adding received ice candidate', e);
        }
    }
});
</code>```

Body:
I am trying to initiate peer to peer connection in webrtc. I am using signalr as signaling server. I am getting error in all the browser when adding ice candidate. Below is the error and line of code. Please let me know how can i fix this.

Error in Firefox:

InvalidStateError: No remoteDescription.

Error in Chrome:

DOMException: Failed to execute 'addIceCandidate' on
  'RTCPeerConnection': Error processing ICE candidate

Code:

if (signal.ice) {
       console.log(signal.ice);
       peerConnections.addIceCandidate(new RTCIceCandidate(signal.ice)).catch(errorHandler.message);
}

Body:
You don't need to build a new ice candidate object. Just adding signal.ice as ice candidate is enough. Here is the example from the official webrtc guide

signalingChannel.addEventListener('message', async message => {
    if (message.iceCandidate) {
        try {
            await peerConnection.addIceCandidate(message.iceCandidate);
        } catch (e) {
            console.error('Error adding received ice candidate', e);
        }
    }
});


问:
C# if statement interpretation
I'm confused about a simple thing. In my opinion the result of line 4 must be the same as the one of line 6. Can somebody explain what the optimizer is doing on line 5.

I expected b to be decremented and incremented on each line. So the value of b must have 2 at the begin of interpretation of the line. So the result should have been the same for line 4 and 6.

```<code>1. int a = 1;
2. int b = 2;
3.
4. Console.WriteLine(a == --b && a == b++); // expected: true, real: true
5. Console.WriteLine(a == --b || a == b++); // expected: true, real: true
6. Console.WriteLine(a == --b && a == b++); // expected: true, real: false
</code>```

答:
```<code>1. int a = 1;
2. int b = 2;
3.
4. Console.WriteLine(a == --b && a == b++); // expected: true, real: true
5. Console.WriteLine(a == --b || a == b++); // expected: true, real: true
6. Console.WriteLine(a == --b && a == b++); // expected: true, real: false
</code>```

becomes

```<code>1. int a = 1;
2. int b = 2;
3.

   // now: a = 1, b = 2
   // b is decremented to 1, expressions are evaluated. b is incremented to 2,
4. Console.WriteLine(1 == 1 && 1 == 1);

   // now: a = 1, b = 2
   // b is decremented to 1, first expression is evaluated to true,
   // that causes the second expression to be short circuited. It doesnt
   // matter whether it is true or false, the whole expression will be true anyway.
   // So the second expression will not be executed.
5. Console.WriteLine(1 == 1);

   // now: a = 1, b = 1
   // b is decremented to 0, expressions are evaluated, b is incremented to 1
6. Console.WriteLine(1 == 0 && 1 == 0);
</code>```

Title: C# if statement interpretation

Body:
I'm confused about a simple thing. In my opinion the result of line 4 must be the same as the one of line 6. Can somebody explain what the optimizer is doing on line 5.

I expected b to be decremented and incremented on each line. So the value of b must have 2 at the begin of interpretation of the line. So the result should have been the same for line 4 and 6.

1. int a = 1;
2. int b = 2;
3.
4. Console.WriteLine(a == --b && a == b++); // expected: true, real: true
5. Console.WriteLine(a == --b || a == b++); // expected: true, real: true
6. Console.WriteLine(a == --b && a == b++); // expected: true, real: false

Body:
1. int a = 1;
2. int b = 2;
3.
4. Console.WriteLine(a == --b && a == b++); // expected: true, real: true
5. Console.WriteLine(a == --b || a == b++); // expected: true, real: true
6. Console.WriteLine(a == --b && a == b++); // expected: true, real: false

becomes

1. int a = 1;
2. int b = 2;
3.

   // now: a = 1, b = 2
   // b is decremented to 1, expressions are evaluated. b is incremented to 2,
4. Console.WriteLine(1 == 1 && 1 == 1);

   // now: a = 1, b = 2
   // b is decremented to 1, first expression is evaluated to true,
   // that causes the second expression to be short circuited. It doesnt
   // matter whether it is true or false, the whole expression will be true anyway.
   // So the second expression will not be executed.
5. Console.WriteLine(1 == 1);

   // now: a = 1, b = 1
   // b is decremented to 0, expressions are evaluated, b is incremented to 1
6. Console.WriteLine(1 == 0 && 1 == 0);


问:
Can't get required response using json parameters within get requests
I'm trying to get json response from this webpage using the following approach but this is what I get {"message": "Must provide valid one of: query_id, query_hash", "status": "fail"}. I tried to print the response url, as in r.url in the second script to see if it matches the one I tried to send but I found it different in structure.

If I use the url directly (taken from dev tools) within requests, I get required content:

```<code>import json
import requests

check_url = 'https://www.instagram.com/graphql/query/?query_hash=7dabc71d3e758b1ec19ffb85639e427b&variables=%7B%22tag_name%22%3A%22instagood%22%2C%22first%22%3A2%2C%22after%22%3A%22QVFDa3djMUFwM1BkRWJNTlEzRmxBYkRGdFBDVzViU2JoNVZPbWNQSmNCTE1HNDlhYWdsdi1EcE5ickhvYjhRWUhqUDhIcXE3YTE4M1JMbmdVN0lMSXM3ZA%3D%3D%22%7D'
r = requests.get(check_url)
print(r.json())
</code>```

But, I can't make it work:

```<code>import json
import requests

url = 'https://www.instagram.com/explore/tags/instagood/'
query_url = 'https://www.instagram.com/graphql/query/?'

payload = {
    "query_hash": "7dabc71d3e758b1ec19ffb85639e427b",
    "variables": {"tag_name":"instagood","first":"2","after":"QVFDa3djMUFwM1BkRWJNTlEzRmxBYkRGdFBDVzViU2JoNVZPbWNQSmNCTE1HNDlhYWdsdi1EcE5ickhvYjhRWUhqUDhIcXE3YTE4M1JMbmdVN0lMSXM3ZA=="}
}

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
    r = s.get(query_url,params=json.dumps(payload))
    print(r.content)
</code>```

How can I make the above script work?

答:
While running your code, the URL that forms after api call contains unnecessary escape characters. This is what screwing up the API call.

It is not suggested to send data payload while using get. A quick solution to this could be using post request instead. It worked fine!

```<code>import json
import requests

url = 'https://www.instagram.com/explore/tags/instagood/'
query_url = 'https://www.instagram.com/graphql/query/?'

payload = {
    "query_hash": "7dabc71d3e758b1ec19ffb85639e427b",
    "variables": {"tag_name":"instagood","first":"2","after":"QVFDa3djMUFwM1BkRWJNTlEzRmxBYkRGdFBDVzViU2JoNVZPbWNQSmNCTE1HNDlhYWdsdi1EcE5ickhvYjhRWUhqUDhIcXE3YTE4M1JMbmdVN0lMSXM3ZA=="}
}

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
    r = s.post(query_url,params=json.dumps(payload))
    print(r.content)
</code>```

Body:
I'm trying to get json response from this webpage using the following approach but this is what I get {"message": "Must provide valid one of: query_id, query_hash", "status": "fail"}. I tried to print the response url, as in r.url in the second script to see if it matches the one I tried to send but I found it different in structure.

If I use the url directly (taken from dev tools) within requests, I get required content:

import json
import requests

check_url = 'https://www.instagram.com/graphql/query/?query_hash=7dabc71d3e758b1ec19ffb85639e427b&variables=%7B%22tag_name%22%3A%22instagood%22%2C%22first%22%3A2%2C%22after%22%3A%22QVFDa3djMUFwM1BkRWJNTlEzRmxBYkRGdFBDVzViU2JoNVZPbWNQSmNCTE1HNDlhYWdsdi1EcE5ickhvYjhRWUhqUDhIcXE3YTE4M1JMbmdVN0lMSXM3ZA%3D%3D%22%7D'
r = requests.get(check_url)
print(r.json())

But, I can't make it work:

import json
import requests

url = 'https://www.instagram.com/explore/tags/instagood/'
query_url = 'https://www.instagram.com/graphql/query/?'

payload = {
    "query_hash": "7dabc71d3e758b1ec19ffb85639e427b",
    "variables": {"tag_name":"instagood","first":"2","after":"QVFDa3djMUFwM1BkRWJNTlEzRmxBYkRGdFBDVzViU2JoNVZPbWNQSmNCTE1HNDlhYWdsdi1EcE5ickhvYjhRWUhqUDhIcXE3YTE4M1JMbmdVN0lMSXM3ZA=="}
}

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
    r = s.get(query_url,params=json.dumps(payload))
    print(r.content)

How can I make the above script work?

Body:
While running your code, the URL that forms after api call contains unnecessary escape characters. This is what screwing up the API call.

It is not suggested to send data payload while using get. A quick solution to this could be using post request instead. It worked fine!

import json
import requests

url = 'https://www.instagram.com/explore/tags/instagood/'
query_url = 'https://www.instagram.com/graphql/query/?'

payload = {
    "query_hash": "7dabc71d3e758b1ec19ffb85639e427b",
    "variables": {"tag_name":"instagood","first":"2","after":"QVFDa3djMUFwM1BkRWJNTlEzRmxBYkRGdFBDVzViU2JoNVZPbWNQSmNCTE1HNDlhYWdsdi1EcE5ickhvYjhRWUhqUDhIcXE3YTE4M1JMbmdVN0lMSXM3ZA=="}
}

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
    r = s.post(query_url,params=json.dumps(payload))
    print(r.content)


问:
Issue with Matplotlib Dates appearing incorrectly on Graph/ Date Formatting Issue in Python
I'm trying to do a basic Time Series plot using matplotlib in Google Colab.

I have a fairly basic issue where I can't get the dates to appear properly, the dates go from 1971 to 2020, so there is quite a lot of data there.

I have saved my code and graph in the below location:

https://github.com/Ianfm94/Financial_Analysis/blob/master/LSTM_NN.ipynb

As you can also see in the below image, the dates are just appearing as black.

I have also tried formatting the dates using "Dateformatter" from the matplotlib package but this didn't have the desired effect.

Could someone please shed some light on how to fix this date issue?

Thanks.

答:
There is a feature that automatically adjusts the xticks.
matplotlib.datesPlease refer to this page

```<code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates

# Reading in data
nasdaq_data = "https://raw.githubusercontent.com/Ianfm94/Financial_Analysis/master/NASDAQ_data%20US%20Listing.csv"

X = pd.read_csv(nasdaq_data)
Y = X['close']
#print(X.head(n=3))
X['date'] = pd.to_datetime(X['date'])

# Create figure and plot space
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(12, 12))

# Add x-axis and y-axis, colour of graph and increase
# the line-width
ax.plot(X['date'],
       X['mid_price'],
       color='#69b3a2', lw=2)

# Set title and labels for axes
ax.set(xlabel='Date',
       ylabel='Index Value in $',
       title='Nasdaq Index Analysis')

# Change plot background colour
ax.set_facecolor('xkcd:light grey')

locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)

ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

# Add grid
plt.grid(b=True, which='both', axis='both')

plt.show()
</code>```

Body:
There is a feature that automatically adjusts the xticks.
matplotlib.datesPlease refer to this page

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates

# Reading in data
nasdaq_data = "https://raw.githubusercontent.com/Ianfm94/Financial_Analysis/master/NASDAQ_data%20US%20Listing.csv"

X = pd.read_csv(nasdaq_data)
Y = X['close']
#print(X.head(n=3))
X['date'] = pd.to_datetime(X['date'])

# Create figure and plot space
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(12, 12))

# Add x-axis and y-axis, colour of graph and increase
# the line-width
ax.plot(X['date'],
       X['mid_price'],
       color='#69b3a2', lw=2)

# Set title and labels for axes
ax.set(xlabel='Date',
       ylabel='Index Value in $',
       title='Nasdaq Index Analysis')

# Change plot background colour
ax.set_facecolor('xkcd:light grey')

locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)

ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

# Add grid
plt.grid(b=True, which='both', axis='both')

plt.show()


问:
Dealing with .csv files: Error: only integer scalar arrays can be converted to a scalar index
enter image description herePython Machine Learning dealing with .csv files: Error: only integer scalar arrays can be converted to a scalar index

```<code>import pandas as pd
df = pd.read_csv('EURGBP.csv')
df.columns = [['date', 'open', 'high', 'low', 'close', 'volume']]
df.date = pd.to_datetime(df.date,format='%d.%m.%Y  %H:%M:%S.%f')
df = df.set_index(df.date)
print(df.head())
</code>```

Error: only integer scalar arrays can be converted to a scalar index

答:
Problem is you pass nested list to columns names, so created 'broken' one level MultiIndex, need remove outer []:

```<code>df.columns = ['date', 'open', 'high', 'low', 'close', 'volume']
</code>```

Body:
enter image description herePython Machine Learning dealing with .csv files: Error: only integer scalar arrays can be converted to a scalar index

import pandas as pd
df = pd.read_csv('EURGBP.csv')
df.columns = [['date', 'open', 'high', 'low', 'close', 'volume']]
df.date = pd.to_datetime(df.date,format='%d.%m.%Y  %H:%M:%S.%f')
df = df.set_index(df.date)
print(df.head())

Error: only integer scalar arrays can be converted to a scalar index

Body:
Problem is you pass nested list to columns names, so created 'broken' one level MultiIndex, need remove outer []:

df.columns = ['date', 'open', 'high', 'low', 'close', 'volume']


问:
Stored procedure - Use array list in SQL query for insert in snowflake
If i have created/generated a list of elements during processing in stored procedure say rownum = [1,2,3,4].
Now i want to use this list in a sql statement to filter out rows say select * from mytable where rownum not in (1,2,3,4) in same stored procedure.
How can i achieve this ?
Please guide.
Thanks</p>

答:
The general solution to this would be to use binding variables. However, set types are not supported as bind variables in the Stored Procedure APIs currently.

The JavaScript APIs do permit you to generate your SQL dynamically using string and array transform functions, so the following approaches can be taken to work around the problem.

Inline the list of values into the query by forming a SQL syntax of a set of values:

CREATE OR REPLACE PROCEDURE SAMPLE()
    RETURNS RETURNTYPE
    LANGUAGE JAVASCRIPT
    AS
    $$
      var lst = [2, 3, 4]
      var lstr = lst.join(',') // "2, 3, 4"
      var sql_command = `SELECT * FROM T WHERE C NOT IN (${lstr})` // (2, 3, 4)
      var stmt = snowflake.createStatement( {sqlText: sql_command} )
      // Runs: SELECT * FROM T WHERE C NOT IN (2, 3, 4) [Literal query string]
      [...]
    $$;
```

<p>Or if the list of values used could be unsafe, you can generate the query to carry just the right number of bind variables:</p>

<pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE PROCEDURE SAMPLE()
    RETURNS RETURNTYPE
    LANGUAGE JAVASCRIPT
    AS
    $$
      var lst = [2, 3, 4]
      var lst_vars = Array(lst.length).fill("?").join(", ") // "?, ?, ?"
      var sql_command = `SELECT * FROM T WHERE C NOT IN (${lst_vars})` // (?, ?, ?)
      var stmt = snowflake.createStatement( {sqlText: sql_command, binds: lst} )
      // Runs: SELECT * FROM T WHERE C NOT IN (2, 3, 4) [After bind-substitution]
      [...]
    $$;
</code>```

Body:
The general solution to this would be to use binding variables. However, set types are not supported as bind variables in the Stored Procedure APIs currently.

The JavaScript APIs do permit you to generate your SQL dynamically using string and array transform functions, so the following approaches can be taken to work around the problem.

Inline the list of values into the query by forming a SQL syntax of a set of values:

CREATE OR REPLACE PROCEDURE SAMPLE()
    RETURNS RETURNTYPE
    LANGUAGE JAVASCRIPT
    AS
    $$
      var lst = [2, 3, 4]
      var lstr = lst.join(',') // "2, 3, 4"
      var sql_command = `SELECT * FROM T WHERE C NOT IN (${lstr})` // (2, 3, 4)
      var stmt = snowflake.createStatement( {sqlText: sql_command} )
      // Runs: SELECT * FROM T WHERE C NOT IN (2, 3, 4) [Literal query string]
      [...]
    $$;

Or if the list of values used could be unsafe, you can generate the query to carry just the right number of bind variables:

CREATE OR REPLACE PROCEDURE SAMPLE()
    RETURNS RETURNTYPE
    LANGUAGE JAVASCRIPT
    AS
    $$
      var lst = [2, 3, 4]
      var lst_vars = Array(lst.length).fill("?").join(", ") // "?, ?, ?"
      var sql_command = `SELECT * FROM T WHERE C NOT IN (${lst_vars})` // (?, ?, ?)
      var stmt = snowflake.createStatement( {sqlText: sql_command, binds: lst} )
      // Runs: SELECT * FROM T WHERE C NOT IN (2, 3, 4) [After bind-substitution]
      [...]
    $$;


问:
Proxmox apt-get update fails
When I type in the bash of the Server apt-get update it fails, I don't know why. The error is:

E: Failed to fetch https://enterprise.proxmox.com/debian/pve/dists/buster/InRelease  401  Unauthorized [IP: 2a01:7e0:0:424::249 443]

E: The repository 'https://enterprise.proxmox.com/debian/pve buster InRelease' is not signed.

N: Updating from such a repository can't be done securely, and is therefore disabled by default.

N: See apt-secure(8) manpage for repository creation and user configuration details.

答:
The apt package manager on the fresh Proxmox host is configured to download packages from Enterprise Repository by default. You must have a paid subscription to use this repo. If you don't have paid subscription you should switch to No-Subscription Repository.

Either delete /etc/apt/sources.list.d/pve-enterprise.list file or comment all lines in this file with #.

Create new file /etc/apt/sources.list.d/pve-no-subscription.list with content:

```<code>deb http://download.proxmox.com/debian/pve buster pve-no-subscription
</code>```

Read about Proxmox package repositories here:
https://pve.proxmox.com/wiki/Package_Repositories

Title: Proxmox apt-get update fails

Body:
The apt package manager on the fresh Proxmox host is configured to download packages from Enterprise Repository by default. You must have a paid subscription to use this repo. If you don't have paid subscription you should switch to No-Subscription Repository.

Either delete /etc/apt/sources.list.d/pve-enterprise.list file or comment all lines in this file with #.

Create new file /etc/apt/sources.list.d/pve-no-subscription.list with content:

deb http://download.proxmox.com/debian/pve buster pve-no-subscription

Read about Proxmox package repositories here:
https://pve.proxmox.com/wiki/Package_Repositories


答:
Try this:</p>

```<code>from textwrap import wrap

sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

new_sentence = ""
parts = wrap(sentence, 20)
for i, part in enumerate(parts):
    new_sentence += part
    # adding separator after each part except for the last one
    if i < len(parts) - 1:
        new_sentence += f"[SEPARATOR{i+1}]"
print(new_sentence)

# output: here are third-party[SEPARATOR1]extensions like[SEPARATOR2]Scener that allow us[SEPARATOR3]to watch content.

</code>```

Title: Split string each Nth character and join it back with different separators

Body:
I try to use text wrapping in a sentence with different separators. This is exactly what I would like to get as an output:

'here are third-party[SEPARATOR1]extensions like[SEPARATOR2]Scener that allow us[SEPARATOR3]to watch content.'

Here is my first attempt with .join() and wrap(), unsuccessful:

[In] :
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

separator = '[SEPARATOR]'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR]extensions like[SEPARATOR]Scener that allow us[SEPARATOR]to watch content.'

Then, I have tried a for loop inside the separator, but without success too... :

[In] :
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

for i in range(1, 4):
    separator = '[SEPARATOR' + str(i) + ']'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR3]extensions like[SEPARATOR3]Scener that allow us[SEPARATOR3]to watch content.'

Maybe combining .split() and .join() function can be a better way to do what I would like, but I can't find how. Please, do you have any idea about how to achieve this?

Body:
Try this:

from textwrap import wrap

sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

new_sentence = ""
parts = wrap(sentence, 20)
for i, part in enumerate(parts):
    new_sentence += part
    # adding separator after each part except for the last one
    if i < len(parts) - 1:
        new_sentence += f"[SEPARATOR{i+1}]"
print(new_sentence)

# output: here are third-party[SEPARATOR1]extensions like[SEPARATOR2]Scener that allow us[SEPARATOR3]to watch content.


问:
using pip3: module "importlib._bootstrap" has no attribute "SourceFileLoader"
I have installed pip for python 3.6 on Ubuntu 14. After I run

```<code>sudo apt-get install python3-pip
</code>```

to install pip3, it works very well. However, after installation, when I am trying to run

```<code>pip3 install packagename
</code>```

to install a new package, something strange occurs:

```<code>File "/usr/lib/python3/dist-packages/pkg_resources.py", line 1479, in <module>
 register_loader-type(importlib_bootstrap.SourceFileLoader, DefaultProvider)
AttributeError: module "importlib._bootstrap" has no attribute "SourceFileLoader"
</code>```

It seems that I did nothing wrong, and I really cannot figure out the reason.

答:
If you face this issue in anaconda environment, simply upgrade setuptools using the following:

```<code>conda install -c conda-forge setuptools
</code>```

Body:
I have installed pip for python 3.6 on Ubuntu 14. After I run

sudo apt-get install python3-pip

to install pip3, it works very well. However, after installation, when I am trying to run

pip3 install packagename

to install a new package, something strange occurs:

File "/usr/lib/python3/dist-packages/pkg_resources.py", line 1479, in <module>
 register_loader-type(importlib_bootstrap.SourceFileLoader, DefaultProvider)
AttributeError: module "importlib._bootstrap" has no attribute "SourceFileLoader"

It seems that I did nothing wrong, and I really cannot figure out the reason.

Body:
If you face this issue in anaconda environment, simply upgrade setuptools using the following:

conda install -c conda-forge setuptools


问:
Filter an array taking into account that the filtered options are optional
I have a code that should filter the array depending on some condition. One time it could be 1 condition or 2, depending on how many user are inserted.

const arr = [
  {
    name: 'John',
    age: 44,
    old: 'No'
  },
  {
    name: 'John',
    age: 4,
    old: 'No'
  },
  {
    name: 'Bill',
    age: 47,
    old: 'No'
  },
]
const filteredData = [4, "John", "No"];

var find = arr.filter(function(result) {
  return filteredData.includes(result.name) && filteredData.includes(result.age) && filteredData.includes(result.old);
})

console.log(find)```
</div>
</div>
</p>

<p>In this case the code works, but if I add just one value in <code>const filteredData = [4, "John", "No" ];</code>, like: <code>const filteredData = ["John"];</code>, I should get:</p>

```[
  {
    name: 'John',
    age: 44,
    old: 'No'
  },
  {
    name: 'John',
    age: 4,
    old: 'No'
  },
]
```

...but now I don't get anything, because in filteredData all 3 conditions should be mandatory. How to change the code to make the number of condition optional?

答:
You need to make the filteredData as an object so you know what field you are checking.
Try the following code and run the snippet to see test case:

const arr = [
  {
    name:'John',
    age:44,
    old:'No'
  },
   {
    name:'John',
    age:4,
    old:'No'
  },
  {
    name:'Bill',
    age:47,
    old:'No'
  },
]

// Make this as object
let filteredData = {
    name:'John',
    age:4,
    old:'No'
  };

var find = arr.filter(function(result) {
  // Get all key from filteredData
  const filteredDataKeys = Object.keys(filteredData)
  // Check if all key pass
  return filteredDataKeys.every(key => filteredData[key] === result[key])
})

console.log(find)

 filteredData = {
    name:'John',
  };

find = arr.filter(function(result) {
  // Get all key from filteredData
  const filteredDataKeys = Object.keys(filteredData)
  // Check if all key pass
  return filteredDataKeys.every(key => filteredData[key] === result[key])
})

console.log(find)```

Body:
I have a code that should filter the array depending on some condition. One time it could be 1 condition or 2, depending on how many user are inserted.

const arr = [
  {
    name: 'John',
    age: 44,
    old: 'No'
  },
  {
    name: 'John',
    age: 4,
    old: 'No'
  },
  {
    name: 'Bill',
    age: 47,
    old: 'No'
  },
]
const filteredData = [4, "John", "No"];

var find = arr.filter(function(result) {
  return filteredData.includes(result.name) && filteredData.includes(result.age) && filteredData.includes(result.old);
})

console.log(find)

In this case the code works, but if I add just one value in const filteredData = [4, "John", "No" ];, like: const filteredData = ["John"];, I should get:

[
  {
    name: 'John',
    age: 44,
    old: 'No'
  },
  {
    name: 'John',
    age: 4,
    old: 'No'
  },
]

...but now I don't get anything, because in filteredData all 3 conditions should be mandatory. How to change the code to make the number of condition optional?


问:
Create a column to indicate the presence of a value in other columns
I have a dataset with symptoms (20+), the symptoms are categorized as Yes/No/Unknown. I would like to create a new column which indicates if the subject (ID) has no symptoms (I'm defining this as they have no symptoms with 'Yes').

I've got a sample dataset below and I can create a column as desired but it feels like there must be a better/cleaner way just using dplyr::mutate() rather than the filtering and joining that I'm doing?

library(dplyr)

test <- tibble(
  ID = c(1:10),
  col1 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE),
  col2 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE),
  col3 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE)
)

left_join(test, test %>%
  filter_at(vars(col1:col3), any_vars(. == "Yes")) %>%
  mutate(any_symptoms = "Yes") %>%
  select(ID, any_symptoms),
by = "ID"
) %>%
  mutate(any_symptoms = recode(any_symptoms, .missing = "No"))
#> # A tibble: 10 x 5
#>       ID col1    col2    col3    any_symptoms
#>    <int> <chr>   <chr>   <chr>   <chr>
#>  1     1 Unknown Unknown Unknown No
#>  2     2 Unknown No      No      No
#>  3     3 Yes     Yes     Unknown Yes
#>  4     4 No      Unknown Unknown No
#>  5     5 No      No      Unknown No
#>  6     6 Unknown Yes     Unknown Yes
#>  7     7 Yes     Unknown Unknown Yes
#>  8     8 No      No      No      No
#>  9     9 No      Unknown Unknown No
#> 10    10 No      No      No      No
```

Created on 2020-05-29 by the reprex package (v0.3.0)

答:
You can use rowSums to check if you have more than 0 "yes" in a row.

```<code>test$any_symptoms <- c('No', 'Yes')[(rowSums(test[-1] == 'Yes') > 0) + 1]
</code>```

You can also use this in dplyr pipes :

```<code>library(dplyr)
test %>% mutate(any_symptoms = c('No', 'Yes')[(rowSums(.[-1] == 'Yes') > 0) + 1])
</code>```

Or using pmap from purrr

```<code>library(purrr)
test %>%
    mutate(any_symptoms = c('No', 'Yes')[pmap_lgl(select(., starts_with('col')),
                                        ~any(c(...) == 'Yes')) + 1])
</code>```

Body:
I have a dataset with symptoms (20+), the symptoms are categorized as Yes/No/Unknown. I would like to create a new column which indicates if the subject (ID) has no symptoms (I'm defining this as they have no symptoms with 'Yes').

I've got a sample dataset below and I can create a column as desired but it feels like there must be a better/cleaner way just using dplyr::mutate() rather than the filtering and joining that I'm doing?

library(dplyr)

test <- tibble(
  ID = c(1:10),
  col1 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE),
  col2 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE),
  col3 = sample(c("Yes", "No", "Unknown"), 10, replace = TRUE)
)

left_join(test, test %>%
  filter_at(vars(col1:col3), any_vars(. == "Yes")) %>%
  mutate(any_symptoms = "Yes") %>%
  select(ID, any_symptoms),
by = "ID"
) %>%
  mutate(any_symptoms = recode(any_symptoms, .missing = "No"))
#> # A tibble: 10 x 5
#>       ID col1    col2    col3    any_symptoms
#>    <int> <chr>   <chr>   <chr>   <chr>
#>  1     1 Unknown Unknown Unknown No
#>  2     2 Unknown No      No      No
#>  3     3 Yes     Yes     Unknown Yes
#>  4     4 No      Unknown Unknown No
#>  5     5 No      No      Unknown No
#>  6     6 Unknown Yes     Unknown Yes
#>  7     7 Yes     Unknown Unknown Yes
#>  8     8 No      No      No      No
#>  9     9 No      Unknown Unknown No
#> 10    10 No      No      No      No

Created on 2020-05-29 by the reprex package (v0.3.0)

Body:
You can use rowSums to check if you have more than 0 "yes" in a row.

test$any_symptoms <- c('No', 'Yes')[(rowSums(test[-1] == 'Yes') > 0) + 1]

You can also use this in dplyr pipes :

library(dplyr)
test %>% mutate(any_symptoms = c('No', 'Yes')[(rowSums(.[-1] == 'Yes') > 0) + 1])

Or using pmap from purrr

library(purrr)
test %>%
    mutate(any_symptoms = c('No', 'Yes')[pmap_lgl(select(., starts_with('col')),
                                        ~any(c(...) == 'Yes')) + 1])


问:
How can I suppress warnings (codebase-wide) during javadoc compilation?
I'm stuck with a legacy Java codebase that has THOUSANDS of warnings when you compile it. I would love to actually fix the source of all these warnings, but unfortunately that's not an option at this time at my company (other things like "making new products that generate revenue" are considered higher priority by the people in charge; fancy that).

Now, I could just live with all of these warnings, if it wasn't for the fact that they make it difficult to find actual errors in the output from our continuous build server.  The build server just uses an ant  call, nothing fancy, but so far I haven't been able to find anything anywhere for how I can modify this call to prevent warning output.

Going through the code and adding a @SuppressWarnings annotation everywhere would work, but it would also be almost as much of a pain as going through and fixing all the warnings' sources.  So what I'd really love is if there was just some way I could do:

```<code><javadoc suppressWarrnings="true"
</code>```

or something similar, to make the javadoc compiler not output all the warning messages.  Is anything like this (global javadoc warning disabling) possible?

答:
Both the ant task and javadoc tool itself have no way of disabling warnings globally.

One possible workaround I can think of is to run the javadoc task as a separate ant call from the rest of the build. You could use the -logfile argument to ant to redirect the output to a log file rather than the console.

OwnerDisplayName: machineghost

ContentLicense: CC BY-SA 2.5

Body:
I'm stuck with a legacy Java codebase that has THOUSANDS of warnings when you compile it. I would love to actually fix the source of all these warnings, but unfortunately that's not an option at this time at my company (other things like "making new products that generate revenue" are considered higher priority by the people in charge; fancy that).

Now, I could just live with all of these warnings, if it wasn't for the fact that they make it difficult to find actual errors in the output from our continuous build server.  The build server just uses an ant  call, nothing fancy, but so far I haven't been able to find anything anywhere for how I can modify this call to prevent warning output.

Going through the code and adding a @SuppressWarnings annotation everywhere would work, but it would also be almost as much of a pain as going through and fixing all the warnings' sources.  So what I'd really love is if there was just some way I could do:

<javadoc suppressWarrnings="true"

or something similar, to make the javadoc compiler not output all the warning messages.  Is anything like this (global javadoc warning disabling) possible?

OwnerDisplayName: Mark


问:
Python Seasonal decompose Freq paramater determination
Although the question seems to have been tackled a lot, I cannot figure out why seasonal decompose doesn't work in my case although I am giving as input a dataframe with a Datetime Index. Here is an example of my dataset:

```<code>    Customer order actual date  Sales Volumes
0   01/01/1900                           300
1   10/03/2008                          3000
2   15/11/2013                            10
3   23/12/2013                           200
4   04/03/2014                             5
5   17/03/2014                            30
6   22/04/2014                             1
7   26/06/2014                           290
8   30/06/2014                            40
</code>```

the code snippet is shown below:

```<code>from statsmodels.tsa.seasonal import seasonal_decompose
df_agg['Customer order actual date'] = pd.to_datetime(df_agg['Customer order actual date'])
df_agg = df_agg.set_index('Customer order actual date')
df_agg.reset_index().sort_values('Customer order actual date', ascending=True)
decomposition = seasonal_decompose(np.asarray(df_agg['Sales Volumes'] ), model = 'multiplicative')
</code>```

But I get systematically the following error:

: You must specify a freq or x must be a pandas object with a timeseries index witha freq not set to None

Could you please explain why I should give a freq input although I am using a dataframe with Datetime Index? Does it make sense to give a frequency as an input paramater whereas I am looking for the seasonality as an output of seasonal_decompose?

答:
First of all, if you hand an np.asarray(...) to seasonal_decompose, it will see only an array, your index is gone. So get rid of the np.asarray.

Secondly, if you look at df_agg['Sales Volumes'].index you will see that freq=None - that's what causes the function to complain. You need an existing frequency like D, M, whatever. You can achieve a frequency by setting it via df_agg.asfreq('D').

Last, but not least: your sample data are not following any frequency - asfreq will fill them up - but you get lots of NaN.

If you want to look up the abbreviations for freqs, they are here.

Body:
Although the question seems to have been tackled a lot, I cannot figure out why seasonal decompose doesn't work in my case although I am giving as input a dataframe with a Datetime Index. Here is an example of my dataset:

    Customer order actual date  Sales Volumes
0   01/01/1900                           300
1   10/03/2008                          3000
2   15/11/2013                            10
3   23/12/2013                           200
4   04/03/2014                             5
5   17/03/2014                            30
6   22/04/2014                             1
7   26/06/2014                           290
8   30/06/2014                            40

the code snippet is shown below:

from statsmodels.tsa.seasonal import seasonal_decompose
df_agg['Customer order actual date'] = pd.to_datetime(df_agg['Customer order actual date'])
df_agg = df_agg.set_index('Customer order actual date')
df_agg.reset_index().sort_values('Customer order actual date', ascending=True)
decomposition = seasonal_decompose(np.asarray(df_agg['Sales Volumes'] ), model = 'multiplicative')

But I get systematically the following error:

: You must specify a freq or x must be a pandas object with a timeseries index witha freq not set to None

Could you please explain why I should give a freq input although I am using a dataframe with Datetime Index? Does it make sense to give a frequency as an input paramater whereas I am looking for the seasonality as an output of seasonal_decompose?


问:
Unable to use yarn and import mapbox into typescript
I use

yarn add --dev @types/mapbox-gl @types/geojson

to add mapbox and geojson to my project. The packages install successfully and are visible when I try to import mapboxgl.

The I build something that looks like this:

```<code>import * as L from 'mapbox-gl';

export class MapBuilder
{

    build(): void {
        let map = new L.Map({
            container: 'mapContainer',
            style: this.map.getStyle()
            //etc
        });
    }
}
</code>```

When I use yarn build I get this message:

This dependency was not found:

mapbox-gl in ./assets/js/MapBuilder.ts

答:
Thanks to Zhonk who commented on this issue the problem is solved.

I simply forgot to add the mapbox-gl library.

yarn add --dev mapbox-gl

Body:
I use

yarn add --dev @types/mapbox-gl @types/geojson

to add mapbox and geojson to my project. The packages install successfully and are visible when I try to import mapboxgl.

The I build something that looks like this:

import * as L from 'mapbox-gl';

export class MapBuilder
{

    build(): void {
        let map = new L.Map({
            container: 'mapContainer',
            style: this.map.getStyle()
            //etc
        });
    }
}

When I use yarn build I get this message:

This dependency was not found:

mapbox-gl in ./assets/js/MapBuilder.ts


问:
system shows All requested packages already installed.however i get error message when i import pytorch
I installed pytorch using the following command as specified on their site: conda install pytorch torchvision cudatoolkit=10.2 -c pytorch.
However, I tried using import torch and I get the following error:

```<code>'Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\ProgramData\Anaconda3\lib\site-packages\torch\__init__.py", line 81, in <module>
    ctypes.CDLL(dll)
  File "C:\ProgramData\Anaconda3\lib\ctypes\__init__.py", line 364, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found'
</code>```

How do I resolve this?

答:
It is because you are using a CUDA variant of PyTorch on a system that doesn’t have GPU driver installed.
If you don’t have a Nvidia GPU card, please install the cpu-only package according to the commands on:

Conda

```<code>conda install pytorch torchvision cpuonly -c pytorch
</code>```

Pip

```<code>pip install torch==1.5.0+cpu torchvision==0.6.0+cpu -f
</code>```

Or:

```<code>conda install PyTorch -c PyTorch
</code>```

Or:

```<code>pip3 install torchvision
</code>```

Body:
I installed pytorch using the following command as specified on their site: conda install pytorch torchvision cudatoolkit=10.2 -c pytorch.
However, I tried using import torch and I get the following error:

'Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\ProgramData\Anaconda3\lib\site-packages\torch\__init__.py", line 81, in <module>
    ctypes.CDLL(dll)
  File "C:\ProgramData\Anaconda3\lib\ctypes\__init__.py", line 364, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found'

How do I resolve this?

Body:
It is because you are using a CUDA variant of PyTorch on a system that doesn’t have GPU driver installed.
If you don’t have a Nvidia GPU card, please install the cpu-only package according to the commands on:

Conda

conda install pytorch torchvision cpuonly -c pytorch

Pip

pip install torch==1.5.0+cpu torchvision==0.6.0+cpu -f

Or:

conda install PyTorch -c PyTorch

Or:

pip3 install torchvision


问:
C# DateTime to UTC Time without changing the time
How would I convert a preexisting datetime to UTC time without changing the actual time.

Example:

```<code>DateTime dateTime = GetSomeDateTime(); // dateTime here is 3pm
dateTime.ToUtcDateTime() // datetime should still be 3pm
</code>```

答: Use the DateTime.ToUniversalTime method.

Body:
How would I convert a preexisting datetime to UTC time without changing the actual time.

Example:

DateTime dateTime = GetSomeDateTime(); // dateTime here is 3pm
dateTime.ToUtcDateTime() // datetime should still be 3pm


问:
How to hide 'note: ... ' gcc output for external headers?
I try to compile my testproject with gcc 4.8.5. To exclude a warning messages from third-party code I put all external headers into my header - external.h:

```<code>#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wall"
...
#include "Object.h"
...
#pragma GCC diagnostic pop
</code>```

This works fine for warnings, but I see in gcc output many messages like below:

```<code>In file included from /home/testuser/testproject/external.h:26:0,
             from /home/testuser/testproject/main.cpp:14:
/home/testuser/externallib/Object.h: In instantiation of ‘int ObjectImpl<T_Class, T_Type, T_Size>::addChild(IObj*, unsigned int) [with T_Class = Shape; ObjType T_Type = (ObjType)12u; unsigned int T_Size = 20u:
/home/testuser/externallib/Object.h:1618:43:   required from here
/home/testuser/externallib/Object.h:817:5: note: declarations in dependent base ‘ObjBase’ are not found by unqualified lookup
/home/testuser/externallib/Object.h:817:5: note: use ‘this->get_Obj’ instead
</code>```

...

Unfortunately, I can't change the third-party code to hide that messages. Could anyone provide a way how to hide 'note:' messages when project builds? This will make my build-logs more clean :). Thanks in advance.

答:
Taken from here:
https://unix.stackexchange.com/questions/547567/want-to-turn-off-note-level-messages-in-gcc

Adding:

```<code>-fcompare-debug-second
</code>```

to the GCC build string worked for me.

Body:
I try to compile my testproject with gcc 4.8.5. To exclude a warning messages from third-party code I put all external headers into my header - external.h:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wall"
...
#include "Object.h"
...
#pragma GCC diagnostic pop

This works fine for warnings, but I see in gcc output many messages like below:

In file included from /home/testuser/testproject/external.h:26:0,
             from /home/testuser/testproject/main.cpp:14:
/home/testuser/externallib/Object.h: In instantiation of ‘int ObjectImpl<T_Class, T_Type, T_Size>::addChild(IObj*, unsigned int) [with T_Class = Shape; ObjType T_Type = (ObjType)12u; unsigned int T_Size = 20u:
/home/testuser/externallib/Object.h:1618:43:   required from here
/home/testuser/externallib/Object.h:817:5: note: declarations in dependent base ‘ObjBase’ are not found by unqualified lookup
/home/testuser/externallib/Object.h:817:5: note: use ‘this->get_Obj’ instead

...

Unfortunately, I can't change the third-party code to hide that messages. Could anyone provide a way how to hide 'note:' messages when project builds? This will make my build-logs more clean :). Thanks in advance.

Body:
Taken from here:
https://unix.stackexchange.com/questions/547567/want-to-turn-off-note-level-messages-in-gcc

Adding:

-fcompare-debug-second

to the GCC build string worked for me.


问:
ngbpopover placement always showing left in angular9 using bootstrap@4.5
I am using ngbPopover bootstrap in my application, I have upgraded my App from 5 to 9 version and updated bootstrap version 4.5 and @ng-bootstrap6. After upgrade this popover is always displaying left. I tried changing placement options but no use.

how can i move it to right ? did any one face similar kind of issues ? I tried installing popover.js and J QUERY as well but no use. always placement stick to left.

```<code><li class="nav-item main-menu-right-option">
          <a class="nav-link link-icon" href="javascript: void(0)" [ngbPopover]="alertsModal" #popoverAlert="ngbPopover" placement="bottom-right">
            <i class="icon icon-alert">
              <span class="icon icon-dot icon-custom-dot"></span>
            </i>
            <span class="d-inline-block d-sm-none nav-link-text">Alert</span>
          </a>
</li>
<ng-template #alertsModal let-c="close" let-d="dismiss">
    <div class="modal-header">
        <div class="modal-title align-self-center">alerts</div>
    </div>
</ng-template>
</code>```

Please let me know if needed any more details.

Thank you,
Praveen

答:
I was missing autoClose option in html and there is texttransform style overriding ngbpopover styles in my project.
I added autoClose as false and removed texttransform styles. working as expected.

Thank you.

Body:
I am using ngbPopover bootstrap in my application, I have upgraded my App from 5 to 9 version and updated bootstrap version 4.5 and @ng-bootstrap6. After upgrade this popover is always displaying left. I tried changing placement options but no use.

how can i move it to right ? did any one face similar kind of issues ? I tried installing popover.js and J QUERY as well but no use. always placement stick to left.

            Alert

<ng-template #alertsModal let-c="close" let-d="dismiss">

alerts

</ng-template>

Please let me know if needed any more details.

Thank you,
Praveen


问:
Python vectorizing nested for loops in image processing
I am trying to detect skin. I found a nice and easy formula to detect skin from RGB picture. The only problem is, that for loops are very slow, and I need to accelerate the process. I've done some researching and vectorization could fasten my for-loops, but I don't know how to use it in my case.

Here is code of my function:

Function receives 1 parameter of type: numpy array, with shape of (144x256x3), dtype=np.uint8

Function returns coordinates of first detected skin colored pixel(as numpy.array [height,width]); number of skin detected pixels(int) and calculated angle (from left to right) of first skin detected picture(float)

```<code># picture = npumpy array, with 144x256x3 shape, dtype=np.uint8
def filter_image(picture):
    r = 0.0
    g = 0.0
    b = 0.0

    # In first_point I save first occurrence of skin colored pixel, so I can track person movement
    first_point = np.array([-1,-1])

    # counter is used to count how many skin colored pixels are in an image (to determine distance to target, because LIDAR isn't working)
    counter = 0

    # angle of first pixel with skin color (from left to right, calculated with Horizontal FOV)
    angle = 0.0

    H = picture.shape[0]
    W = picture.shape[1]

    # loop through each pixel
    for i in range(H):
        for j in range(W):
            # if all RGB are 0(black), we take with next pixel
            if(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2])) == 0:
               continue
            #else we calculate r,g,b used for skin recognition
            else:
                r = picture[i,j][0]/(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2]))
                g = picture[i,j][1]/(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2]))
                b = picture[i,j][2]/(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2]))
            # if one of r,g,b calculations are 0, we take next pixel
            if(g == 0 or r == 0 or b == 0):
                continue
            # if True, pixel is skin colored
            elif(r/g > 1.185 and (((r * b) / math.pow(r + b + g,2)) > 0.107) and ((r * g) / math.pow(r + b + g,2)) > 0.112):
                # if this is the first point with skin colors in the whole image, we save i,j coordinate
                if(first_point[0] == -1):
                    # save first skin color occurrence
                    first_point[0] = i
                    first_point[1] = j

                    # here angle is calculated, with width skin pixel coordinate, Hor. FOV of camera and constant
                    angle = (j+1)*91 *0.00390626

                # whenever we detect skin colored pixel, we increment the counter value
                counter += 1
                continue
    # funtion returns coordinates of first skin colored pixel, counter of skin colored pixels and calculated angle(from left to right based on j coordinate of first pixel with skin color)
    return first_point,counter, angle
</code>```

Function works well, the only problem is its speed!

Thank you, for helping!

答:
You can skip all of the loops and do the operation with numpy's broadcasting. The process becomes even easier if the image is reshaped to 2D from 3D, giving you HxW rows of pixels to work with.</p>

```<code>def filter(picture):
    H,W = picture.shape[0],picture.shape[1]
    picture = picture.astype('float').reshape(-1,3)
    # A pixel with any r,g,b equalling zero can be removed.
    picture[np.prod(picture,axis=1)==0] = 0

    # Divide non-zero pixels by their rgb sum
    picsum = picture.sum(axis=1)
    nz_idx = picsum!=0
    picture[nz_idx] /= (picsum[nz_idx].reshape(-1,1))

    nonzeros = picture[nz_idx]

    # Condition 1: r/g > 1.185
    C1 = (nonzeros[:,0]/nonzeros[:,1]) > 1.185
    # Condition 2: r*b / (r+g+b)^2 > 0.107
    C2 = (nonzeros[:,0]*nonzeros[:,2])/(nonzeros.sum(axis=1)**2) > 0.107
    # Condition 3: r*g / (r+g+b)^2 > 0.112
    C3 = (nonzeros[:,0]*nonzeros[:,1])/(nonzeros.sum(axis=1)**2) > 0.112
    # Combine conditions
    C = ((C1*C2*C3)!=0)
    picsum[nz_idx] = C
    skin_points = np.where(picsum!=0)[0]
    first_point = np.unravel_index(skin_points[0],(H,W))
    counter = len(skin_points)
    angle = (first_point[1]+1) * 91 * 0.00390626
    return first_point, counter, angle
</code>```

Body:
I am trying to detect skin. I found a nice and easy formula to detect skin from RGB picture. The only problem is, that for loops are very slow, and I need to accelerate the process. I've done some researching and vectorization could fasten my for-loops, but I don't know how to use it in my case.

Here is code of my function:

Function receives 1 parameter of type: numpy array, with shape of (144x256x3), dtype=np.uint8

Function returns coordinates of first detected skin colored pixel(as numpy.array [height,width]); number of skin detected pixels(int) and calculated angle (from left to right) of first skin detected picture(float)

# picture = npumpy array, with 144x256x3 shape, dtype=np.uint8
def filter_image(picture):
    r = 0.0
    g = 0.0
    b = 0.0

    # In first_point I save first occurrence of skin colored pixel, so I can track person movement
    first_point = np.array([-1,-1])

    # counter is used to count how many skin colored pixels are in an image (to determine distance to target, because LIDAR isn't working)
    counter = 0

    # angle of first pixel with skin color (from left to right, calculated with Horizontal FOV)
    angle = 0.0

    H = picture.shape[0]
    W = picture.shape[1]

    # loop through each pixel
    for i in range(H):
        for j in range(W):
            # if all RGB are 0(black), we take with next pixel
            if(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2])) == 0:
               continue
            #else we calculate r,g,b used for skin recognition
            else:
                r = picture[i,j][0]/(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2]))
                g = picture[i,j][1]/(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2]))
                b = picture[i,j][2]/(int(picture[i,j][0]+picture[i,j][1]+picture[i,j][2]))
            # if one of r,g,b calculations are 0, we take next pixel
            if(g == 0 or r == 0 or b == 0):
                continue
            # if True, pixel is skin colored
            elif(r/g > 1.185 and (((r * b) / math.pow(r + b + g,2)) > 0.107) and ((r * g) / math.pow(r + b + g,2)) > 0.112):
                # if this is the first point with skin colors in the whole image, we save i,j coordinate
                if(first_point[0] == -1):
                    # save first skin color occurrence
                    first_point[0] = i
                    first_point[1] = j

                    # here angle is calculated, with width skin pixel coordinate, Hor. FOV of camera and constant
                    angle = (j+1)*91 *0.00390626

                # whenever we detect skin colored pixel, we increment the counter value
                counter += 1
                continue
    # funtion returns coordinates of first skin colored pixel, counter of skin colored pixels and calculated angle(from left to right based on j coordinate of first pixel with skin color)
    return first_point,counter, angle

Function works well, the only problem is its speed!

Thank you, for helping!

Body:
You can skip all of the loops and do the operation with numpy's broadcasting. The process becomes even easier if the image is reshaped to 2D from 3D, giving you HxW rows of pixels to work with.

def filter(picture):
    H,W = picture.shape[0],picture.shape[1]
    picture = picture.astype('float').reshape(-1,3)
    # A pixel with any r,g,b equalling zero can be removed.
    picture[np.prod(picture,axis=1)==0] = 0

    # Divide non-zero pixels by their rgb sum
    picsum = picture.sum(axis=1)
    nz_idx = picsum!=0
    picture[nz_idx] /= (picsum[nz_idx].reshape(-1,1))

    nonzeros = picture[nz_idx]

    # Condition 1: r/g > 1.185
    C1 = (nonzeros[:,0]/nonzeros[:,1]) > 1.185
    # Condition 2: r*b / (r+g+b)^2 > 0.107
    C2 = (nonzeros[:,0]*nonzeros[:,2])/(nonzeros.sum(axis=1)**2) > 0.107
    # Condition 3: r*g / (r+g+b)^2 > 0.112
    C3 = (nonzeros[:,0]*nonzeros[:,1])/(nonzeros.sum(axis=1)**2) > 0.112
    # Combine conditions
    C = ((C1*C2*C3)!=0)
    picsum[nz_idx] = C
    skin_points = np.where(picsum!=0)[0]
    first_point = np.unravel_index(skin_points[0],(H,W))
    counter = len(skin_points)
    angle = (first_point[1]+1) * 91 * 0.00390626
    return first_point, counter, angle


问:
How to query CRM Dynamics entities using raw TSQL only instead of Web API and Org Service?
I'm helping migrate my company from CRM 2011 to CRM Dynamics online. Many of the applications we use currently run TSQL in order to obtain entities. Is it possible to execute TSQL against this latest new version of Microsoft CRM in order to obtain entities? Am I limited in using the Web API and Org service in order to obtain entities or is there some way for me to execute raw TSQL?

I'd like to have the option to use TSQL if possible. I understand the Web API service is the latest approach to obtaining entities using a REST API. However, I don't want to be limited to this. Is this possible?

答:
TSQL access to the CDS and D365 should now be possible as MS has just announced a TSQL end point for CDS. You can execute SQL against entities, like the example below, on Dynamics but in read only though.

```<code>select top 5 a.name as [VIP customer], a.address1_postalcode as [ZIP code] from account a order by a.address1_postalcode desc
</code>```

The link below from MS describes how to set this up in SSMS,

https://learn.microsoft.com/en-us/powerapps/developer/common-data-service/cds-sql-query

Also, the following link is a very useful blog on getting it up and running, you may have to update EnableTDSEndpoint tag to true manually within the orgdborgsettings field in the organization entity.

https://markcarrington.dev/2020/05/13/cds-t-sql-endpoint-pt-1-connecting/

Credit to Mark Carrington

Body:
TSQL access to the CDS and D365 should now be possible as MS has just announced a TSQL end point for CDS. You can execute SQL against entities, like the example below, on Dynamics but in read only though.

select top 5 a.name as [VIP customer], a.address1_postalcode as [ZIP code] from account a order by a.address1_postalcode desc

The link below from MS describes how to set this up in SSMS,

https://learn.microsoft.com/en-us/powerapps/developer/common-data-service/cds-sql-query

Also, the following link is a very useful blog on getting it up and running, you may have to update EnableTDSEndpoint tag to true manually within the orgdborgsettings field in the organization entity.

https://markcarrington.dev/2020/05/13/cds-t-sql-endpoint-pt-1-connecting/

Credit to Mark Carrington


问:
How to transpose data with many columns in SAS
Hi I new in SAS and I have a problem. I have the data which contains 337 rows and 64 columns.
It looks like this:
enter image description here
I need to make like this:
enter image description here

I've tried to use proc transpose, but I felt.
Please help.

答:
You will need to TRANSPOSE BY DATE and then SORT by country date, I presume country is from the label of the original variables.

Example:
3 dates and 5 variables, easily changed for larger data.

```<code>data total_returns(label='Example data');
  do date = '01jan2020'd to '03jan2020'd;
    array RI RI_1-RI_5;
    do over ri;
      demo_value + 1;
      RI = demo_value;
    end;
    output;
  end;
  label
    RI_1 = 'MSCI Country Biff blah blah blah'
    RI_2 = 'MSCI Country Bam blah blah blah'
    RI_3 = 'MSCI Country Boom blah blah blah'
    RI_4 = 'MSCI Country Zwok blah blah blah'
    RI_5 = 'MSCI Country Pow blah blah blah'
  ;
  format date yymmdd10.;
  drop demo_value;
run;

proc transpose
  data=total_returns
  out=stage1 (
    drop=_name_
    rename= ( _label_=Country
              col1 = RI
            )
  )
;
  by date;
  var RI_1-RI_5;
  label country = ' ';
run;

proc sort data=stage1 out=want;
  by country date;
run;

proc print label data=total_returns;
  title "Original, across/array layout";
proc print data=want;
  title "Transposed and Sorted, categorical/vector layout";
run;
</code>```

Output:

Body:
You will need to TRANSPOSE BY DATE and then SORT by country date, I presume country is from the label of the original variables.

Example:
3 dates and 5 variables, easily changed for larger data.

data total_returns(label='Example data');
  do date = '01jan2020'd to '03jan2020'd;
    array RI RI_1-RI_5;
    do over ri;
      demo_value + 1;
      RI = demo_value;
    end;
    output;
  end;
  label
    RI_1 = 'MSCI Country Biff blah blah blah'
    RI_2 = 'MSCI Country Bam blah blah blah'
    RI_3 = 'MSCI Country Boom blah blah blah'
    RI_4 = 'MSCI Country Zwok blah blah blah'
    RI_5 = 'MSCI Country Pow blah blah blah'
  ;
  format date yymmdd10.;
  drop demo_value;
run;

proc transpose
  data=total_returns
  out=stage1 (
    drop=_name_
    rename= ( _label_=Country
              col1 = RI
            )
  )
;
  by date;
  var RI_1-RI_5;
  label country = ' ';
run;

proc sort data=stage1 out=want;
  by country date;
run;

proc print label data=total_returns;
  title "Original, across/array layout";
proc print data=want;
  title "Transposed and Sorted, categorical/vector layout";
run;

Output:


问:
Cannot Implicitly convert Type, UNITY
I am going to make a save system to save my highscore in my unity game but gives me two errors
this is first code to data,,,

```<code>public class SaveHighScore
{
    public int highScore;

    public SaveHighScore(HighScore highscore)
    {
        highScore = highscore.highScore;
    }
}
</code>```

this is my second one to Save System

```<code>public class SaveSystem
{
     public static void SaveScore(HighScore highscore)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            string path = Application.persistentDataPath + "/player.fun";
            FileStream stream = new FileStream(path, FileMode.Create);

            SaveHighScore data = new SaveHighScore(highscore);
            formatter.Serialize(stream, data);
            stream.Close();
        }
        public static SaveHighScore loadHighScore()
        {
            string path = Application.persistentDataPath + "/player.fun";
            if (File.Exists(path))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                FileStream stream = new FileStream(path, FileMode.Open);
                HighScore data = formatter.Deserialize(stream) as SaveHighScore;
                stream.Close();
                return (SaveHighScore) data;
            }
            else
            {
                Debug.Log("no highScore found");
                return null;
            }
}
</code>```

this is my third and last code

```<code>public class HighScore : MonoBehaviour
{
    public int highScore;
    public void saveHighscore()
    {
        SaveSystem.SaveScore(this);
    }
    public void loadHighscore()
    {
        SaveHighScore data = SaveSystem.loadHighScore();
        highScore = data.highScore;
    }
}
</code>```

first code is to prepare data to save. second code is to make save system. third one is to make two functions to call when the player wants to load last high score.

but there gives two errors in second code.

SaveSystem.cs(24,30) Cannot implicitly convert type 'SaveHighScore' to 'HighScore'

and

SaveSystem.cs(26,20) Cannot implicitly convert type 'HighScore' to 'SaveHighScore'

i'm finding a solution for these errors.
i don't know how to solve these.

Anyone here to help me out????

答:
HighScore data = formatter.Deserialize(stream) as SaveHighScore;

You're deserializing a SaveHighScore but trying to save it in a HighScore, which is a MonoBehaviour component, and not at all the same thing you wish it to be.

Modify your code to

var data = formatter.Deserialize(stream) as SaveHighScore;

and I think everything should work.

Title: Cannot Implicitly convert Type, UNITY

Body:
I am going to make a save system to save my highscore in my unity game but gives me two errors
this is first code to data,,,

public class SaveHighScore
{
    public int highScore;

    public SaveHighScore(HighScore highscore)
    {
        highScore = highscore.highScore;
    }
}

this is my second one to Save System

public class SaveSystem
{
     public static void SaveScore(HighScore highscore)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            string path = Application.persistentDataPath + "/player.fun";
            FileStream stream = new FileStream(path, FileMode.Create);

            SaveHighScore data = new SaveHighScore(highscore);
            formatter.Serialize(stream, data);
            stream.Close();
        }
        public static SaveHighScore loadHighScore()
        {
            string path = Application.persistentDataPath + "/player.fun";
            if (File.Exists(path))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                FileStream stream = new FileStream(path, FileMode.Open);
                HighScore data = formatter.Deserialize(stream) as SaveHighScore;
                stream.Close();
                return (SaveHighScore) data;
            }
            else
            {
                Debug.Log("no highScore found");
                return null;
            }
}

this is my third and last code

public class HighScore : MonoBehaviour
{
    public int highScore;
    public void saveHighscore()
    {
        SaveSystem.SaveScore(this);
    }
    public void loadHighscore()
    {
        SaveHighScore data = SaveSystem.loadHighScore();
        highScore = data.highScore;
    }
}

first code is to prepare data to save. second code is to make save system. third one is to make two functions to call when the player wants to load last high score.

but there gives two errors in second code.

SaveSystem.cs(24,30) Cannot implicitly convert type 'SaveHighScore' to 'HighScore'

and

SaveSystem.cs(26,20) Cannot implicitly convert type 'HighScore' to 'SaveHighScore'

i'm finding a solution for these errors.
i don't know how to solve these.

Anyone here to help me out????


问:
Routing from a react app to get a server side rendered HTML generated from handlebars
My react app is running at localhost:3000 and my Node server is running at localhost:5000.

I have a button named Book in my React app at the route localhost:3000/. When the button is clicked, i want to render a page(generated by handlebars templating engine) that the route localhost:5000/book renders.

Actually I am very confused right now. I know that localhost:5000/book will render the page. But how do I render that page when clicked the book button from the react code at localhost:3000/.

I know, I can't href to localhost:3000/book, since it would be react's url and not the server's url.
Hence I tried to get the page as a request through axios. But it isn't working. (I know i am doing it wrongly).

The point is how should I route to localhost:5000/book and get it rendered through my react app when I click the book button?

My Node code

```<code>app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

// Routes
app.get('/book', (req, res) => {
    res.render('book');
})

</code>```

答:
You can add a redirect handler on click of your book button

```<code>redirect = () => {
  window.location.href = 'http://localhost:5000/book';
  return null;
}
</code>```

Body:
My react app is running at localhost:3000 and my Node server is running at localhost:5000.

I have a button named Book in my React app at the route localhost:3000/. When the button is clicked, i want to render a page(generated by handlebars templating engine) that the route localhost:5000/book renders.

Actually I am very confused right now. I know that localhost:5000/book will render the page. But how do I render that page when clicked the book button from the react code at localhost:3000/.

I know, I can't href to localhost:3000/book, since it would be react's url and not the server's url.
Hence I tried to get the page as a request through axios. But it isn't working. (I know i am doing it wrongly).

The point is how should I route to localhost:5000/book and get it rendered through my react app when I click the book button?

My Node code

app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

// Routes
app.get('/book', (req, res) => {
    res.render('book');
})

Body:
You can add a redirect handler on click of your book button

redirect = () => {
  window.location.href = 'http://localhost:5000/book';
  return null;
}


问:
SQL trying to use a column from a joined table in a subquery
Here is what I currently have which returns 3 columns for patient_id, group_concat_1, and group_concat_2:

```<code>SELECT patient_id,
(SELECT GROUP_CONCAT(column1) FROM
table1 where patient_id = patient.id
) group_concat_1,
(SELECT GROUP_CONCAT(column1) FROM
table2 where patient_id = patient.id
) group_concat_2
FROM patient
</code>```

However, I need to return a single column with group_concat_1 and group_concat_2 combined, so I tried this:

```<code>SELECT patient_id,
SELECT CONCAT(group_concat_1, group_concat_2) FROM (
    (SELECT GROUP_CONCAT(column1) FROM
    table1 where patient_id = patient.id
    ) group_concat_1,
    (SELECT GROUP_CONCAT(column1) FROM
    table2 where patient_id = patient.id
    ) group_concat_2
)
FROM patient
</code>```

But his clearly doesn't work since now it can't find patient.id in the inner subquery. Any advice? Thanks!

答:
You can concatenate directly the 2 columns:</p>

```<code>SELECT p.patient_id,
  CONCAT(
    (SELECT GROUP_CONCAT(column1) FROM table1 where patient_id = p.patient.id),
    (SELECT GROUP_CONCAT(column1) FROM table2 where patient_id = p.patient.id)
  )
FROM patient p
</code>```

Body:
Here is what I currently have which returns 3 columns for patient_id, group_concat_1, and group_concat_2:

SELECT patient_id,
(SELECT GROUP_CONCAT(column1) FROM
table1 where patient_id = patient.id
) group_concat_1,
(SELECT GROUP_CONCAT(column1) FROM
table2 where patient_id = patient.id
) group_concat_2
FROM patient

However, I need to return a single column with group_concat_1 and group_concat_2 combined, so I tried this:

SELECT patient_id,
SELECT CONCAT(group_concat_1, group_concat_2) FROM (
    (SELECT GROUP_CONCAT(column1) FROM
    table1 where patient_id = patient.id
    ) group_concat_1,
    (SELECT GROUP_CONCAT(column1) FROM
    table2 where patient_id = patient.id
    ) group_concat_2
)
FROM patient

But his clearly doesn't work since now it can't find patient.id in the inner subquery. Any advice? Thanks!

Body:
You can concatenate directly the 2 columns:

SELECT p.patient_id,
  CONCAT(
    (SELECT GROUP_CONCAT(column1) FROM table1 where patient_id = p.patient.id),
    (SELECT GROUP_CONCAT(column1) FROM table2 where patient_id = p.patient.id)
  )
FROM patient p


问:
Lights in A-Frame have striped artifacts depending on distance from them
I am using the latest A-Frame 1.0.4 and I have tried both with spot light (in the picture attached) and with direct light.

The shadowBias is set to -0.0001, changing it affects the artifact only slightly.

If I set the shadowMapHeight and shadowMapWidth to 1024 the artifact shrinks back a bit from the source of light. To have it completely disappear I have to put 4096, which is a bit too much, performance-wise. I can't have all lights with a 4k shadow map.

A similar effect has increasing the shadowCamera far, from 500 to 5000 for example. but this introduces wrong shadows, distant from the objects (even if I tweak the shadowBias).

Am I doing something wrong? Why the lights with default settings have these problems? Does it perhaps depend on the models ?

Any clue would be appreciated

答:
I downloaded a fairly complex, animated model (this one) as glTF from Sketchfab and manged to get the shadows right(-ish) with these parameters:

```<code><a-entity shadow="cast: true; receive: true" id="model1" gltf-model="scene.gltf"
  position="6 1.5 -12" scale="0.5 0.5 0.5" animation-mixer>
</a-entity>

<a-entity light="type: ambient; intensity:0.1;"></a-entity>

<a-entity id="sun" light="type: directional; color: #FFF; intensity: 0.9; castShadow: true; shadowCameraFar: 500;
    shadowCameraVisible: false;
    shadowBias: -0.001;
    shadowMapHeight:2048; shadowMapWidth:2048;
    shadowCameraLeft: -50; shadowCameraRight: 50;
    shadowCameraBottom: -50; shadowCameraTop: 50;" position="10 50 -10">
</a-entity>
</code>```

The result looked good:

but you can still see some artefacts. Additionally it was just a tad too much stress for the Oculus Quest.

Overall, I (re)turned to shadow baking for my own models which of course doesn't help with animated models.

I do remember that I had one model that showed this effect due to z-buffer fighting, not the shadows.

So maybe you start with this model, adjust the parameters accordingly, find the same results as me, and then you throw your model in there.

Maybe this helps.

Body:
I downloaded a fairly complex, animated model (this one) as glTF from Sketchfab and manged to get the shadows right(-ish) with these parameters:

<a-entity shadow="cast: true; receive: true" id="model1" gltf-model="scene.gltf"
  position="6 1.5 -12" scale="0.5 0.5 0.5" animation-mixer>
</a-entity>

<a-entity light="type: ambient; intensity:0.1;"></a-entity>

<a-entity id="sun" light="type: directional; color: #FFF; intensity: 0.9; castShadow: true; shadowCameraFar: 500;
    shadowCameraVisible: false;
    shadowBias: -0.001;
    shadowMapHeight:2048; shadowMapWidth:2048;
    shadowCameraLeft: -50; shadowCameraRight: 50;
    shadowCameraBottom: -50; shadowCameraTop: 50;" position="10 50 -10">
</a-entity>

The result looked good:

but you can still see some artefacts. Additionally it was just a tad too much stress for the Oculus Quest.

Overall, I (re)turned to shadow baking for my own models which of course doesn't help with animated models.

I do remember that I had one model that showed this effect due to z-buffer fighting, not the shadows.

So maybe you start with this model, adjust the parameters accordingly, find the same results as me, and then you throw your model in there.

Maybe this helps.


问:
R shiny RenderDT format specific cell in table output
I am trying to format a SPECIFIC cell in a R shiny dashboard data table (using renderDT).

In the UI I use the following line of code:

```<code>DTOutput('dt_vols')
</code>```

I also include this line in the UI as I dont want to display column names (not sure if that is relevant to the problem)

```<code>tags$head(tags$style(type = "text/css", "#dt_vols th {display:none;}")),

</code>```

In the server code, I first create the following reactive 2x2 matrix (called dt_vols) - I've simplified the matrix in the example

```<code>dt_vols <- reactive({

    mtx_vols <- matrix(1:4, nrow = 2, ncol = 2)

    return(mtx_vols)

  })
</code>```

Then I render the DT table as follows:

```<code>  output$dt_vols = renderDT(

    dt_vols(), options = list(pageLength = 4, dom = 't', autoWidth = FALSE), rownames= FALSE,
    formatStyle(dt_vols(), columns = 1, border = '1px solid #ddd')

  )
</code>```

It works until I add the formatstyle line. I am not sure how to get this line right and to get it pointing a specific cell (for example row1, column2). It seems to have a problem with the column argument. If i run the below I get the following error:

```<code>Warning: Error in : $ operator is invalid for atomic vectors
</code>```

答:
formatStyle expects a table object created from datatable() as input - you passed a matrix, which results in the error.

Please check the following:

```<code>library(shiny)
library(DT)

ui <- fluidPage(DTOutput('dt_vols'),
                tags$head(tags$style(type = "text/css", "#dt_vols th {display:none;}")))

server <- function(input, output, session) {
  dt_vols <- reactive({
    mtx_vols <- matrix(1:4, nrow = 2, ncol = 2)

    return(mtx_vols)

  })

  output$dt_vols = renderDT({
    myTable <- datatable(dt_vols(),
                         options = list(pageLength = 4, dom = 't', autoWidth = FALSE),
                         rownames = FALSE
    )

    formatStyle(myTable, columns = 1, border = '10px solid #ddd')
  })
}

shinyApp(ui, server)
</code>```

Body:
I am trying to format a SPECIFIC cell in a R shiny dashboard data table (using renderDT).

In the UI I use the following line of code:

DTOutput('dt_vols')

I also include this line in the UI as I dont want to display column names (not sure if that is relevant to the problem)

tags$head(tags$style(type = "text/css", "#dt_vols th {display:none;}")),

In the server code, I first create the following reactive 2x2 matrix (called dt_vols) - I've simplified the matrix in the example

dt_vols <- reactive({

    mtx_vols <- matrix(1:4, nrow = 2, ncol = 2)

    return(mtx_vols)

  })

Then I render the DT table as follows:

  output$dt_vols = renderDT(

    dt_vols(), options = list(pageLength = 4, dom = 't', autoWidth = FALSE), rownames= FALSE,
    formatStyle(dt_vols(), columns = 1, border = '1px solid #ddd')

  )

It works until I add the formatstyle line. I am not sure how to get this line right and to get it pointing a specific cell (for example row1, column2). It seems to have a problem with the column argument. If i run the below I get the following error:

Warning: Error in : $ operator is invalid for atomic vectors

Body:
formatStyle expects a table object created from datatable() as input - you passed a matrix, which results in the error.

Please check the following:

library(shiny)
library(DT)

ui <- fluidPage(DTOutput('dt_vols'),
                tags$head(tags$style(type = "text/css", "#dt_vols th {display:none;}")))

server <- function(input, output, session) {
  dt_vols <- reactive({
    mtx_vols <- matrix(1:4, nrow = 2, ncol = 2)

    return(mtx_vols)

  })

  output$dt_vols = renderDT({
    myTable <- datatable(dt_vols(),
                         options = list(pageLength = 4, dom = 't', autoWidth = FALSE),
                         rownames = FALSE
    )

    formatStyle(myTable, columns = 1, border = '10px solid #ddd')
  })
}

shinyApp(ui, server)