问:
Windows task scheduler created programmatically in C# not running automatically
I have created windows task scheduler programmatically in c#. Task is created successfully and is scheduled to run correctly. At scheduled time, it says task is running but without any result and next schedule time is updated.

But last run time and last run result does not update.

Last run result is: The task has not yet run.(0x41303)

But when run manually from task scheduler it executes successfully but not automatically.

Below code that i used to create task

```<code>var ts = new TaskService();
var td = ts.NewTask();
td.RegistrationInfo.Author = "My company";
td.RegistrationInfo.Description = "Runs test application";
var trigger = new WeeklyTrigger { StartBoundary = startDate, DaysOfWeek = daysOfWeek, Enabled = enabled };
trigger.Repetition.Interval = TimeSpan.FromSeconds(((minutes == 0) ? 60 : minutes) * 60);
td.Triggers.Add(trigger);
var action = new ExecAction(Assembly.GetExecutingAssembly().Location, null, null);
if (filePath != string.Empty && File.Exists(filePath))
{
    action = new ExecAction(filePath);
}
action.Arguments = "AutoRun";
td.Actions.Add(action);
ts.RootFolder.RegisterTaskDefinition(TaskName, td);
</code>```

Any help would be much appreciated!

答:
Check the execution privileges first.
Then check the task manager if the process is really running when it seems 'running'. If yes, try to use some try-catch blocks and create event logs as exceptions.

I think when you run manually from task scheduler, its executed by a user that belongs to task scheduler (maybe administrator). But at scheduled time, application trying to be executed as a user that won't have enough privileges to do some stuff in your code.

UPDATE

Set Start in (optional) value to target file location. Without it,
the task scheduler runs in system32 folder but like i said before,
target application wouldn't have privileges to run in system32.

Try to change the version of the console application to 32 bit.

i.e. Right click  Goto  -> Properties -> Build ->  Platform Target
= x86.

Body:
I have created windows task scheduler programmatically in c#. Task is created successfully and is scheduled to run correctly. At scheduled time, it says task is running but without any result and next schedule time is updated.

But last run time and last run result does not update.

Last run result is: The task has not yet run.(0x41303)

But when run manually from task scheduler it executes successfully but not automatically.

Below code that i used to create task

var ts = new TaskService();
var td = ts.NewTask();
td.RegistrationInfo.Author = "My company";
td.RegistrationInfo.Description = "Runs test application";
var trigger = new WeeklyTrigger { StartBoundary = startDate, DaysOfWeek = daysOfWeek, Enabled = enabled };
trigger.Repetition.Interval = TimeSpan.FromSeconds(((minutes == 0) ? 60 : minutes) * 60);
td.Triggers.Add(trigger);
var action = new ExecAction(Assembly.GetExecutingAssembly().Location, null, null);
if (filePath != string.Empty && File.Exists(filePath))
{
    action = new ExecAction(filePath);
}
action.Arguments = "AutoRun";
td.Actions.Add(action);
ts.RootFolder.RegisterTaskDefinition(TaskName, td);

Any help would be much appreciated!


来源: stackexchange

问:
Check if string contains no characters except numbers?
I need to check if a string contains NO other characters except numbers (0,1,2,3,4,5,6,7,8,9).

I'm expecting the user to input a time (12:00). I explode() the input to seperate the hours and minutes. I now need to make sure the time is an actual time value.

```<code>$time = explode(":",$time);

if ($time['0'] > 12 || $time['0'] < 1 || not_actual_numbers)
{
    //error: not valid hour
    echo("error: time val hour is bad");
}
</code>```

答:
You can use is_int

```<code>$time = explode(":",$time);

if ($time['0'] > 12 || $time['0'] < 1 || !is_int($time[0]))
{
    //error: not valid hour
    echo("error: time val hour is bad");
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to check if a string contains NO other characters except numbers (0,1,2,3,4,5,6,7,8,9).

I'm expecting the user to input a time (12:00). I explode() the input to seperate the hours and minutes. I now need to make sure the time is an actual time value.

$time = explode(":",$time);

if ($time['0'] > 12 || $time['0'] < 1 || not_actual_numbers)
{
    //error: not valid hour
    echo("error: time val hour is bad");
}

Body:
You can use is_int

$time = explode(":",$time);

if ($time['0'] > 12 || $time['0'] < 1 || !is_int($time[0]))
{
    //error: not valid hour
    echo("error: time val hour is bad");
}


问:
Is it possible to fwrite from specific starting index in C?
For example,

```<code>    char ch[50] = "ABCDEFGH";
    FILE *fp;
    fp = fopen("test.txt","w");
    fwrite(ch,1,6,fp);

</code>```

this codes writes "ABCDEF" to the file. But I need to write "BCDEFG" to the file. It will be perfect if that can be done without making any substring.

答:
In order to write BCDEFG from the same string, just pass a pointer to the second byte of the array ch to fwrite:

```<code>char ch[50] = "ABCDEFGH";
FILE *fp = fopen("test.txt", "w");
if (fp != NULL) {
    fwrite(ch + 1, 1, 6, fp);
    ...
}
</code>```

Note that you can also use the string literal, which is a constant array of characters, directly:

```<code>FILE *fp = fopen("test.txt", "w");
if (fp != NULL) {
    fwrite("ABCDEFGH" + 1, 1, 6, fp);
    ...
}
</code>```

"ABCDEFGH" + 1 is the same as &"ABCDEFGH"[1], the address of the second byte of the string. Arrays decay as pointers to their first element when used in expressions, except as the argument of sizeof and _Alignof.

ContentLicense: CC BY-SA 4.0

Body:
For example,

    char ch[50] = "ABCDEFGH";
    FILE *fp;
    fp = fopen("test.txt","w");
    fwrite(ch,1,6,fp);

this codes writes "ABCDEF" to the file. But I need to write "BCDEFG" to the file. It will be perfect if that can be done without making any substring.

Body:
In order to write BCDEFG from the same string, just pass a pointer to the second byte of the array ch to fwrite:

char ch[50] = "ABCDEFGH";
FILE *fp = fopen("test.txt", "w");
if (fp != NULL) {
    fwrite(ch + 1, 1, 6, fp);
    ...
}

Note that you can also use the string literal, which is a constant array of characters, directly:

FILE *fp = fopen("test.txt", "w");
if (fp != NULL) {
    fwrite("ABCDEFGH" + 1, 1, 6, fp);
    ...
}

"ABCDEFGH" + 1 is the same as &"ABCDEFGH"[1], the address of the second byte of the string. Arrays decay as pointers to their first element when used in expressions, except as the argument of sizeof and _Alignof.


问:
.htaccess rule slight help needed
I have spent hours trying to get this rule right and I am really struggling. I have got so close but I can not get it right. Any help is more than welcome... Thank you #

Trying to remove unwanted segments in the URL. From this:

https://example.com/index.php/module/action/param1/static/PFBC/js/jquery/rss/static/css/js/jquery/smoothness/templates/themes/datelove/img/icon/xml/sitemap/user/help/rss/legal/rss/comment-picture

To this:

https://example.com/comment-picture

The segments are random in name and in quantity, this is the rules I have so far

RewriteEngine on

RewriteCond %{REQUEST_URI} (\^|~|`|<|>|,|%|\\|\{|\}|\[|\]|\|)/ [NC]

RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

It almost works but I need the last segment to be left, this rule gives a new URL of

The new url is https://example.com/
Test are stopped, a redirect will be made with status code 301

What is needed to leave the final segment?

I am getting closer

RewriteCond %{REQUEST_URI} (^https:.*?com|\/[\w+-]+$) ~gm [NC]

RewriteRule ^https:.*?com|\/(.*)[\w+-]+$(.*) $2 [R=301,L]

Gives me

https://example.com/index.php

So selecting the wrong part of URL but getting closer!

答:
The code below will give the 2 string you are looking for.</p>

```<code>(^https:.*?com|\/[\w+-]+$)
</code>```

Title: .htaccess rule slight help needed

Body:
The code below will give the 2 string you are looking for.

(^https:.*?com|\/[\w+-]+$)


问:
Data is not saved in TextArea. Probably due to page refresh
I have code that works as I need. (If you select items in Select, then click Button. Selected value from Select should be copied and TextArea will be added and the cursor should be placed on the next line).
https://codesandbox.io/s/lingering-currying-mdksx

But when I transfer the module to another file. And now, when you click on the button, the entire page begins to refresh, and TextArea turns out to be empty. I think this is due to setState. How to save data in TextArea? I think need to get rid of page refresh. Bbut I dont know how.

Same code with the distant module
https://codesandbox.io/s/priceless-jennings-jkgef

P.S.
I don't know why, the ListBox file doesn't load in codesandbox, but everything works for me.

答:
Its not a magic. Just change < form > to

I don’t know how, but I drank coffee, returned for a PC and everything worked on my main project.

Body:
Its not a magic. Just change < form > to < div >

I don’t know how, but I drank coffee, returned for a PC and everything worked on my main project.


问:
TLSv1.2 on Azure PostgreSQL Server
I am trying to ensure that the PostgreSQL client's connection to Azure PostgreSQL server (version 10.7) is using TLSv1.2.  When I execute psql command, the connection header shows me protocol TLSv1.2:

```<code>[user ~]# psql -h psql_server.postgres.database.azure.com -p 5432 -U psql_admin_accnt@psql_server -W postgres
Password:
psql (10.7)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.
</code>```

Yet, when I query pg_stat_ssl table, I get information, that the current connection is using TLSv1.1 and cipher information isn't the same either.

```<code>postgres=> SELECT * FROM pg_stat_ssl;
  pid   | ssl | version |        cipher        | bits | compression | clientdn
--------+-----+---------+----------------------+------+-------------+----------
 168648 | t   | TLSv1.1 | ECDHE-RSA-AES256-SHA |  256 | f           |
(1 row)
</code>```

Which information is the correct one and I should rely on?  Does my psql connection really uses TLSv1.2 or it is TLSv1.1 as seen from PostgreSQL system tables.

答:
Seems the issue was fixed by Microsoft itself

```<code>[user@host ~]$ /usr/pgsql-10/bin/psql "host=psql_server.postgres.database.azure.com port=5432 dbname=dbname user=psql_admin_accnt@psql_server sslmode=require sslrootcert=/path/to/BaltimoreCyberTrustRoot.cer"
Password:
psql (10.11)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.

dbname=> SELECT * FROM pg_stat_ssl WHERE pid = pg_backend_pid();
  pid   | ssl | version |           cipher            | bits | compression | clientdn
--------+-----+---------+-----------------------------+------+-------------+----------
 812820 | t   | TLSv1.2 | ECDHE-RSA-AES256-GCM-SHA384 |  256 | f           |
(1 row)

dbname=> SELECT VERSION();
                           version
-------------------------------------------------------------
PostgreSQL 10.11, compiled by Visual C++ build 1800, 64-bit
(1 row)
</code>```

Now, the TLS version is correctly returned.

Title: TLSv1.2 on Azure PostgreSQL Server

Body:
I am trying to ensure that the PostgreSQL client's connection to Azure PostgreSQL server (version 10.7) is using TLSv1.2.  When I execute psql command, the connection header shows me protocol TLSv1.2:

[user ~]# psql -h psql_server.postgres.database.azure.com -p 5432 -U psql_admin_accnt@psql_server -W postgres
Password:
psql (10.7)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.

Yet, when I query pg_stat_ssl table, I get information, that the current connection is using TLSv1.1 and cipher information isn't the same either.

postgres=> SELECT * FROM pg_stat_ssl;
  pid   | ssl | version |        cipher        | bits | compression | clientdn
--------+-----+---------+----------------------+------+-------------+----------
 168648 | t   | TLSv1.1 | ECDHE-RSA-AES256-SHA |  256 | f           |
(1 row)

Which information is the correct one and I should rely on?  Does my psql connection really uses TLSv1.2 or it is TLSv1.1 as seen from PostgreSQL system tables.

Body:
Seems the issue was fixed by Microsoft itself

[user@host ~]$ /usr/pgsql-10/bin/psql "host=psql_server.postgres.database.azure.com port=5432 dbname=dbname user=psql_admin_accnt@psql_server sslmode=require sslrootcert=/path/to/BaltimoreCyberTrustRoot.cer"
Password:
psql (10.11)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.

dbname=> SELECT * FROM pg_stat_ssl WHERE pid = pg_backend_pid();
  pid   | ssl | version |           cipher            | bits | compression | clientdn
--------+-----+---------+-----------------------------+------+-------------+----------
 812820 | t   | TLSv1.2 | ECDHE-RSA-AES256-GCM-SHA384 |  256 | f           |
(1 row)

dbname=> SELECT VERSION();
                           version
-------------------------------------------------------------
PostgreSQL 10.11, compiled by Visual C++ build 1800, 64-bit
(1 row)

Now, the TLS version is correctly returned.


问:
How to get object of selected vuetify tab, not index?
By default, the v-tabs change event provides the index of the new tab. I'm facing issues with the wrong index if the tab items are dynamic.

```<code><v-tabs :slider-size=4 v-model="tabs" @change="tabChangeHandler">
        <div v-for="(obj) in computedMasterTabsList" :key="'div'+obj.key">
          <v-tab v-if="obj.permission" :key="obj.key" @click="tabClickHandler(obj)">{{obj.label}}
          </v-tab>
       </div>
</v-tabs>
</code>```

Dynamic tab list example:

```<code>[{key: 1, name:"A", permission: false, label:'Label A'}, {key: 2, name:"B", permission: true, label:'Label B'}, {key: 3, name:"C", permission: true, label:'Label C'}]
</code>```

Display Tabs: Who has permission: true

On change of tabs, getting selected tab value is 0 or 1.

I'm unable to get the selected object from the list using 0 and 1.

Can anyone help me out with this? Thanks in advance.

答:
You are using the tabClickHandler method just declare the selected_tab in data and use indexof method to get the selected tab index.

codepen - https://codepen.io/Pratik__007/pen/XWbXZKw?editors=1010;

```<code>this.selected_index = this.computedMasterTabsList.indexOf(obj);

mounted(){
    let i=0;
    for(i in this.computedMasterTabsList){
        if(this.computedMasterTabsList[i]['permission']==true){
          console.log(i)
          this.selected_index = i;
          break;
        }
    }
  }
</code>```

Body:
By default, the v-tabs change event provides the index of the new tab. I'm facing issues with the wrong index if the tab items are dynamic.

<v-tabs :slider-size=4 v-model="tabs" @change="tabChangeHandler">

          <v-tab v-if="obj.permission" :key="obj.key" @click="tabClickHandler(obj)">{{obj.label}}
          </v-tab>

</v-tabs>

Dynamic tab list example:

[{key: 1, name:"A", permission: false, label:'Label A'}, {key: 2, name:"B", permission: true, label:'Label B'}, {key: 3, name:"C", permission: true, label:'Label C'}]

Display Tabs: Who has permission: true

On change of tabs, getting selected tab value is 0 or 1.

I'm unable to get the selected object from the list using 0 and 1.

Can anyone help me out with this? Thanks in advance.

Body:
You are using the tabClickHandler method just declare the selected_tab in data and use indexof method to get the selected tab index.

codepen - https://codepen.io/Pratik__007/pen/XWbXZKw?editors=1010;

this.selected_index = this.computedMasterTabsList.indexOf(obj);

mounted(){
    let i=0;
    for(i in this.computedMasterTabsList){
        if(this.computedMasterTabsList[i]['permission']==true){
          console.log(i)
          this.selected_index = i;
          break;
        }
    }
  }


问:
AML Notebook VM auto shutdown policy
Whether an auto shutdown policy can be set to turn off Notebook VM?.Is this need to shutdown the VM Notebook by the user?</p>

答:
Currently Auto shutdown is on roadmap, Workaround While you can see and change settings for the underlying IaaS VM,if using Azure VM Auto-shutdown (also Automation Runbook) is to start the VM from the Azure VM resource blade first, then restart in the Azure ML Workspace UI.

Azure Notebooks starts the underlying virtual machine whenever you run a notebook or other file. The server automatically saves files and shuts down after 60 minutes of inactivity. You can also stop the server at any time with the Shutdown command (keyboard shortcut: h). Ref: https://learn.microsoft.com/en-us/azure/notebooks/configure-manage-azure-notebooks-projects.

Title: AML Notebook VM auto shutdown policy


问:
Git get updated files
I'm starting a new job as developer, so far i'm the only one contributing to the project which is basically working on a project from another company that devleoped it on maven so i have to get their archetype and start editing,adding classes (java).
Since i've never used git, succesfully i added my own repo on github, and the process of editing (correct me if i'm wrong) is to edit->commit->push.
The final product must me deployed on a remote server and deployed on tomcat; my question is: do i have to git clone every time, i commit new modifications?Or is there a faster way?
Than on the remote server i compile it and push the war files in the tomcat server </p>

答:
No, git clone is only executed once to clone the server repository into your local machine.

Once you make changes to the source code, you can git commit command to save changes to your local repository. After that, you can use git push command to push your local commits from local repository to remote repository.

Update

You can use git pull command to get the latest files from remote repository to your local repository.

Title: Git get updated files


问:
Calculation loop in python new values
I would like to do the calculation loop using my function.

```<code>b=list(data.iloc[1])

def balance(rate, payment, os):
    interest_amount=os*rate/100/12
    principal_amount=payment-interest_amount
    next_balance=os+interest_amount-principal_amount
    return next_balance

c=balance(b[9], b[11], b[8])
d=balance(b[9], b[11], c)
e=balance(b[9], b[11], d)
</code>```

I would have to start with b[8] as the amount for calculation. After I got the next amount from the function balance, the next amount will be the beginning of the third calculation and so on until the next amount eqaul of less than 0. It should stop the loop.

I need to append calculated values since b[8] until the last (before getting 0 or less).

Any suggestion on this, thank you!

Edit: based on Zaraki Kenpachi

b[8] is amount of money given 17183
b[9] is rate of interest given 3.39
b[11] is payment per month given 5759

The output, which I am trying to do is:

```<code>[17183, 11,521, 5,826, 99]
</code>```

答:
Python doesn't have a builtin way to unfold / iterate but the normal way you'd implenent a specific unfold is through a generator, which can keep computational state and yield values:

def balances(balance, rate, payment):
    while True:
        interest_amount = balance*rate/100/12
        principal_amount = payment-interest_amount
        balance = os+interest_amount-principal_amount
        # TO DO: end the computation when balance <= 0, maybe find a way to
        # note extra in the last payment, or reject the last payment entirely
        # and handle that case separately outside the generator
        yield balance
```

<p>then you can either call <code>next()</code> on your balances iterator to get successive values</p>

<pre class="lang-py prettyprint-override"><code>bs = balances(b[8], b[9], b[11])
c = next(bs)
d = next(bs)
e = next(bs)
</code>```

or iterate the entire thing

for balance in balances(b[8], b[9], b[11]):
    if balance < 0:
        "do something when the last payment was excessive and stop the loop"
    ...
```

Title: Calculation loop in python new values

Body:
I would like to do the calculation loop using my function.

b=list(data.iloc[1])

def balance(rate, payment, os):
    interest_amount=os*rate/100/12
    principal_amount=payment-interest_amount
    next_balance=os+interest_amount-principal_amount
    return next_balance

c=balance(b[9], b[11], b[8])
d=balance(b[9], b[11], c)
e=balance(b[9], b[11], d)

I would have to start with b[8] as the amount for calculation. After I got the next amount from the function balance, the next amount will be the beginning of the third calculation and so on until the next amount eqaul of less than 0. It should stop the loop.

I need to append calculated values since b[8] until the last (before getting 0 or less).

Any suggestion on this, thank you!

Edit: based on Zaraki Kenpachi

b[8] is amount of money given 17183
b[9] is rate of interest given 3.39
b[11] is payment per month given 5759

The output, which I am trying to do is:

[17183, 11,521, 5,826, 99]

Body:
Python doesn't have a builtin way to unfold / iterate but the normal way you'd implenent a specific unfold is through a generator, which can keep computational state and yield values:

def balances(balance, rate, payment):
    while True:
        interest_amount = balance*rate/100/12
        principal_amount = payment-interest_amount
        balance = os+interest_amount-principal_amount
        # TO DO: end the computation when balance <= 0, maybe find a way to
        # note extra in the last payment, or reject the last payment entirely
        # and handle that case separately outside the generator
        yield balance

then you can either call next() on your balances iterator to get successive values

bs = balances(b[8], b[9], b[11])
c = next(bs)
d = next(bs)
e = next(bs)

or iterate the entire thing

for balance in balances(b[8], b[9], b[11]):
    if balance < 0:
        "do something when the last payment was excessive and stop the loop"
    ...


问:
How can I implement snap carousel in Vertical direction?
I need to create List but using snap carousel component. But I am unable to do so.</p>

答:
Just adding a prop to carousel as vertical.
You can refer https://github.com/archriss/react-native-snap-carousel
For using the vertical props find it here https://github.com/archriss/react-native-snap-carousel/blob/master/src/carousel/Carousel.js


问:
SQL Server Unicode queries with SC Collation
In SQL Server 2012 I have a table with an nvarchar column with collation Latin1_General_100_CI_AS_SC, which is supposed to support unicode surrogate pair characters, or supplementary characters.

When I run this query:

```<code>select KeyValue from terms where KeyValue = N'➰'
</code>```

(above is a Unicode SC)

above is a curly loop character with code 10160 (x27B0)

The result is hundreds of different looking single character entries, even though they all have different UTF-16 codepoints.  Is this due to collation? Why isn't there an exact match?

EDIT: I now think this is due to collation. There seems to be a group of "undefined" characters in the UTF-16 range, more than 1733 characters, and they are treated as the same by this collation. Although, characters with codes above 65535 are treated as unique and those queries return exact matches.

The two queries below have different results:

```<code>select KeyValue from terms where KeyValue = N'π'
</code>```

returns 3 rows: π and ℼ and ᴨ

```<code>select KeyValue from terms where KeyValue LIKE N'π'
</code>```

returns 2 rows: π and ℼ

Why is this?

This is the weirdest of all.  This query:

```<code>select KeyValue from terms where KeyValue like N'➰%'
</code>```

returns ALMOST ALL records in the table, which has many multiple character regular latin character set terms like "8w" or "apple".  90% of those not being returned are starting with "æ".  What is happening?

NOTE: Just to give this a bit of context, these are all Wikipedia article titles, not random strings.

答:
I have a table with an nvarchar column with collation Latin1_General_100_CI_AS_SC, which is supposed to support Unicode surrogate pair characters, or supplementary characters.

The Supplementary Character-Aware (SCA) collations — those ending with _SC or with _140_ in their names — do support supplementary characters. BUT, "support" only means that the built-in functions handle the surrogate pair as a single, supplementary code point instead a pair of surrogate code points. But support for sorting and comparison of supplementary characters actually started in SQL Server 2005 with the introduction of the version 90 collations.

even though they all have different UTF-16 codepoints. Is this due to collation? Why isn't there an exact match?

UTF-16 doesn't have code points, it is an encoding that encodes all Unicode code points.

Yes, this behavior is due to collation.

There is no exact match because (as you guessed), code point U+27B0 has no defined sort weight. Hence it is completely ignored and equates to an empty string or any other code point that has no sort weight.

There seems to be a group of "undefined" characters in the UTF-16 range, more than 1733 characters, and they are treated as the same by this collation.

Correct, though some only have a sort weight due to the accent sensitivity of the collation. You would get even more matches if you used Latin1_General_100_CI_AI_SC. And, to be clear, the UTF-16 "range" is all 1,114,112 Unicode code points.

The two queries below have different results ... Why is this?

I can't (yet!) explain why = vs LIKE returns different sets of matches, but there is 1 more character that equates to the 3 that you currently have:

SELECT KeyValue, CONVERT(VARBINARY(40), [KeyValue])
FROM (VALUES (N'π' COLLATE Latin1_General_100_CI_AS_SC), (N'ℼ'), (N'ᴨ'),
             (N'Π')) t([KeyValue])
WHERE KeyValue = N'π'; -- 4 rows

SELECT KeyValue, CONVERT(VARBINARY(40), [KeyValue])
FROM (VALUES (N'π' COLLATE Latin1_General_100_CI_AS_SC), (N'ℼ'), (N'ᴨ'),
             (N'Π')) t([KeyValue])
WHERE KeyValue LIKE N'π'; -- 3 rows
```

<blockquote>
  <p>This is the weirdest of all. This query: ... returns ALMOST ALL records in the table</p>
</blockquote>

<pre class="lang-sql prettyprint-override"><code>
SELECT 1 WHERE NCHAR(0x27B0) = NCHAR(0x0000) COLLATE Latin1_General_100_CI_AS_SC;
-- 1

SELECT 2 WHERE NCHAR(0x27B0) = N'' COLLATE Latin1_General_100_CI_AS_SC;
-- 2

SELECT 3 WHERE NCHAR(0x27B0) = NCHAR(0x27B0) + NCHAR(0x27B0) + NCHAR(0x27B0)
           COLLATE Latin1_General_100_CI_AS_SC;
-- 3

SELECT 4 WHERE N'➰' = N'➰   ➰    ➰    ➰' COLLATE Latin1_General_100_CI_AS_SC;
-- 4

SELECT 5 WHERE N'➰' LIKE N'➰   ➰    ➰    ➰' COLLATE Latin1_General_100_CI_AS_SC;
-- NO ROWS RETURNED!!  (spaces matter here due to LIKE)

SELECT 6 WHERE N'➰' LIKE N'➰➰➰➰➰➰' COLLATE Latin1_General_100_CI_AS_SC;
-- 6
</code>```

This, again, has something to do with the fact that "➰" has no sort weight defined. Of course, neither does æ, Þ, ß, Ǉ, etc.

I will update this answer once I figured out exactly what LIKE is doing differently than =.

For more info, please see:

How Many Bytes Per Character in SQL Server: a Completely Complete Guide

Collations Info

Body:
In SQL Server 2012 I have a table with an nvarchar column with collation Latin1_General_100_CI_AS_SC, which is supposed to support unicode surrogate pair characters, or supplementary characters.

When I run this query:

select KeyValue from terms where KeyValue = N'➰'

(above is a Unicode SC)

above is a curly loop character with code 10160 (x27B0)

The result is hundreds of different looking single character entries, even though they all have different UTF-16 codepoints.  Is this due to collation? Why isn't there an exact match?

EDIT: I now think this is due to collation. There seems to be a group of "undefined" characters in the UTF-16 range, more than 1733 characters, and they are treated as the same by this collation. Although, characters with codes above 65535 are treated as unique and those queries return exact matches.

The two queries below have different results:

select KeyValue from terms where KeyValue = N'π'

returns 3 rows: π and ℼ and ᴨ

select KeyValue from terms where KeyValue LIKE N'π'

returns 2 rows: π and ℼ

Why is this?

This is the weirdest of all.  This query:

select KeyValue from terms where KeyValue like N'➰%'

returns ALMOST ALL records in the table, which has many multiple character regular latin character set terms like "8w" or "apple".  90% of those not being returned are starting with "æ".  What is happening?

NOTE: Just to give this a bit of context, these are all Wikipedia article titles, not random strings.

Body:
I have a table with an nvarchar column with collation Latin1_General_100_CI_AS_SC, which is supposed to support Unicode surrogate pair characters, or supplementary characters.

The Supplementary Character-Aware (SCA) collations — those ending with _SC or with _140_ in their names — do support supplementary characters. BUT, "support" only means that the built-in functions handle the surrogate pair as a single, supplementary code point instead a pair of surrogate code points. But support for sorting and comparison of supplementary characters actually started in SQL Server 2005 with the introduction of the version 90 collations.

even though they all have different UTF-16 codepoints. Is this due to collation? Why isn't there an exact match?

UTF-16 doesn't have code points, it is an encoding that encodes all Unicode code points.

Yes, this behavior is due to collation.

There is no exact match because (as you guessed), code point U+27B0 has no defined sort weight. Hence it is completely ignored and equates to an empty string or any other code point that has no sort weight.

There seems to be a group of "undefined" characters in the UTF-16 range, more than 1733 characters, and they are treated as the same by this collation.

Correct, though some only have a sort weight due to the accent sensitivity of the collation. You would get even more matches if you used Latin1_General_100_CI_AI_SC. And, to be clear, the UTF-16 "range" is all 1,114,112 Unicode code points.

The two queries below have different results ... Why is this?

I can't (yet!) explain why = vs LIKE returns different sets of matches, but there is 1 more character that equates to the 3 that you currently have:

SELECT KeyValue, CONVERT(VARBINARY(40), [KeyValue])
FROM (VALUES (N'π' COLLATE Latin1_General_100_CI_AS_SC), (N'ℼ'), (N'ᴨ'),
             (N'Π')) t([KeyValue])
WHERE KeyValue = N'π'; -- 4 rows

SELECT KeyValue, CONVERT(VARBINARY(40), [KeyValue])
FROM (VALUES (N'π' COLLATE Latin1_General_100_CI_AS_SC), (N'ℼ'), (N'ᴨ'),
             (N'Π')) t([KeyValue])
WHERE KeyValue LIKE N'π'; -- 3 rows

This is the weirdest of all. This query: ... returns ALMOST ALL records in the table

SELECT 1 WHERE NCHAR(0x27B0) = NCHAR(0x0000) COLLATE Latin1_General_100_CI_AS_SC;
-- 1

SELECT 2 WHERE NCHAR(0x27B0) = N'' COLLATE Latin1_General_100_CI_AS_SC;
-- 2

SELECT 3 WHERE NCHAR(0x27B0) = NCHAR(0x27B0) + NCHAR(0x27B0) + NCHAR(0x27B0)
           COLLATE Latin1_General_100_CI_AS_SC;
-- 3

SELECT 4 WHERE N'➰' = N'➰   ➰    ➰    ➰' COLLATE Latin1_General_100_CI_AS_SC;
-- 4

SELECT 5 WHERE N'➰' LIKE N'➰   ➰    ➰    ➰' COLLATE Latin1_General_100_CI_AS_SC;
-- NO ROWS RETURNED!!  (spaces matter here due to LIKE)

SELECT 6 WHERE N'➰' LIKE N'➰➰➰➰➰➰' COLLATE Latin1_General_100_CI_AS_SC;
-- 6

This, again, has something to do with the fact that "➰" has no sort weight defined. Of course, neither does æ, Þ, ß, Ǉ, etc.

I will update this answer once I figured out exactly what LIKE is doing differently than =.

For more info, please see:

How Many Bytes Per Character in SQL Server: a Completely Complete Guide

Collations Info


Title: Is it possible to divide the value of a list in a certain amount of times

Body:
Hi I am trying to split the values in a (y2)list into (inv) amount of parts.

x = [0,100,200,300,400,500,600,700,800,900,1000,1100]
y2 = [58,55,49,12,6,5,4,4.5,35,48,56,58]
interval = 5
inv = (x[0] + x[1])/interval

I will like to split y2 into inv parts so my answer should be:

[58 57.85 57.7 57.55 57.4 57.25 57.1 56.95 56.8 56.65 56.5 56.35 56.2 56.05 55.9 55.75 55.6 55.45 55.3 55.15 55...…….49...…………..12...….6 ………...5...……..]

I will like to mention that inv will always be (x[0] + x[1])/interval

Body:
Not sure I understood you correctly, but if I did, this would be one way of doing it:

x = [0,100,200,300,400,500,600,700,800,900,1000,1100]
y2 = [58,55,49,12,6,5,4,4.5,35,48,56,58]
inv = 5
intervals = int((x[0] + x[1]) / inv)
step_size = [(a - b)/intervals for i, (a, b) in enumerate(zip(y2, y2[1:]))]

res = []
for i, (top, bot) in enumerate(zip(y2, y2[1:])):
  for j in range(intervals):
    res.append(top - j * step_size[i])
res.append(y2[-1])

Which results in:

# [58.0, 57.85, 57.7, 57.55, 57.4, 57.25, 57.1, 56.95, 56.8, 56.65, 56.5, 56.35, 56.2, 56.05, 55.9, 55.75, 55.6, 55.45, 55.3, 55.15, 55.0, 54.7, 54.4, 54.1, 53.8, 53.5, 53.2, 52.9, 52.6, 52.3, 52.0, 51.7, 51.4, 51.1, 50.8, 50.5, 50.2, 49.9, 49.6, 49.3, 49.0, 47.15, 45.3, 43.45, 41.6, 39.75, 37.9, 36.05, 34.2, 32.349999999999994, 30.5, 28.65, 26.799999999999997, 24.95, 23.099999999999998, 21.25, 19.4, 17.549999999999997, 15.699999999999996, 13.850000000000001, 12.0, 11.7, 11.4, 11.1, 10.8, 10.5, 10.2, 9.9, 9.6, 9.3, 9.0, 8.7, 8.4, 8.1, 7.8, 7.5, 7.2, 6.9, 6.6000000000000005, 6.3, 6.0, 5.95, 5.9, 5.85, 5.8, 5.75, 5.7, 5.65, 5.6, 5.55, 5.5, 5.45, 5.4, 5.35, 5.3, 5.25, 5.2, 5.15, 5.1, 5.05, 5.0, 4.95, 4.9, 4.85, 4.8, 4.75, 4.7, 4.65, 4.6, 4.55, 4.5, 4.45, 4.4, 4.35, 4.3, 4.25, 4.2, 4.15, 4.1, 4.05, 4.0, 4.025, 4.05, 4.075, 4.1, 4.125, 4.15, 4.175, 4.2, 4.225, 4.25, 4.275, 4.3, 4.325, 4.35, 4.375, 4.4, 4.425, 4.45, 4.475, 4.5, 6.025, 7.55, 9.075, 10.6, 12.125, 13.649999999999999, 15.174999999999999, 16.7, 18.225, 19.75, 21.275, 22.799999999999997, 24.325, 25.849999999999998, 27.375, 28.9, 30.424999999999997, 31.95, 33.474999999999994, 35.0, 35.65, 36.3, 36.95, 37.6, 38.25, 38.9, 39.55, 40.2, 40.85, 41.5, 42.15, 42.8, 43.45, 44.1, 44.75, 45.4, 46.05, 46.7, 47.35, 48.0, 48.4, 48.8, 49.2, 49.6, 50.0, 50.4, 50.8, 51.2, 51.6, 52.0, 52.4, 52.8, 53.2, 53.6, 54.0, 54.4, 54.8, 55.2, 55.6, 56.0, 56.1, 56.2, 56.3, 56.4, 56.5, 56.6, 56.7, 56.8, 56.9, 57.0, 57.1, 57.2, 57.3, 57.4, 57.5, 57.6, 57.7, 57.8, 57.9, 58]


问:
Opsgenie powershell alert post not working
I have successfully made an alert post using Python, but cannot get my powershell alert creation to work. I just get a wall of HTML in my response and no alert creation. Message is the only required field.
Here's what I'm using and it does not work

```<code>$api = "XXX"
$URI = "https://api.opsgenie.com/v2/alerts"
$head = @{"Authorization" = "GenieKey $api"}
$body = @{
            message = "testing";
            responders =
                ]@{
                    name = "TEAMNAMEHERE";
                    type = "team"
                }]

        } | ConvertTo-Json

$request = Invoke-RestMethod -Uri $URI -Method Post -Headers $head -ContentType "application/json" -Body $body
$request
</code>```

Here is my python code I made and it works just fine.

```<code>import requests
import json

def CreateOpsGenieAlert(api_token):
    header = {
        "Authorization": "GenieKey " + api_token,
        "Content-Type": "application/json"
    }

    body = json.dumps({"message": "testing",
                       "responders": [
                           {
                               "name": "TEAMNAMEHERE",
                               "type": "team"
                           }
                       ]
                       }
                      )
    try:
        response = requests.post("https://api.opsgenie.com/v2/alerts",
                                headers=header,
                                data=body)
        jsontemp = json.loads(response.text)
        print(jsontemp)

        if response.status_code == 202:
            return response
    except:
        print('error')

    print(response)

CreateOpsGenieAlert(api_token="XXX")
</code>```

EDIT: So I've figured out it has something to do with my "responders" section. It has something to do with the [ ]...but I haven't been able to figure out what exactly. If I remove them, it wont work. If I turn the first one around, it won't work. I can get the alert to create successfully, however I keep getting the following error:

```<code>] : The term ']' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\file\Tech\user\powershell scripts\.not working\OpsGenieAlert.ps1:7 char:17
+                 ]@{
+                 ~
    + CategoryInfo          : ObjectNotFound: (]:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

答:
You need to convert your $body to JSON</p>

```<code>$api = "XXX"
$URI = "https://api.opsgenie.com/v2/alerts"
# Declare an empty array
$responders = @()

# Add a new item to the array
$responders += @{
    name = "TEAMNAMEHERE1"
    type = "team1"
}
$responders += @{
    name = "TEAMNAMEHERE2"
    type = "team2"
}

$body = @{
    message    = "testing"
    responders = $responders
} | ConvertTo-Json

$invokeRestMethodParams = @{
    'Headers'     = @{
        "Authorization" = "GenieKey $api"
    }
    'Uri'         = $URI
    'ContentType' = 'application/json'
    'Body'        = $body
    'Method'      = 'Post'
}

$request = Invoke-RestMethod @invokeRestMethodParams
</code>```

Body:
I have successfully made an alert post using Python, but cannot get my powershell alert creation to work. I just get a wall of HTML in my response and no alert creation. Message is the only required field.
Here's what I'm using and it does not work

$api = "XXX"
$URI = "https://api.opsgenie.com/v2/alerts"
$head = @{"Authorization" = "GenieKey $api"}
$body = @{
            message = "testing";
            responders =
                ]@{
                    name = "TEAMNAMEHERE";
                    type = "team"
                }]

        } | ConvertTo-Json

$request = Invoke-RestMethod -Uri $URI -Method Post -Headers $head -ContentType "application/json" -Body $body
$request

Here is my python code I made and it works just fine.

import requests
import json

def CreateOpsGenieAlert(api_token):
    header = {
        "Authorization": "GenieKey " + api_token,
        "Content-Type": "application/json"
    }

    body = json.dumps({"message": "testing",
                       "responders": [
                           {
                               "name": "TEAMNAMEHERE",
                               "type": "team"
                           }
                       ]
                       }
                      )
    try:
        response = requests.post("https://api.opsgenie.com/v2/alerts",
                                headers=header,
                                data=body)
        jsontemp = json.loads(response.text)
        print(jsontemp)

        if response.status_code == 202:
            return response
    except:
        print('error')

    print(response)

CreateOpsGenieAlert(api_token="XXX")

EDIT: So I've figured out it has something to do with my "responders" section. It has something to do with the [ ]...but I haven't been able to figure out what exactly. If I remove them, it wont work. If I turn the first one around, it won't work. I can get the alert to create successfully, however I keep getting the following error:

] : The term ']' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\file\Tech\user\powershell scripts\.not working\OpsGenieAlert.ps1:7 char:17
+                 ]@{
+                 ~
    + CategoryInfo          : ObjectNotFound: (]:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Body:
You need to convert your $body to JSON

$api = "XXX"
$URI = "https://api.opsgenie.com/v2/alerts"
# Declare an empty array
$responders = @()

# Add a new item to the array
$responders += @{
    name = "TEAMNAMEHERE1"
    type = "team1"
}
$responders += @{
    name = "TEAMNAMEHERE2"
    type = "team2"
}

$body = @{
    message    = "testing"
    responders = $responders
} | ConvertTo-Json

$invokeRestMethodParams = @{
    'Headers'     = @{
        "Authorization" = "GenieKey $api"
    }
    'Uri'         = $URI
    'ContentType' = 'application/json'
    'Body'        = $body
    'Method'      = 'Post'
}

$request = Invoke-RestMethod @invokeRestMethodParams


问:
With OpenCSV, how do I append to existing CSV using a MappingStrategy?
With OpenCSV, how do I append to existing CSV using a MappingStrategy?  There are lots of examples I could find where NOT using a Bean mapping stategy BUT I like the dynamic nature of the column mapping with bean strategy and would like to get it working this way.  Here is my code, which just rewrites the single line to CSV file instead of appending.

How can I fix this?  Using OpenCSV 4.5 .  Note: I set my FileWriter for append=true .  This scenario is not working as I expected.   Re-running this method simply results in over-writing the entire file with a header and a single row.

```<code>public void addRowToCSV(PerfMetric rowData) {
    File file = new File(PerfTestMetric.CSV_FILE_PATH);
    try {
        CSVWriter writer = new CSVWriter(new FileWriter(file, true));

        CustomCSVMappingStrategy<PerfMetric> mappingStrategy
          = new CustomCSVMappingStrategy<>();
        mappingStrategy.setType(PerfMetric.class);

        StatefulBeanToCsv<PerfMetric> beanToCsv
           = new StatefulBeanToCsvBuilder<PerfMetric>(writer)
            .withMappingStrategy(mappingStrategy)
            .withSeparator(',')
            .withApplyQuotesToAll(false)
            .build();

        try {
            beanToCsv.write(rowData);
        } catch (CsvDataTypeMismatchException e) {
            e.printStackTrace();
        } catch (CsvRequiredFieldEmptyException e) {
            e.printStackTrace();
        }
        writer.flush();
        writer.close();
    } catch (IOException e) {
            e.printStackTrace();
    }
}
</code>```

Or, is the usual pattern to load all rows into a List and then re-write entire file?   I was able to get it to work by writing two MappingStrategy mapping strategies and then conditionally using them with a if-file-exists but doing it that way leaves me with a "Unchecked assignment" warning in my code.   Not ideal; hoping for an elegant solution?

答:
I've updated OpenCSV to version 5.1 and got it working. In my case I needed the CSV headers to have a specific name and position, so I'm using both @CsvBindByName and @CsvBindByPosition, and needed to create a custom MappingStrategy to get it working.

Later, I needed to edit the MappingStrategy to enable appending, so when it's in Appending mode I don't need to generate a CSV header.

public class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
    private boolean useHeader=true;

    public CustomMappingStrategy(){
    }

    public CustomMappingStrategy(boolean useHeader) {
        this.useHeader = useHeader;
    }

    @Override
    public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
        final int numColumns = FieldUtils.getAllFields(bean.getClass()).length;
        super.setColumnMapping(new String[numColumns]);

        if (numColumns == -1) {
            return super.generateHeader(bean);
        }

        String[] header = new String[numColumns];

        if(!useHeader){
            return ArrayUtils.EMPTY_STRING_ARRAY;
        }
        BeanField<T, Integer> beanField;
        for (int i = 0; i < numColumns; i++){
            beanField = findField(i);
            String columnHeaderName = extractHeaderName(beanField);
            header[i] = columnHeaderName;
        }

        return header;
    }

    private String extractHeaderName(final BeanField<T, Integer> beanField){
        if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0){
            return StringUtils.EMPTY;
        }

        //return value of CsvBindByName annotation
        final CsvBindByName bindByNameAnnotation = beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class)[0];
        return bindByNameAnnotation.column();
    }

}
```

Now if you use the default constructor it'll add the header to the generated CSV, and using a boolean you can tell it to add a header or to ignore it.

Body:
With OpenCSV, how do I append to existing CSV using a MappingStrategy?  There are lots of examples I could find where NOT using a Bean mapping stategy BUT I like the dynamic nature of the column mapping with bean strategy and would like to get it working this way.  Here is my code, which just rewrites the single line to CSV file instead of appending.

How can I fix this?  Using OpenCSV 4.5 .  Note: I set my FileWriter for append=true .  This scenario is not working as I expected.   Re-running this method simply results in over-writing the entire file with a header and a single row.

public void addRowToCSV(PerfMetric rowData) {
    File file = new File(PerfTestMetric.CSV_FILE_PATH);
    try {
        CSVWriter writer = new CSVWriter(new FileWriter(file, true));

        CustomCSVMappingStrategy<PerfMetric> mappingStrategy
          = new CustomCSVMappingStrategy<>();
        mappingStrategy.setType(PerfMetric.class);

        StatefulBeanToCsv<PerfMetric> beanToCsv
           = new StatefulBeanToCsvBuilder<PerfMetric>(writer)
            .withMappingStrategy(mappingStrategy)
            .withSeparator(',')
            .withApplyQuotesToAll(false)
            .build();

        try {
            beanToCsv.write(rowData);
        } catch (CsvDataTypeMismatchException e) {
            e.printStackTrace();
        } catch (CsvRequiredFieldEmptyException e) {
            e.printStackTrace();
        }
        writer.flush();
        writer.close();
    } catch (IOException e) {
            e.printStackTrace();
    }
}

Or, is the usual pattern to load all rows into a List and then re-write entire file?   I was able to get it to work by writing two MappingStrategy mapping strategies and then conditionally using them with a if-file-exists but doing it that way leaves me with a "Unchecked assignment" warning in my code.   Not ideal; hoping for an elegant solution?

Body:
I've updated OpenCSV to version 5.1 and got it working. In my case I needed the CSV headers to have a specific name and position, so I'm using both @CsvBindByName and @CsvBindByPosition, and needed to create a custom MappingStrategy to get it working.

Later, I needed to edit the MappingStrategy to enable appending, so when it's in Appending mode I don't need to generate a CSV header.

public class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
    private boolean useHeader=true;

    public CustomMappingStrategy(){
    }

    public CustomMappingStrategy(boolean useHeader) {
        this.useHeader = useHeader;
    }

    @Override
    public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
        final int numColumns = FieldUtils.getAllFields(bean.getClass()).length;
        super.setColumnMapping(new String[numColumns]);

        if (numColumns == -1) {
            return super.generateHeader(bean);
        }

        String[] header = new String[numColumns];

        if(!useHeader){
            return ArrayUtils.EMPTY_STRING_ARRAY;
        }
        BeanField<T, Integer> beanField;
        for (int i = 0; i < numColumns; i++){
            beanField = findField(i);
            String columnHeaderName = extractHeaderName(beanField);
            header[i] = columnHeaderName;
        }

        return header;
    }

    private String extractHeaderName(final BeanField<T, Integer> beanField){
        if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0){
            return StringUtils.EMPTY;
        }

        //return value of CsvBindByName annotation
        final CsvBindByName bindByNameAnnotation = beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class)[0];
        return bindByNameAnnotation.column();
    }

}

Now if you use the default constructor it'll add the header to the generated CSV, and using a boolean you can tell it to add a header or to ignore it.


问:
how to convert milliseconds into HH:MM:SS format in mongodb(3.4 version)
I am projecting a field as i want the difference between DateOfOcurrance and current time. Then I want to compare the diff_time field with one time which is in String format(HH:MM:SS) as I want those documents which have less than 15mins diff_time, but not getting.</p>

```<code>{$project: {diff_time:{ $subtract: ["$DateOfOcurrance", new Date("2020-02-14")]}}},
{"$match": {"diff_time": { "$lt": "00:15:00" }}}
</code>```

答:
Dates are stored as the number of milliseconds since epoch.  When you subtract one date from another, you get a NumberLong containing the difference in milliseconds.

To find differences less than 15 minutes, use:

```<code>{"$match": {"diff_time": { "$lt": 900000 }}}
</code>```

(900000 = number of milliseconds in 15 minutes)

Body:
I am projecting a field as i want the difference between DateOfOcurrance and current time. Then I want to compare the diff_time field with one time which is in String format(HH:MM:SS) as I want those documents which have less than 15mins diff_time, but not getting.

{$project: {diff_time:{ $subtract: ["$DateOfOcurrance", new Date("2020-02-14")]}}},
{"$match": {"diff_time": { "$lt": "00:15:00" }}}

Body:
Dates are stored as the number of milliseconds since epoch.  When you subtract one date from another, you get a NumberLong containing the difference in milliseconds.

To find differences less than 15 minutes, use:

{"$match": {"diff_time": { "$lt": 900000 }}}

(900000 = number of milliseconds in 15 minutes)


问:
Python won't allow custom package to be imported
So I have a python script located on my desktop as well as a package I made called testpackage. It contains three scripts each containing one function which prints a word. Here is a sample of one of the scripts.

```<code>def dog():
    print ("Dog")
</code>```

I also have an __init__.py  file and contains the following.

```<code>import sys, os
pathVar = os.path.normpath('/Desktop/testpackage')
from cat import *
from dog import *
from horse import *
</code>```

The file on my desktop, named myFile.py, contains the following

```<code>from testpackage import dog
dog.dog()
</code>```

When I run this script, I get an error along the lines of

File 'myFile.py", line1, in  from testpackage import dog. File "C:\Users\User\Deskop\testpackage__init__.py", line 3 in
  from cat import *
  ModuleNotFoundError: No Module named 'cat'

I have tried every trick under the sun that i've found on google so I'm wondering why it can't locate the script from the __init__ file.

答:
You should put the module's parent dir in PYTHONPATH.

You can achieve this using the following code:

```<code>import sys
module_dir = r"/path/to/module/parent/dir"
sys.path.insert(0, module_dir)
# assuming module is named my_mod.py
import my_mod
</code>```

Body:
So I have a python script located on my desktop as well as a package I made called testpackage. It contains three scripts each containing one function which prints a word. Here is a sample of one of the scripts.

def dog():
    print ("Dog")

I also have an __init__.py  file and contains the following.

import sys, os
pathVar = os.path.normpath('/Desktop/testpackage')
from cat import *
from dog import *
from horse import *

The file on my desktop, named myFile.py, contains the following

from testpackage import dog
dog.dog()

When I run this script, I get an error along the lines of

File 'myFile.py", line1, in  from testpackage import dog. File "C:\Users\User\Deskop\testpackage__init__.py", line 3 in
  from cat import *
  ModuleNotFoundError: No Module named 'cat'

I have tried every trick under the sun that i've found on google so I'm wondering why it can't locate the script from the __init__ file.

Body:
You should put the module's parent dir in PYTHONPATH.

You can achieve this using the following code:

import sys
module_dir = r"/path/to/module/parent/dir"
sys.path.insert(0, module_dir)
# assuming module is named my_mod.py
import my_mod


问:
Is GOTO considered harmless when jumping to cleanup at the end of function?
The goto statement has been examined at great length in several SO discussions (see this and that), and I certainly don't want to revive those heated debates.

Instead, I'd like to concentrate on a single use case of gotos and discuss its value and possible alternatives.

Consider the following code snippet, which is common in (at least my own) FSMs:

```<code>while (state = next_state()) {
        switch (state) {
                case foo:
                        /* handle foo, and finally: */
                        if (error) goto cleanup;
                        break;
                case bar:
                        /* handle bar, and finally: */
                        if (error) goto cleanup;
                        break;
                /* ...other cases... */
        }
}

return ok;

cleanup:
/* do some cleanup, i.e. free() local heap requests, adjust global state, and then: */
return error;
</code>```

Swapping out the cleanup stuff in a separate function just in order to save the gotos seems awkward. On the other hand, we've been raised to condemn the use of gotos wherever possible.

My question: is my code example considered good style?

If not, are there feasible alternatives available?

Please adhere to the specific usage of goto described above. I don't want to delve into yet another discussion about the general use of goto.

答:
Goto is not needed when you have switch.  Using both switch and goto just adds complication.

```<code>while (state) {
        switch (state) {
                case cleanup:
                        /* do some cleanup, i.e. free() local heap requests, adjust global state, and then: */
                        return error;
                case foo:
                        /* handle foo, and finally: */
                        if (error) { state = cleanup; continue; }
                        break;
                case bar:
                        /* handle bar, and finally: */
                        if (error) { state = cleanup; continue; }
                        break;
                /* ...other cases... */
        }
        state = next_state();
}

return ok;
</code>```

Body:
The goto statement has been examined at great length in several SO discussions (see this and that), and I certainly don't want to revive those heated debates.

Instead, I'd like to concentrate on a single use case of gotos and discuss its value and possible alternatives.

Consider the following code snippet, which is common in (at least my own) FSMs:

while (state = next_state()) {
        switch (state) {
                case foo:
                        /* handle foo, and finally: */
                        if (error) goto cleanup;
                        break;
                case bar:
                        /* handle bar, and finally: */
                        if (error) goto cleanup;
                        break;
                /* ...other cases... */
        }
}

return ok;

cleanup:
/* do some cleanup, i.e. free() local heap requests, adjust global state, and then: */
return error;

Swapping out the cleanup stuff in a separate function just in order to save the gotos seems awkward. On the other hand, we've been raised to condemn the use of gotos wherever possible.

My question: is my code example considered good style?

If not, are there feasible alternatives available?

Please adhere to the specific usage of goto described above. I don't want to delve into yet another discussion about the general use of goto.

Body:
Goto is not needed when you have switch.  Using both switch and goto just adds complication.

while (state) {
        switch (state) {
                case cleanup:
                        /* do some cleanup, i.e. free() local heap requests, adjust global state, and then: */
                        return error;
                case foo:
                        /* handle foo, and finally: */
                        if (error) { state = cleanup; continue; }
                        break;
                case bar:
                        /* handle bar, and finally: */
                        if (error) { state = cleanup; continue; }
                        break;
                /* ...other cases... */
        }
        state = next_state();
}

return ok;


问:
How to merge only a specific changeset (TFS)
I have a problem where I want to merge a specific changeset from my main branch to my release branch.

I am using Visual Studio 2015 together with team services (TFS).

I performed the following steps:

Select the main branch

Choose the option merge

Select the correct release

Select the "selected changeset option" press next

Select the change set that I wanted to merge with the branch

Press finish to start

Expected: Only the changes in the selected changesets are applied

Actual: The program merges up to the selected changeset.

Here's a specific scenario:

The project is branched when the main branch was at changeset 19

The main branch now also contains changeset 20 through 25

I want to merge changeset 24, but not any other changeset, into the child/release branch.

If I follow the steps above, the merge tool will merge also 20, 21, 22 and 23 from main into the child.

My question is if there is an easy way to merge just the selected changeset (24) and not any other changeset?

I have tried the commandline but it gives me the same result.

答:
You cannot merge multiple changesets in one go, unless the changesets are in sequence. Take a look at below similar question:

how to merge two changesets only (TFS)

TFS merge changeset into file with pending change

You have to merge either a single changeset or a sequential changesets in one go.

I have tried the command line but it gives me the same result.

I am afraid you may use the wrong format.

The following example merges all the changesets up to changeset 24 into branch2.

```<code>c:\projects>tf merge /version:C24 branch1 branch2 /recursive
</code>```

The following example merges changeset 24 into branch2.

```<code>c:\projects>tf merge /version:C24~C24 branch1 branch2 /recursive
</code>```

In you case , please select /version:C24~C24 when you use the command line to merge.

Body:
You cannot merge multiple changesets in one go, unless the changesets are in sequence. Take a look at below similar question:

how to merge two changesets only (TFS)

TFS merge changeset into file with pending change

You have to merge either a single changeset or a sequential changesets in one go.

I have tried the command line but it gives me the same result.

I am afraid you may use the wrong format.

The following example merges all the changesets up to changeset 24 into branch2.

c:\projects>tf merge /version:C24 branch1 branch2 /recursive

The following example merges changeset 24 into branch2.

c:\projects>tf merge /version:C24~C24 branch1 branch2 /recursive

In you case , please select /version:C24~C24 when you use the command line to merge.


问:
Wordpress search returns all pages regardless of search term
I have created a custom search page showing results only from children of two pages in the site. Problem is that no matter what the search term is, it returns all pages under those two. For any search term, it returns the same 200 pages

```<code>$s=get_search_query();
$args = array(
            's' =>$s
        );

if(isset($_GET['book'])) {
    $b = $_GET['book'];
    $args = array(
        'post_type'       => 'page',
        'posts_per_page'  => -1,
        'post_parent__in' => array(7253, 9859),
        'sentence'        => true,
        'exact'           => true,
        'order'           => 'ASC',
        'orderby'         => 'relevance',
    );
    $parent = new WP_Query( $args );
    if ( $parent->have_posts() ) : ?>

</code>```

the if(isset($_GET['book'])) { check if search should go only through these two pages.

What am I missing here?

答:
The problem is you are overriding the args array.

Use the following code:

```<code>$s=get_search_query();

if(isset($_GET['book'])) {
    $b = $_GET['book'];
    $args = array(
        'post_type'       => 'page',
        'posts_per_page'  => -1,
        'post_parent__in' => array(7253, 9859),
        'sentence'        => true,
        'exact'           => true,
        'order'           => 'ASC',
        'orderby'         => 'relevance',
        's'               => $s
    );
    $parent = new WP_Query( $args );
    if ( $parent->have_posts() ) : ?>
</code>```

Body:
I have created a custom search page showing results only from children of two pages in the site. Problem is that no matter what the search term is, it returns all pages under those two. For any search term, it returns the same 200 pages

$s=get_search_query();
$args = array(
            's' =>$s
        );

if(isset($_GET['book'])) {
    $b = $_GET['book'];
    $args = array(
        'post_type'       => 'page',
        'posts_per_page'  => -1,
        'post_parent__in' => array(7253, 9859),
        'sentence'        => true,
        'exact'           => true,
        'order'           => 'ASC',
        'orderby'         => 'relevance',
    );
    $parent = new WP_Query( $args );
    if ( $parent->have_posts() ) : ?>

the if(isset($_GET['book'])) { check if search should go only through these two pages.

What am I missing here?

Body:
The problem is you are overriding the args array.

Use the following code:

$s=get_search_query();

if(isset($_GET['book'])) {
    $b = $_GET['book'];
    $args = array(
        'post_type'       => 'page',
        'posts_per_page'  => -1,
        'post_parent__in' => array(7253, 9859),
        'sentence'        => true,
        'exact'           => true,
        'order'           => 'ASC',
        'orderby'         => 'relevance',
        's'               => $s
    );
    $parent = new WP_Query( $args );
    if ( $parent->have_posts() ) : ?>


问:
Python Pandas: reusing row value to another row - lookup across row
I have the following data frame

```<code>df1 =  DataFrame([['OBJ1', 10, 'BX', 'pool1', 'OBJ2'],['OBJ2', 0, '', '', 'OBJ1'],['OBJ3', 10, 'BY', 'pool2', 'OBJ4'],['OBJ4', 0, '', '', 'OBJ3'],['OBJ5', 10, 'BZ', 'pool3', '']], columns=['OBJ', 'value', 'conf', 'Res', 'Key'])
</code>```

What I am trying to do is to:

check when value is 0

Conf and Res takes the value of the row with the key matching the OBJ

for example, OBJ2 value is 0 and it is key is OBJ 2, then it's conf should become BX and Res becomes pool1

I tried multiple solutions using either lookup or some other posts but nothing seems to work.

```<code>df1.loc[df1['value']==0, 'conf'] = df1.loc[df1['OBJ']==df1['Key']]['conf']
</code>```

failed as I realized this is looking for rows with OBJ = Key

答:
Use DataFrame.merge with left_on and right_on parameters and index column created by DataFrame.reset_index for new DataFrame, then convert index column to index by DataFrame.set_index and last set new volumns by DataFrame.loc:

```<code>m = df1['value'].eq(0)
cols = ['conf','Res']
df = (df1.reset_index().loc[m, ['index','OBJ']]
          .merge(df1, left_on='OBJ', right_on='Key')
          .set_index('index')[cols])
print (df)
      conf    Res
index
1       BX  pool1
3       BY  pool2

df1.loc[m, cols] = df
print (df1)
    OBJ  value conf    Res   Key
0  OBJ1     10   BX  pool1  OBJ2
1  OBJ2      0   BX  pool1  OBJ1
2  OBJ3     10   BY  pool2  OBJ4
3  OBJ4      0   BY  pool2  OBJ3
4  OBJ5     10   BZ  pool3
</code>```

Body:
I have the following data frame

df1 =  DataFrame([['OBJ1', 10, 'BX', 'pool1', 'OBJ2'],['OBJ2', 0, '', '', 'OBJ1'],['OBJ3', 10, 'BY', 'pool2', 'OBJ4'],['OBJ4', 0, '', '', 'OBJ3'],['OBJ5', 10, 'BZ', 'pool3', '']], columns=['OBJ', 'value', 'conf', 'Res', 'Key'])

What I am trying to do is to:

check when value is 0

Conf and Res takes the value of the row with the key matching the OBJ

for example, OBJ2 value is 0 and it is key is OBJ 2, then it's conf should become BX and Res becomes pool1

I tried multiple solutions using either lookup or some other posts but nothing seems to work.

df1.loc[df1['value']==0, 'conf'] = df1.loc[df1['OBJ']==df1['Key']]['conf']

failed as I realized this is looking for rows with OBJ = Key

Body:
Use DataFrame.merge with left_on and right_on parameters and index column created by DataFrame.reset_index for new DataFrame, then convert index column to index by DataFrame.set_index and last set new volumns by DataFrame.loc:

m = df1['value'].eq(0)
cols = ['conf','Res']
df = (df1.reset_index().loc[m, ['index','OBJ']]
          .merge(df1, left_on='OBJ', right_on='Key')
          .set_index('index')[cols])
print (df)
      conf    Res
index
1       BX  pool1
3       BY  pool2

df1.loc[m, cols] = df
print (df1)
    OBJ  value conf    Res   Key
0  OBJ1     10   BX  pool1  OBJ2
1  OBJ2      0   BX  pool1  OBJ1
2  OBJ3     10   BY  pool2  OBJ4
3  OBJ4      0   BY  pool2  OBJ3
4  OBJ5     10   BZ  pool3


问:
Installing SQLite NuGet Package installs the package but the reference is not available. VS2019 Community
I"m writing a c# application using SQLite and I need the the SQLite Reference.  Using NuGet I locate the package and the output window shows a successful install.

Looking at the packages config file in the solution explorer it shows the version installed.

```<code><?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="SQLite" version="3.13.0" targetFramework="net472" />
</packages>
</code>```

However under the project References in the Solution explorer SQLite is not there.

I have watched tutorials online where the same process is done on other machines and all is ok, all of the references pop up after NuGet finishes the installation.

I'm using VS2019 and from what I understand there were some changes on how NuGet operates, however I had VS2015 and VS2017 Community and had the same issues.  I'm really at a standing point as I have no idea how to get the reference to show up so I can access it in my program.

SQLite has no Assembly reference so adding it there is not an option.

I have seen posts about a NuGet config file and Package Config File as well as the possibility of the package being installed outside of the Solution Folder but I don't know where.  I have looked in the output location of the solution and none of the references are located in the debug folder anywhere.

I feel the Dll's are being installed outside of the solution folder but I don't know where and how to get Visual Studio to get them to the proper location or reference there existing location correctly.

Rebuild and Restore NuGet Packages provide no solution.

Any help would be greatly appreciated.

答:
Installing SQLite NuGet Package installs the package but the reference
  is not available. VS2019 Community

I assume you have installed sqlite version 3.13.0 nuget package.If so, it is the behavior of this nuget package. This package is very special in that it is a transactional SQL database engine that implements self-contained, serverless, zero-configuration.

In simple terms, it is a configuration function package that operates on related data when the project is running, rather than a package that provides a reference class library for the project.

Let me explain it in more detail:

This is the content of the nuget package sqlite version 3.13.0

Note that each folder provides specific functionality for the installation project.
And the function of the lib folder is to add its content(xxxx.dlls) as reference to a new project. In a word, Only the Dlls in lib folder can be recognized by nuget and added into Reference.

You can refer to this link for more detailed info about the function of the folders.

Second, there is a file called SQLite.props in the Build folder. The file will do some configuration to your project during build process.

In it, you can see these files:

```<code><Content Include="$(MSBuildThisFileDirectory)..\..\runtimes\win7-x64\native\*">
      <Link>x64\%(Filename)%(Extension)</Link>
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <Visible>False</Visible>
    </Content>
  </ItemGroup>
  <ItemGroup Condition=" (Exists('packages.config') Or Exists('packages.$(MSBuildProjectName).config')) And '$(Platform)' == 'x86'">
    <Content Include="$(MSBuildThisFileDirectory)..\..\runtimes\win7-x86\native\*">
      <Link>%(Filename)%(Extension)</Link>
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <Visible>False</Visible>
    </Content>
  </ItemGroup>
  <ItemGroup Condition=" (Exists('packages.config') Or Exists('packages.$(MSBuildProjectName).config')) And '$(Platform)' == 'x64'">
    <Content Include="$(MSBuildThisFileDirectory)..\..\runtimes\win7-x64\native\*">
      <Link>%(Filename)%(Extension)</Link>
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <Visible>False</Visible>
    </Content>
</code>```

So when you build your project, the SQLite.props file  will be executed and they  will provide services during build or at the runtime.

All of these indicates it is a package for specific execution functions rather than a nuget package for adding reference libraries to the project.

Suggestion

As a suggestion, you could install System.Data.SQLite in your project. And this nuget package provides the dlls which you want in Reference.

Hope it could help you.

Body:
I"m writing a c# application using SQLite and I need the the SQLite Reference.  Using NuGet I locate the package and the output window shows a successful install.

Looking at the packages config file in the solution explorer it shows the version installed.

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="SQLite" version="3.13.0" targetFramework="net472" />
</packages>

However under the project References in the Solution explorer SQLite is not there.

I have watched tutorials online where the same process is done on other machines and all is ok, all of the references pop up after NuGet finishes the installation.

I'm using VS2019 and from what I understand there were some changes on how NuGet operates, however I had VS2015 and VS2017 Community and had the same issues.  I'm really at a standing point as I have no idea how to get the reference to show up so I can access it in my program.

SQLite has no Assembly reference so adding it there is not an option.

I have seen posts about a NuGet config file and Package Config File as well as the possibility of the package being installed outside of the Solution Folder but I don't know where.  I have looked in the output location of the solution and none of the references are located in the debug folder anywhere.

I feel the Dll's are being installed outside of the solution folder but I don't know where and how to get Visual Studio to get them to the proper location or reference there existing location correctly.

Rebuild and Restore NuGet Packages provide no solution.

Any help would be greatly appreciated.

Body:
Installing SQLite NuGet Package installs the package but the reference
  is not available. VS2019 Community

I assume you have installed sqlite version 3.13.0 nuget package.If so, it is the behavior of this nuget package. This package is very special in that it is a transactional SQL database engine that implements self-contained, serverless, zero-configuration.

In simple terms, it is a configuration function package that operates on related data when the project is running, rather than a package that provides a reference class library for the project.

Let me explain it in more detail:

This is the content of the nuget package sqlite version 3.13.0

Note that each folder provides specific functionality for the installation project.
And the function of the lib folder is to add its content(xxxx.dlls) as reference to a new project. In a word, Only the Dlls in lib folder can be recognized by nuget and added into Reference.

You can refer to this link for more detailed info about the function of the folders.

Second, there is a file called SQLite.props in the Build folder. The file will do some configuration to your project during build process.

In it, you can see these files:

<Content Include="$(MSBuildThisFileDirectory)..\..\runtimes\win7-x64\native\*">
      <Link>x64\%(Filename)%(Extension)</Link>
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <Visible>False</Visible>
    </Content>
  </ItemGroup>
  <ItemGroup Condition=" (Exists('packages.config') Or Exists('packages.$(MSBuildProjectName).config')) And '$(Platform)' == 'x86'">
    <Content Include="$(MSBuildThisFileDirectory)..\..\runtimes\win7-x86\native\*">
      <Link>%(Filename)%(Extension)</Link>
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <Visible>False</Visible>
    </Content>
  </ItemGroup>
  <ItemGroup Condition=" (Exists('packages.config') Or Exists('packages.$(MSBuildProjectName).config')) And '$(Platform)' == 'x64'">
    <Content Include="$(MSBuildThisFileDirectory)..\..\runtimes\win7-x64\native\*">
      <Link>%(Filename)%(Extension)</Link>
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <Visible>False</Visible>
    </Content>

So when you build your project, the SQLite.props file  will be executed and they  will provide services during build or at the runtime.

All of these indicates it is a package for specific execution functions rather than a nuget package for adding reference libraries to the project.

Suggestion

As a suggestion, you could install System.Data.SQLite in your project. And this nuget package provides the dlls which you want in Reference.

Hope it could help you.


问:
rxjs/redux-observable dynamic filtering based on different payloads
In short, I would like to apply a switchMap to observables depending on their payload.

I currently have an epic with redux-observable that performs GETs on /api/document/{name}. I include name in the payload of my actions. The challenge is that I only filter based on the action type, and so I don't know how to filter dynamically based on the action's payload too.

```<code>const documentFetchEpic: Epic<TRootAction, TRootAction, TRootState> = (action$, store) =>
  action$.pipe(
    filter(isActionOf(documentActions.fetch)),
    // TODO: Should filter and then switchMap based on different documentName
    mergeMap(action =>
      merge(
        ApiUtils.documents.fetch(action.payload).pipe(
          mergeMap(response => [
            documentActions.fetchSuccess({
              name: action.payload,
              data: response.data,
            }),
          ]),
          catchError(err => of(documentActions.fetchFailure(err)))
        )
      )
    )
  );
</code>```

If I made this mergeMap a switchMap, it would apply a switchMap independent of the action value. Instead, I would just like to use a switchMap if action.payload is the same.

答:
Discovered the groupBy command and came up with this... does this seem reasonable?

```<code>const documentFetchEpic: Epic<TRootAction, TRootAction, TRootState> = (action$, store) =>
  action$.pipe(
    filter(isActionOf(documentActions.fetch)),
    groupBy(({ payload }) => payload),
    mergeMap(group =>
      group.pipe(
        switchMap(action =>
          merge(
            ApiUtils.documents.fetch(action.payload).pipe(
              mergeMap(response => [
                documentActions.fetchSuccess({
                  name: action.payload,
                  data: response.data,
                }),
              ]),
              catchError(err => of(documentActions.fetchFailure(err)))
            )
          )
        )
      )
    )
  );

</code>```

Body:
In short, I would like to apply a switchMap to observables depending on their payload.

I currently have an epic with redux-observable that performs GETs on /api/document/{name}. I include name in the payload of my actions. The challenge is that I only filter based on the action type, and so I don't know how to filter dynamically based on the action's payload too.

const documentFetchEpic: Epic<TRootAction, TRootAction, TRootState> = (action$, store) =>
  action$.pipe(
    filter(isActionOf(documentActions.fetch)),
    // TODO: Should filter and then switchMap based on different documentName
    mergeMap(action =>
      merge(
        ApiUtils.documents.fetch(action.payload).pipe(
          mergeMap(response => [
            documentActions.fetchSuccess({
              name: action.payload,
              data: response.data,
            }),
          ]),
          catchError(err => of(documentActions.fetchFailure(err)))
        )
      )
    )
  );

If I made this mergeMap a switchMap, it would apply a switchMap independent of the action value. Instead, I would just like to use a switchMap if action.payload is the same.

Body:
Discovered the groupBy command and came up with this... does this seem reasonable?

const documentFetchEpic: Epic<TRootAction, TRootAction, TRootState> = (action$, store) =>
  action$.pipe(
    filter(isActionOf(documentActions.fetch)),
    groupBy(({ payload }) => payload),
    mergeMap(group =>
      group.pipe(
        switchMap(action =>
          merge(
            ApiUtils.documents.fetch(action.payload).pipe(
              mergeMap(response => [
                documentActions.fetchSuccess({
                  name: action.payload,
                  data: response.data,
                }),
              ]),
              catchError(err => of(documentActions.fetchFailure(err)))
            )
          )
        )
      )
    )
  );


问:
How to write meaningful docstrings?
What, in Your opinion is a meaningful docstring? What do You expect to be described there?

For example, consider this Python class's __init__:

```<code>def __init__(self, name, value, displayName=None, matchingRule="strict"):
    """
    name - field name
    value - field value
    displayName - nice display name, if empty will be set to field name
    matchingRule - I have no idea what this does, set to strict by default
    """
</code>```

Do you find this meaningful? Post Your good/bad examples for all to know (and a general answer so it can be accepted).

答:
From PEP 8:

Conventions for writing good documentation strings (a.k.a.
  "docstrings") are immortalized in PEP 257.

Write docstrings for all public modules, functions, classes, and methods.  Docstrings are not necessary for non-public methods, but you
  should have a comment that describes what the method does.  This
  comment should appear after the "def" line.

PEP 257 describes good docstring conventions.  Note that most importantly, the """ that ends a multiline docstring should be on a
  line by itself, and preferably preceded by a blank line.

For one liner docstrings, it's okay to keep the closing """ on the same line.

OwnerDisplayName: Konrads

ContentLicense: CC BY-SA 2.5

Title: How to write meaningful docstrings?

Body:
What, in Your opinion is a meaningful docstring? What do You expect to be described there?

For example, consider this Python class's __init__:

def __init__(self, name, value, displayName=None, matchingRule="strict"):
    """
    name - field name
    value - field value
    displayName - nice display name, if empty will be set to field name
    matchingRule - I have no idea what this does, set to strict by default
    """

Do you find this meaningful? Post Your good/bad examples for all to know (and a general answer so it can be accepted).

LastEditorDisplayName: Alabaster Codify

OwnerDisplayName: Xolve


问:
How to Implement Flexible Trial Versions and Licensing Options into Applications
Management has asked us to look into implementing licensing features into some existing applications.  Up to this point these apps were simply paid for and customers could install them as they please.  We need to implement a new licensing model to generate more revenue because our older products work well enough that people do not have a reason to upgrade.  So our new customers will have to pay licensing fees and/or be limited to how many installations they can have.  I have never dealt with this stuff before, so please pardon my ignorance.  I need as much guidance as possible (steering me in the right direction would be great!).  We need the following...

Time limited demo versions.  When they install the software, it works with full features for a fixed amount of time.  After that, when they try to run it, it tells them their license has expired.

Licensing option that limits the app to run on a particular machine.

Licensing option that limits the app to being run by a particular user.

Licensing option that limits the app to a certain total number of users or concurrent users.

Number one is pretty simple to figure out, but I have no idea how to go about implementing the other three.  Any advice is greatly appreciated.

答:
I would look at 3rd party solutions for this honestly.  There are a lot of concepts intrinsically involved in licensing, and for the cost of one week of development time you can buy a fully featured licensing product to integrate into your stuff.  This is a case where writing your own is probably not worth the hassle.

I've previously used the Desaware licensing system for user and machine based licensing.   Works well enough, no complaints. I believe their framework will be robust enough to handle all 4 of your requirements. http://www.desaware.com/products/licensingsystem/index.aspx


问:
Sapper session not setting properly in production build without page reload
I'm working on a project using Sapper, and been struggling with something for a bit now – can't quite figure it out. I'm using Polka for my server (it was included with the sveltejs/sapper-template#rollup template so I went with it), and cookie-session for my session middleware.

Here is my Polka configuration, where I seed session data also:

```<code>polka()
  .use(
    compression({ threshold: 0 }),
    sirv('static', { dev }),
    cookieSession({
      name: 'session',
      keys: [
        '6e818055-d346-4fcb-bf56-4c7d54cb04ab',
        '60f3e980-6e9c-460d-8ea7-af1fffbdb92f'
      ]
    }),
    sapper.middleware({
      session: (req, res) => ({
        user: req.session.user
      })
    })
  )
  .listen(PORT, err => {
    if (err) console.log('error', err);
  });
</code>```

When a user logs in, it's handled in routes/login.js essentially some profile info and tokens get set on session.user and the request is redirected back to the root path. I'm using @polka/send-type to respond. See below:

```<code>req.session.user = {
  accessToken: access_token,
  name: first_name,
  pic: picture.data.url
};
send(res, 302, '', {
  Location: appUrl
});
</code>```

There, I have a  preload module for routes/index.svelte checks if session.user exists, and if so redirects to dashboard:

```<code><script context="module">
  export async function preload(page, session) {
    const { user } = session;

    if (user) {
      return this.redirect(302, "dashboard");
    }
   }
</script>
</code>```

This all works fine in dev, but when I npm run build and build for production it doesn't so well. It seems like the session.user isn't getting populated after the redirect in login.js.

The session object that I get in preload doesn't have session.user set after login, and vice versa on logout where session.user is simply set to null and the client is redirected to the root, session.user is still populated.

If I refresh the browser, session.user is in the correct state. Without a refresh – if I just logged out I can click around as if I were logged in, and if I had just logged in nothing happens as session.user is undefined.

Just not sure why it'd work on the dev build but not in production. Given that the session.user state is correct on browser refresh, I'm guessing it's not an issue with the cookie middleware configuration. Seems like I'm missing something else. Any help would be hugely appreciated!

答:
Sapper does indeed handle the cache headers differently for dev and production environment. That's why you are experiencing it this way.

But there is a simple solution by changing the sapper.middleware function:

```<code>    sapper.middleware({
      session: (req, res) => {
        res.setHeader('cache-control', 'no-cache, no-store')
        return { user: req.session.user }
      }
    })
</code>```

This sets the cache-control as you want it.

Body:
I'm working on a project using Sapper, and been struggling with something for a bit now – can't quite figure it out. I'm using Polka for my server (it was included with the sveltejs/sapper-template#rollup template so I went with it), and cookie-session for my session middleware.

Here is my Polka configuration, where I seed session data also:

polka()
  .use(
    compression({ threshold: 0 }),
    sirv('static', { dev }),
    cookieSession({
      name: 'session',
      keys: [
        '6e818055-d346-4fcb-bf56-4c7d54cb04ab',
        '60f3e980-6e9c-460d-8ea7-af1fffbdb92f'
      ]
    }),
    sapper.middleware({
      session: (req, res) => ({
        user: req.session.user
      })
    })
  )
  .listen(PORT, err => {
    if (err) console.log('error', err);
  });

When a user logs in, it's handled in routes/login.js essentially some profile info and tokens get set on session.user and the request is redirected back to the root path. I'm using @polka/send-type to respond. See below:

req.session.user = {
  accessToken: access_token,
  name: first_name,
  pic: picture.data.url
};
send(res, 302, '', {
  Location: appUrl
});

There, I have a  preload module for routes/index.svelte checks if session.user exists, and if so redirects to dashboard:

This all works fine in dev, but when I npm run build and build for production it doesn't so well. It seems like the session.user isn't getting populated after the redirect in login.js.

The session object that I get in preload doesn't have session.user set after login, and vice versa on logout where session.user is simply set to null and the client is redirected to the root, session.user is still populated.

If I refresh the browser, session.user is in the correct state. Without a refresh – if I just logged out I can click around as if I were logged in, and if I had just logged in nothing happens as session.user is undefined.

Just not sure why it'd work on the dev build but not in production. Given that the session.user state is correct on browser refresh, I'm guessing it's not an issue with the cookie middleware configuration. Seems like I'm missing something else. Any help would be hugely appreciated!

Body:
Sapper does indeed handle the cache headers differently for dev and production environment. That's why you are experiencing it this way.

But there is a simple solution by changing the sapper.middleware function:

    sapper.middleware({
      session: (req, res) => {
        res.setHeader('cache-control', 'no-cache, no-store')
        return { user: req.session.user }
      }
    })

This sets the cache-control as you want it.


问:
Use of views in jam.py framework
for an academic project, I am currently using the python framework jam.py 5.4.83 to develop a back office for a new company.
I would like to use views instead of tables for reporting but I don't find how to do it, I can only import data from tables.
So if someone already used this framework, I would be very thankful.

Regards,
Yoan

答:
the use of database views are not supported in Jam.py
However, you can import tables as read only if used for reporting.
Than you can build Reports as you would.
Good luck.</p>

Title: Use of views in jam.py framework


问:
After seeding data in EFCore 3.1.1 code first, is it possible to set identity value to last id inserted + 1?
So, i am seeding some Identity Server Users with Id's 1,2,3 and 4 respectively. After trying to insert a new user after running the application, i have to 'try' to insert 4 times, before the ID is set at 5 and i can start inserting without errors.

I have tried searching for an answer, but have came up short. The question - is this doable trough Code-First approach, by using the ModelBuilder or query to database after seeding is done?

Also, i am using PostgreSQL database with code-first approach in Asp Net Core application.

EDIT: Also, here is all the ID column constraints, which show that it is a identity column.

答:
I found a more correct fix than setting negative values on database entries.

```<code>// Set starting value to start after seeded data count. Must be done
// to any entity, that can be added to from application logic.
builder.Entity<SomeTable>()
    .Property(b => b.YourIdProperty)
    .HasIdentityOptions(startValue: seededDataCount + 1);
</code>```

This is for postgreSQL, but should work really similiarly for other implementations.

Body:
I found a more correct fix than setting negative values on database entries.

// Set starting value to start after seeded data count. Must be done
// to any entity, that can be added to from application logic.
builder.Entity<SomeTable>()
    .Property(b => b.YourIdProperty)
    .HasIdentityOptions(startValue: seededDataCount + 1);

This is for postgreSQL, but should work really similiarly for other implementations.


问:
How to get Azure DevOps client using python script
I am trying to get client of Azure DevOps by using python script.
Here is the code that I am using for this purpose:

```<code>from azure.devops.connection import Connection
   git_client = p_context.connection.clients.get_git_client()
</code>```

p_context is access token of my Azure DevOps organization.

Following is the error that I am facing:

```<code>Traceback (most recent call last):
  File "/home/vsts/work/1/s/IdentifyGitBuildCommitItems.py", line 95, in <module>
    t = get_commit_changes_for_build(context ,azdevops_projectid ,azdevops_build_id ,azdevops_build_number ,bld_commit.id ,azdevops_repository_name)
  File "/home/vsts/work/1/s/IdentifyGitBuildCommitItems.py", line 51, in get_commit_changes_for_build
    comt = git_client.get_changes(p_commit_id ,repository_id=p_repository_name ,project=p_project_id)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/released/git/git_client_base.py", line 250, in get_changes
    query_parameters=query_parameters)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/client.py", line 104, in _send
    response = self._send_request(request=request, headers=headers, content=content, media_type=media_type)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/client.py", line 68, in _send_request
    self._handle_error(request, response)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/client.py", line 295, in _handle_error
    status_code=response.status_code))
azure.devops.exceptions.AzureDevOpsClientRequestError: Page not found.  Operation returned a 404 status code.
##[error]/opt/hostedtoolcache/Python/3.6.10/x64/bin/python failed with return code: 1
</code>```

This is the full GitHub example that I am following for my use case: https://github.com/venkatra/dbt_hacks/blob/PERSISTENT_TABLE_MATERIALIZATION/IdentifyGitBuildCommitItems.py

答:
You could check the Azure DevOps Python API and try the following code:</p>

```<code>from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
import pprint

# Fill in with your personal access token and org URL
personal_access_token = 'YOURPAT'
organization_url = 'https://dev.azure.com/YOURORG'

# Create a connection to the org
credentials = BasicAuthentication('', personal_access_token)
connection = Connection(base_url=organization_url, creds=credentials)

# Get a client
git_client = connection.clients.get_git_client()
</code>```

Body:
I am trying to get client of Azure DevOps by using python script.
Here is the code that I am using for this purpose:

from azure.devops.connection import Connection
   git_client = p_context.connection.clients.get_git_client()

p_context is access token of my Azure DevOps organization.

Following is the error that I am facing:

Traceback (most recent call last):
  File "/home/vsts/work/1/s/IdentifyGitBuildCommitItems.py", line 95, in <module>
    t = get_commit_changes_for_build(context ,azdevops_projectid ,azdevops_build_id ,azdevops_build_number ,bld_commit.id ,azdevops_repository_name)
  File "/home/vsts/work/1/s/IdentifyGitBuildCommitItems.py", line 51, in get_commit_changes_for_build
    comt = git_client.get_changes(p_commit_id ,repository_id=p_repository_name ,project=p_project_id)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/released/git/git_client_base.py", line 250, in get_changes
    query_parameters=query_parameters)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/client.py", line 104, in _send
    response = self._send_request(request=request, headers=headers, content=content, media_type=media_type)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/client.py", line 68, in _send_request
    self._handle_error(request, response)
  File "/opt/hostedtoolcache/Python/3.6.10/x64/lib/python3.6/site-packages/azure/devops/client.py", line 295, in _handle_error
    status_code=response.status_code))
azure.devops.exceptions.AzureDevOpsClientRequestError: Page not found.  Operation returned a 404 status code.
##[error]/opt/hostedtoolcache/Python/3.6.10/x64/bin/python failed with return code: 1

This is the full GitHub example that I am following for my use case: https://github.com/venkatra/dbt_hacks/blob/PERSISTENT_TABLE_MATERIALIZATION/IdentifyGitBuildCommitItems.py

Body:
You could check the Azure DevOps Python API and try the following code:

from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
import pprint

# Fill in with your personal access token and org URL
personal_access_token = 'YOURPAT'
organization_url = 'https://dev.azure.com/YOURORG'

# Create a connection to the org
credentials = BasicAuthentication('', personal_access_token)
connection = Connection(base_url=organization_url, creds=credentials)

# Get a client
git_client = connection.clients.get_git_client()


问:
Having a problem in redirect to the canvas page
I'm new in FB and having a problem.

I want to put an application in Facebook and already have a website and database. The application could be displayed in Facebook no matter whether the user logged in or not. In order to show the application only to the logged in user, I add some code:

```<code>if (!$session){
    $url = $facebook->getLoginUrl(array(
            'cavas' => 1,
            'fbconnet' => 0
    ));

    echo "<script type='text/javascript'>top.location.href = '$url';</script>";
}
else {
    try {
        $uid = $facebook->getUser();
        $me  = $facebook->api('/me');
    } catch (FacebookApiException $e){
        error_log($e);
    }
}
</code>```

But when a user logs in and redirects to my site, the page didn't successfully load. How can I solve it?
(The old code is written like below and runs well except for the login problem:

```<code>if ($session){

    try {
        $uid = $facebook->getUser();
        $me  = $facebook->api('/me');
    } catch (FacebookApiException $e){
        error_log($e);
    }
}
</code>```

答:
Use next and it's canvas not cavas:

```<code>if (!$session){
    $url = $facebook->getLoginUrl(array(
            'canvas' => 1,
            'next' => 'http://apps.facebook.com/CANVAS_NAME',
            'fbconnet' => 0
    ));

    echo "<script type='text/javascript'>top.location.href = '$url';</script>";
}
else {
    try {
        $uid = $facebook->getUser();
        $me  = $facebook->api('/me');
    } catch (FacebookApiException $e){
        error_log($e);
    }
}
</code>```

Body:
I'm new in FB and having a problem.

I want to put an application in Facebook and already have a website and database. The application could be displayed in Facebook no matter whether the user logged in or not. In order to show the application only to the logged in user, I add some code:

if (!$session){
    $url = $facebook->getLoginUrl(array(
            'cavas' => 1,
            'fbconnet' => 0
    ));

    echo "";
}
else {
    try {
        $uid = $facebook->getUser();
        $me  = $facebook->api('/me');
    } catch (FacebookApiException $e){
        error_log($e);
    }
}

But when a user logs in and redirects to my site, the page didn't successfully load. How can I solve it?
(The old code is written like below and runs well except for the login problem:

if ($session){

    try {
        $uid = $facebook->getUser();
        $me  = $facebook->api('/me');
    } catch (FacebookApiException $e){
        error_log($e);
    }
}

Body:
Use next and it's canvas not cavas:

if (!$session){
    $url = $facebook->getLoginUrl(array(
            'canvas' => 1,
            'next' => 'http://apps.facebook.com/CANVAS_NAME',
            'fbconnet' => 0
    ));

    echo "<script type='text/javascript'>top.location.href = '$url';</script>";
}
else {
    try {
        $uid = $facebook->getUser();
        $me  = $facebook->api('/me');
    } catch (FacebookApiException $e){
        error_log($e);
    }
}