问:
How to stop Flash content shine-through jQuery UI Dialog in Firefox on Windows
I'm using the jQuery UI dialog box, in IE & FF on Windows I'm getting underlying Flash content shining through the dialog box.

I resolved this on IE by enabling the bgiframe option on the jQuery dialog window and changing the bgiframe script to apply to any windows browsers, however I'm still getting the shine-through on FF.

Note that I can't know exactly where the Flash content will be showing as it is usually Flash widgets that users have added to pages, although I have thought about hiding the Flash content temporarily while displaying the dialog box - is this the only option left to me?

答: Either use iFrame in dialog box or hide flash contents on page when dialog box is fired.</p>

OwnerDisplayName: DEfusion

OwnerDisplayName: Stiropor

ContentLicense: CC BY-SA 2.5


来源: stackexchange

问:
How to sum two rows by a simple condition in a data frame
I'd like to sum rows 2 by 2, in order to study the lag of certain variable.

Suppose that I have the following the data base:

```<code>> SE eggs
  4  2.0
  6  4.0
  7 10.0
  8  0.5
  5  1.0
  1  3.0
  2  6.0
  3  9.0
</code>```

So, I expected to obtain the following, where eggsare the sum of the indexes "SE"'s:

```<code>> df
    SE2    eggs
  "4+5"    3
  "6+7"    14
  "8+1"    3.5
  "2+3"    15
</code>```

Where

```<code>df = data.frame(SE=c(4,6,7,8,5,1,2,3),eggs = c(2,4,10,0.5,1,3,6,9))
</code>```

Obs.: Don't mater the order of the data frame, but I need to start from certain number (in this case, number 4), and then take the next number, in this case, number 5, and keep this logic. After SE 6+7, SE 8+1, SE 2+3...

Any hint on how can I do that?

答:
I think I get the logic. You want ascending numbers starting from 4. When these numbers reach 8 (or whatever the maximum value of SE is), they wrap around back to one and continue to ascend until all the numbers are used up.

You then group these numbers into sequential pairs.

For each pair of numbers, you find the rows of your data frame with the matching values of SE. These rows contain the two values of eggs you wish to sum.

df = data.frame(SE=c(4,6,7,8,5,1,2,3),eggs = c(2,4,10,0.5,1,3,6,9))

first <- 4
i <- match(df$SE, c(first:nrow(df), seq(first - 1)))
groups <- ((seq_along(i) + 1) %/% 2)[i]

do.call(rbind, lapply(split(df, groups), function(x) {
  data.frame(SE = paste(x$SE, collapse = "+"), eggs = sum(x$eggs))}))
#>    SE eggs
#> 1 4+5  3.0
#> 2 6+7 14.0
#> 3 8+1  3.5
#> 4 2+3 15.0
```

Created on 2020-02-17 by the reprex package (v0.3.0)

ContentLicense: CC BY-SA 4.0

Body:
I'd like to sum rows 2 by 2, in order to study the lag of certain variable.

Suppose that I have the following the data base:

> SE eggs
  4  2.0
  6  4.0
  7 10.0
  8  0.5
  5  1.0
  1  3.0
  2  6.0
  3  9.0

So, I expected to obtain the following, where eggsare the sum of the indexes "SE"'s:

> df
    SE2    eggs
  "4+5"    3
  "6+7"    14
  "8+1"    3.5
  "2+3"    15

Where

df = data.frame(SE=c(4,6,7,8,5,1,2,3),eggs = c(2,4,10,0.5,1,3,6,9))

Obs.: Don't mater the order of the data frame, but I need to start from certain number (in this case, number 4), and then take the next number, in this case, number 5, and keep this logic. After SE 6+7, SE 8+1, SE 2+3...

Any hint on how can I do that?

Body:
I think I get the logic. You want ascending numbers starting from 4. When these numbers reach 8 (or whatever the maximum value of SE is), they wrap around back to one and continue to ascend until all the numbers are used up.

You then group these numbers into sequential pairs.

For each pair of numbers, you find the rows of your data frame with the matching values of SE. These rows contain the two values of eggs you wish to sum.

df = data.frame(SE=c(4,6,7,8,5,1,2,3),eggs = c(2,4,10,0.5,1,3,6,9))

first <- 4
i <- match(df$SE, c(first:nrow(df), seq(first - 1)))
groups <- ((seq_along(i) + 1) %/% 2)[i]

do.call(rbind, lapply(split(df, groups), function(x) {
  data.frame(SE = paste(x$SE, collapse = "+"), eggs = sum(x$eggs))}))
#>    SE eggs
#> 1 4+5  3.0
#> 2 6+7 14.0
#> 3 8+1  3.5
#> 4 2+3 15.0

Created on 2020-02-17 by the reprex package (v0.3.0)


问:
Can't Format Date in GraphQL in Gatsby Site
I am having trouble formatting a date in Gatsby.  I have sourced some data from firestore.  One of the fields that I have sourced is called datePublished and it contains a number in the form of a timestamp (e.g., 1576945502000).  Indeed, it really is a timestamp, but it got saved to firestore in the number format type.

Now, I would like to format the datePublished field using the formatString function in graphql -- as noted here:  https://www.gatsbyjs.org/docs/graphql-reference/#dates

But I can't get the formatting to work.  Whether I try to format the string in graphiql or on my site, it does not work.  Here is the code that I tried:

```<code>query MyQuery {
  allNewsFeed {
    edges {
      node {
        published(formatString:"dddd Mo, YYYY")
      }
    }
  }
}
</code>```

And this is the error message that I get in graphiql:

Unknown argument "formatString on field 'datePublished' of type 'NewsFeed'.

If I dig a little deeper, I notice that the field type in firestore is listed as number and in the graphiql document explorer it is listed as a FloatQueryOperatorInput.

What's more, I did a little experiment where I tried to save the same number as a string, number and timestamp in firestore.  Neither the string or number format worked and for whatever reason, the gatsby-firesource plugin will not pull in the field with a timestamp format.

So I am wondering, what do I have to do to get this to work in gatsby?

Any ideas?

Thanks.

答:
I had a similar situation with Gatsby not accepting "formatString" on a date field, for me what solved the issue was to change the format of the field to YYYY-MM-DD so it went from 02 06 2017 to 2017-06-02 and gatsby got the hint that that field represents a date.
It seems gatsby "reads" the data and guesses the type and based on that we get certain functionality.

Since gatsby uses moment.js I'm guessing the YYYY-MM-DD format is picked up by it.

I'm using MDX so it was really easy for me to change the format of my date field since it's just plain text, I'm not sure you have the same luxury with firestore but I hope this at least give you some ideas to try out. Good luck!

Body:
I am having trouble formatting a date in Gatsby.  I have sourced some data from firestore.  One of the fields that I have sourced is called datePublished and it contains a number in the form of a timestamp (e.g., 1576945502000).  Indeed, it really is a timestamp, but it got saved to firestore in the number format type.

Now, I would like to format the datePublished field using the formatString function in graphql -- as noted here:  https://www.gatsbyjs.org/docs/graphql-reference/#dates

But I can't get the formatting to work.  Whether I try to format the string in graphiql or on my site, it does not work.  Here is the code that I tried:

query MyQuery {
  allNewsFeed {
    edges {
      node {
        published(formatString:"dddd Mo, YYYY")
      }
    }
  }
}

And this is the error message that I get in graphiql:

Unknown argument "formatString on field 'datePublished' of type 'NewsFeed'.

If I dig a little deeper, I notice that the field type in firestore is listed as number and in the graphiql document explorer it is listed as a FloatQueryOperatorInput.

What's more, I did a little experiment where I tried to save the same number as a string, number and timestamp in firestore.  Neither the string or number format worked and for whatever reason, the gatsby-firesource plugin will not pull in the field with a timestamp format.

So I am wondering, what do I have to do to get this to work in gatsby?

Any ideas?

Thanks.


问:
Understanding git conflicts
I think I might be misunderstanding something about how git handles things, and, therefore, I'm facing some rather annoying conflicts.

I start a new branch A, from master, and start creating new files. Eventually, from branch A, I create branch B, and start working on that as well. A branch A continues to be developed, B needs the changes made in branch A, so I merge A into B, and continue working on both of them.

Times goes on, branch A continues to be developed, until it is merged into master. At this point, I think that, now it has been merged into master, I can do a simply merge master into B, and get all changes from A, and from everyone else as well.

Problem is, now that I'm trying to do that, I'm getting multiple conflicts of "Both added", "Both modified", and such - but on files I haven't changed. I totally understand the conflicts in the files I changed - I caused them, I know it full well.

Thinking my explanation my get confusing, I ventured into Google Slides and created this "amazing" drawing to illustrate my scenario (in which the arrows represent merges, as in "merged master into A", unless they point to the first commit in the branch - in which case they mean "branched off from here"; that is, pretty standard git notation, apart from the arrow direction - not sure here):

Regarding files other people changed, I don't understand why are they listed as conflicts. That is, there is a file which has been changed by the time I created branch A, and that same file got changed again when I tried to merge master into B. Sure, branch B still has a super old version of that given file, but, still, shouldn't git recognize that they have not been changed in my commits, and just overwrite them, or whatever it does? What am I missing here?

EDIT: just to clarify, I'm the sole contributor of both branches A and B.

答:
shouldn't git recognize that they have not been changed in my commits, and just overwrite them?

No.

It doesn't matter that you didn't change the file. There is nothing in git's head about who created the commits or who gets priority. Neither master nor b is "better" in some way.

The point is only that the file as known to master and the file as known to b differ in a way that cannot be automatically reconciled.

Git can automatically reconcile some differences, obviously; for instance, if a file is different in one branch because line 1 was changed and different in the other branch because line 1000 was changed. But sometimes it just throws up its hands and lets you sort it out. That's not because of who changed the file, it's because of the nature of the differences.

As for what the differences are, I think it will help to read https://stackoverflow.com/a/56053884/341994 — that is best essay I have ever read on what a merge is and how it works. It's all about the LCA and the diffs from it to the ends of the branches. In your diagram, the LCA is the second commit from the far left, all the way back at the point where A was first branched off. All the differences between that commit and the end of master, and all the differences between that commit and the end of b, must be accounted for in order to merge. Well, git is telling you that for this file it can't do that. And if you think about how the file has changed from there to the end of master and from there to the end of b, you will see why.

It doesn't matter who changed the files or how you draw the diagram. It doesn't matter that there is a path that describes (in your mind) the history of what happened. All that matters is three states of things: the state of things at the time of that very early commit, the state of things at the end of master, and the state of things at the end of b.

Title: Understanding git conflicts


问:
How to get selected radio button from ToggleGroup
I an working on JavaFX 8 and SceneBuilder. I created some radio buttons in the FXML File and specified a toggleGroup name to a radio button list in that. So, now I want to get the toggleGroup's selected radio button in my controller, do I need to make all the radio buttons again as fields in the controller, or just the toggleGroup object will get me the selected radio button (the text of that radio button only, not the button object).

答:
```<code>public class MyControler {
    @FXML
    private ToggleGroup myToggleGroup;

    @FXML
    public void initialize(){
        //the simplest way to print current value (text of the selected radio button)
        System.out.format("Selected Radio Button: " + ((RadioButton)myToggleGroup.getSelectedToggle()).getText());

        //register on change event
        myToggleGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>()
        {
            @Override
            public void changed(ObservableValue<? extends Toggle> observable, Toggle oldToggle, Toggle newToggle)
            {
                //print new selected value after change
                System.out.println("Selected Radio Button: " + ((RadioButton)newToggle).getText());
            }
        });
    }

    //sample method to set radio button (unselect all if group don't contain value)
    private void setRadioButtons(ToggleGroup toggleGroup, String value) {
        for (Toggle t : toggleGroup.getToggles())
            t.setSelected(((RadioButton) t).getText().equals(value));
    }

    //sample method to set radio button (select existing value or do nothing)
    private void setRadioButton(ToggleGroup toggleGroup, String value) {
        for (Toggle t : toggleGroup.getToggles())
            if(((RadioButton) t).getText().equals(value))
                t.setSelected(true);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0


问:
What is the easiest mail server setup for piping incoming mails to scripts *only*?
I want to set up a ticketing system (osTicket) on a centOS server that generates tickets from incoming e-mails.

osTicket can query mailboxes, but it also provides an API / scripts for piping. Is there a recommended way to setup a (lightweight) mailserver to pipe incoming emails to the script? I do not need actual mailboxes for users.

It's been a while since I did any work on a mail server, but it seems to me that I would only need to set up an MTA for this, and no MDA, correct?

My fallback is to set up POP3/SMTP inboxes elsewhere and query from osTicket. Easy as that would be, the local MTA setup seems cleaner to me.

答:
Consider using remote mailbox accessible via IMAP with IMAP IDLE command support.
It will allow you to get "near real time" delivery to pipe without burden of configuring properly your own SMTP server.

[AFAIR IMAP IDLE is supported e.g. by gmail]

You may use fetchmail with custom procmail script as mda (no need for local SMTP/MTA server).

Using procmail (as "man in the middle) is not strictly necessary but your it will allow you to easily run filtering before delivery to the ticket system (e.g. anti-spam + anti-virus).


问:
Prolog Program Not Merging Sorted Lists Correctly
I have a simple program I'm trying to write in Prolog. Essentially, as I learning exercise, I'm trying to write a program that takes two sorted lists as input, and returns the merged list that is also sorted. I have dubbed the predicate "merge2" as to no be confused with the included predicate "merge" that seems to do this already.

I am using recursion. My implementation is below

```<code>merge2([],[],[]).
merge2([X],[],[X]).
merge2([],[Y],[Y]).
merge2([X|List1],[Y|List2],[X|List]):- X =< Y,merge2(List1,[Y|List2],List).
merge2([X|List1],[Y|List2],[Y|List]):- merge2([X|List1],List2,List).
</code>```

When I run this, I get X = [1,2,4,5,3,6] which is obviously incorrect. I've been able to code multiple times and tried to draw out the recursion. To the best of my knowledge, this should be returning the correct result. I'm not sure why the actualy result is so strange.

Thank you.

答:
This is done using difference list and since you are learning it uses reveals, AKA spoiler, which are  the empty boxes that you have to mouse over to ravel the contents. Note that the reveals don't allow for nice formatting of code. At the end is the final version of the code with nice formatting but not hidden by a reveal so don't peek at the visible code at the very end if you want to try it for yourself.

This answer takes it that you have read my Difference List wiki.

Your basic idea was sound and the basis for this answer using difference list. So obviously the big change is to just change from closed list to open list.

As your code is recursive, the base case can be used to set up the pattern for the rest of the clauses in the predicate.

Your simplest base case is

```<code>merge2([],[],[]).
</code>```

but a predicate using difference list can use various means to represent a difference list with the use of L-H being very common but not one I chose to use. Instead this answer will follow the pattern in the wiki of using two variables, the first for the open list and the second for the hole at the end of the open list.

Try to create the simple base case on your own.

 merge2_prime([],[],Hole,Hole).

Next is needed the two base cases when one of the list is empty.

 merge2_prime([X],[],Hole0,Hole) :-

     Hole0 = [X|Hole].

 merge2_prime([],[Y],Hole0,Hole) :-

     Hole0 = [Y|Hole].

Then the cases that select an item from one or the other list.

merge2_prime([X|List1],[Y|List2],Hole0,Hole) :-

    X =< Y,

    Hole0 = [X|Hole1],

    merge2_prime(List1,[Y|List2],Hole1,Hole).

merge2_prime(List1,[Y|List2],Hole0,Hole) :-

    Hole0 = [Y|Hole1],

    merge2_prime(List1,List2,Hole1,Hole).

Lastly a helper predicate is needed so that the query merge2(L1,L2,L3) can be used.

merge2(L1,L2,L3) :-

    merge2_prime(L1,L2,Hole0,Hole),

    Hole = [],

    L3 = Hole0.

If you run the code as listed it will produce multiple answer because of backtracking. A few cuts will solve the problem.

```<code>merge2(L1,L2,L3) :-
    merge2_prime(L1,L2,Hole0,Hole),
    Hole = [],
    L3 = Hole0.
merge2_prime([],[],Hole,Hole) :- !.
merge2_prime([X],[],Hole0,Hole) :-
    !,
    Hole0 = [X|Hole].
merge2_prime([],[Y],Hole0,Hole) :-
    !,
    Hole0 = [Y|Hole].
merge2_prime([X|List1],[Y|List2],Hole0,Hole) :-
    X =< Y,
    !,
    Hole0 = [X|Hole1],
    merge2_prime(List1,[Y|List2],Hole1,Hole).
merge2_prime(List1,[Y|List2],Hole0,Hole) :-
    Hole0 = [Y|Hole1],
    merge2_prime(List1,List2,Hole1,Hole).
</code>```

Example run:

```<code>?- merge2([1,3,4],[2,5,6],L).
L = [1, 2, 3, 4, 5, 6].

?- merge2([0],[0],L).
L = [0, 0].
</code>```

I didn't check this with lots of examples as this was just to demonstrate that an answer can be found using difference list.

Body:
I have a simple program I'm trying to write in Prolog. Essentially, as I learning exercise, I'm trying to write a program that takes two sorted lists as input, and returns the merged list that is also sorted. I have dubbed the predicate "merge2" as to no be confused with the included predicate "merge" that seems to do this already.

I am using recursion. My implementation is below

merge2([],[],[]).
merge2([X],[],[X]).
merge2([],[Y],[Y]).
merge2([X|List1],[Y|List2],[X|List]):- X =< Y,merge2(List1,[Y|List2],List).
merge2([X|List1],[Y|List2],[Y|List]):- merge2([X|List1],List2,List).

When I run this, I get X = [1,2,4,5,3,6] which is obviously incorrect. I've been able to code multiple times and tried to draw out the recursion. To the best of my knowledge, this should be returning the correct result. I'm not sure why the actualy result is so strange.

Thank you.

Body:
This is done using difference list and since you are learning it uses reveals, AKA spoiler, which are  the empty boxes that you have to mouse over to ravel the contents. Note that the reveals don't allow for nice formatting of code. At the end is the final version of the code with nice formatting but not hidden by a reveal so don't peek at the visible code at the very end if you want to try it for yourself.

This answer takes it that you have read my Difference List wiki.

Your basic idea was sound and the basis for this answer using difference list. So obviously the big change is to just change from closed list to open list.

As your code is recursive, the base case can be used to set up the pattern for the rest of the clauses in the predicate.

Your simplest base case is

merge2([],[],[]).

but a predicate using difference list can use various means to represent a difference list with the use of L-H being very common but not one I chose to use. Instead this answer will follow the pattern in the wiki of using two variables, the first for the open list and the second for the hole at the end of the open list.

Try to create the simple base case on your own.

 merge2_prime([],[],Hole,Hole).

Next is needed the two base cases when one of the list is empty.

 merge2_prime([X],[],Hole0,Hole) :-

     Hole0 = [X|Hole].

 merge2_prime([],[Y],Hole0,Hole) :-

     Hole0 = [Y|Hole].

Then the cases that select an item from one or the other list.

merge2_prime([X|List1],[Y|List2],Hole0,Hole) :-

    X =< Y,

    Hole0 = [X|Hole1],

    merge2_prime(List1,[Y|List2],Hole1,Hole).

merge2_prime(List1,[Y|List2],Hole0,Hole) :-

    Hole0 = [Y|Hole1],

    merge2_prime(List1,List2,Hole1,Hole).

Lastly a helper predicate is needed so that the query merge2(L1,L2,L3) can be used.

merge2(L1,L2,L3) :-

    merge2_prime(L1,L2,Hole0,Hole),

    Hole = [],

    L3 = Hole0.

If you run the code as listed it will produce multiple answer because of backtracking. A few cuts will solve the problem.

merge2(L1,L2,L3) :-
    merge2_prime(L1,L2,Hole0,Hole),
    Hole = [],
    L3 = Hole0.
merge2_prime([],[],Hole,Hole) :- !.
merge2_prime([X],[],Hole0,Hole) :-
    !,
    Hole0 = [X|Hole].
merge2_prime([],[Y],Hole0,Hole) :-
    !,
    Hole0 = [Y|Hole].
merge2_prime([X|List1],[Y|List2],Hole0,Hole) :-
    X =< Y,
    !,
    Hole0 = [X|Hole1],
    merge2_prime(List1,[Y|List2],Hole1,Hole).
merge2_prime(List1,[Y|List2],Hole0,Hole) :-
    Hole0 = [Y|Hole1],
    merge2_prime(List1,List2,Hole1,Hole).

Example run:

?- merge2([1,3,4],[2,5,6],L).
L = [1, 2, 3, 4, 5, 6].

?- merge2([0],[0],L).
L = [0, 0].

I didn't check this with lots of examples as this was just to demonstrate that an answer can be found using difference list.


问:
CPU soft lockup on GCP - KVM on Centos
For the past couple of weeks I am seeing this softlockup issue on GCP. VM gets extremely slow and CPU utilization rate is normal. Has anyone seen this recently, is there any debugging I can do to get to the bottom of thisCPU Utilization chart

Message from syslogd@testbed-6 at Feb 13 20:40:46 ...
 kernel:NMI watchdog: BUG: soft lockup - CPU#11 stuck for 22s! [qemu-kvm:1547]
[Error logs]2

System info:
Using the latest centos image https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/family/centos-7

答:
Normally when you have a CPU utilization issue on GCP Virtual Machine (VM) instances, the CPU issue could be by exceeding the IOPS and throughput limits, you can check the limits on GCP disks (standard or SSD persistent disk) according to following tables, check the "Disk I/O bytes and Disk I/O (operations)"graphics in the monitoring section on your VM instance and if you exceed the suggested values, Resize your persistent disks to increase the IOPS and throughput limits.

Greetings.

Aldo.

Title: CPU soft lockup on GCP - KVM on Centos


问:
Routing Error when the Route exists
I get this routing error when loading the page:

```<code>ActionController::RoutingError in Videos#index

Showing /rubyprograms/dreamstill/app/views/layouts/application.html.erb where line #26 raised:

No route matches {:action=>"show", :controller=>"profiles"}
</code>```

It is referring to this line:

```<code><%= link_to "Profile", profile_path(current_user.profile), :class => 'normal' %>
</code>```

However, the route exists because I have this in my routes:

```<code>resources :profiles do
    get 'activity', :on => :member
    get 'shown_songs', :on => :member
end
</code>```

and I have this action in my profiles controller:

```<code>def show
  @profile = Profile.find(params[:id])
end
</code>```

What's going on and how can I fix this?

答:
If you're passing a nil object to your url helper, you will see this error. Check that current_user.profile isn't nil in this line:</p>

```<code>profile_path(current_user.profile)
</code>```

Title: Routing Error when the Route exists

Body:
I get this routing error when loading the page:

ActionController::RoutingError in Videos#index

Showing /rubyprograms/dreamstill/app/views/layouts/application.html.erb where line #26 raised:

No route matches {:action=>"show", :controller=>"profiles"}

It is referring to this line:

<%= link_to "Profile", profile_path(current_user.profile), :class => 'normal' %>

However, the route exists because I have this in my routes:

resources :profiles do
    get 'activity', :on => :member
    get 'shown_songs', :on => :member
end

and I have this action in my profiles controller:

def show
  @profile = Profile.find(params[:id])
end

What's going on and how can I fix this?

Body:
If you're passing a nil object to your url helper, you will see this error. Check that current_user.profile isn't nil in this line:

profile_path(current_user.profile)


问:
How do I delete an sql database in Azure?
I have used the following powershell script to delete a database:

```<code>Remove-AzureRmSqlDatabase -ServerName $server -ResourceGroupName $rgname -DatabaseName $dbname
</code>```

(first setting the variables)

and have tried using the Azure Portal

The port indicates a success in deletion, as does the activity logs, however

the resource is not being deleted?

Screenshot of activity log:

The deletes (on a number of occasions after the db comes back) show successful, however there is an audit policy that seems to be doing something.
There are no Locks on the resrouce group.

UPDATE:

I have deleted from SSMS, and is not showing there or in the portal anymore..
(will wait to see if it comes back, as it did when deleting via portal and powershell)

UPDATE 2:
Database is now back, so this is the database having been deleted 3 ways, portal, powershell and via SSMS.

答:
It turns out the web application uses EF migrations which is recreating the database.

Note: The bigger issue is that the database is created on a much higher, and much more expensive tier.

Body:
I have used the following powershell script to delete a database:

Remove-AzureRmSqlDatabase -ServerName $server -ResourceGroupName $rgname -DatabaseName $dbname

(first setting the variables)

and have tried using the Azure Portal

The port indicates a success in deletion, as does the activity logs, however

the resource is not being deleted?

Screenshot of activity log:

The deletes (on a number of occasions after the db comes back) show successful, however there is an audit policy that seems to be doing something.
There are no Locks on the resrouce group.

UPDATE:

I have deleted from SSMS, and is not showing there or in the portal anymore..
(will wait to see if it comes back, as it did when deleting via portal and powershell)

UPDATE 2:
Database is now back, so this is the database having been deleted 3 ways, portal, powershell and via SSMS.


问:
Threading with .Net Core
I'm trying to make a series of microservices and am currently working on a base class for them utilizing a .Net Core console app.  The goal is to have the services, deployed as Docker containers, be able to monitor a source of information (Kafka, SQL, whatever) ,and then activate when they find their trigger.  A dev should be able to just grab this base class and put their logic in place without having to worry about the logic triggering it or any other underlying service logic.

To do this I'm trying to utilize threading in the base class in a way that the user of the class doesn't have to deal with it but keeps the service responsive and able to monitor/respond to external commands (like the ability to get status, cancel a job, etc).  Unfortunately it seems that Microsoft is trying to do away with System.Threading in .Net core, since I can start threads them but I can't stop them.  This removes the ability to cancel/pause a job, which in turn removes the ability to shut down the service since I cannot stop the thread.

I've looked at Tasks, but they seem to be for web development.  In fact most if not all information I've found about threading and microservices in .Net Core refers to making WebAPIs in ASP .Net.  Other than that I really haven't found much information about how to use System.Threading now that every control other than .Start seems to have been removed.

I'm about to look at a system where I have the thread host a Task, then try using Task controls to see if I can cancel it and then have the thread just gracefully drop (similar to answer from here: dotnet core equivalent to Thread.Abort).  This doesn't feel right, like I'm making a toothpick tower that can easily break, however I need to have the base service maintain control over the thread; I don't want myself or others to have to continuously check a token throughout their logic to see if the thread is supposed to be shut down.

Is there a better way of going about what I'm trying to do here?  I've been looking for days but I keep running into the same stuff and it's all about how to make webapis utilizing Tasks, which is nothing like what I'm trying to do here; they pause the main logic rather than run independently.  Guess it's an annoying bi-product of this "everything must be a website" frame of mind in the industry.  Not sure if I'm missing something obvious by asking the wrong questions or if it's just going to be this odd of a job.

答:
Task and await/async language features are a nice way to abstract threading, and are supposed to help exactly for what you wish for (keep the application responsive by using thread pool), whilst saving you the hassle of properly create and manage all those threads (not to mention catching exceptions during asynchronous execution).

As stated in comments, I think you should give it a try "properly" and then measure if it meets your performance objectives.

Some of the functions returning a Task return them "hot" (meaning, already executing their work). If you do not wish to "pause the Main flow", just do not await the Task returned until the end of your workflow. By the way, this should be the case when using Task.Run.

Sometimes, Task are "cold", and started automatically when await is called. But you can start them manually without awaiting them by using Task.Start.

Of course, using Tasks have it's pitfalls and you should should still be aware of what it does behind the scenes. You can still  do "bad" thread programming things, for instance cause deadlocks in some situations, or fail to handle exceptions.

Further reading, picked up among many :

A Tour of Tasks, a series of blog posts by Stephen Cleary

Microsoft documentation : Asynchronous programming - follow the links in the article for much more doc !

MSDN article : Async/Await - Best Practices in Asynchronous Programming also by Stephen Cleary

but there are many more.

Title: Threading with .Net Core


问:
how can i do dot production in python?
Write the function dot_product(M, N), that takes as parameters two matrices M and N, and returns a new matrix containing dot product of these matrices.

I understand the logic but not sure how to do the multiply each rows and columns this is what i have so far

```<code>def dot_product(M, N):

    """ takes as parameters two matrices M and N, and returns a new matrix
        containing dot product of these matrices
    """

    assert( len(M[0]) == len(N)), " innter length differnet "

    new_matrix = zeros(len(M[0]) , len(N))

    transP = transpose(N)

    storing_values = []

    for r in range(len(M)):

        for c in range(len(M[0])):

            storing_values += M[r][c] * transP[r][c]
</code>```

I'm using helper function transpose to rotate the matrix N so when i iterate I'm looking at same columns and rows for both matrices.

output should look like this :
 [[26.00, 4.00]
 [62.00, 13.00]]

答:
Using the numpy in-built dot product function looks easy: https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html

Should be something to the effect of:

```<code>import numpy as np

def dot_product(M, N):
    return np.dot(np.asarray(M), np.asarray(N))
</code>```

In general, a lot of functionality in python has already been implemented in packages like numpy, I try not to reinvent the wheel. Not sure if this is acceptable in your case as this seems to be a homework problem, but this is the easiest way to get the dot product of two matrices.

Title: how can i do dot production in python?

Body:
Write the function dot_product(M, N), that takes as parameters two matrices M and N, and returns a new matrix containing dot product of these matrices.

I understand the logic but not sure how to do the multiply each rows and columns this is what i have so far

def dot_product(M, N):

    """ takes as parameters two matrices M and N, and returns a new matrix
        containing dot product of these matrices
    """

    assert( len(M[0]) == len(N)), " innter length differnet "

    new_matrix = zeros(len(M[0]) , len(N))

    transP = transpose(N)

    storing_values = []

    for r in range(len(M)):

        for c in range(len(M[0])):

            storing_values += M[r][c] * transP[r][c]

I'm using helper function transpose to rotate the matrix N so when i iterate I'm looking at same columns and rows for both matrices.

output should look like this :
 [[26.00, 4.00]
 [62.00, 13.00]]

Body:
Using the numpy in-built dot product function looks easy: https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html

Should be something to the effect of:

import numpy as np

def dot_product(M, N):
    return np.dot(np.asarray(M), np.asarray(N))

In general, a lot of functionality in python has already been implemented in packages like numpy, I try not to reinvent the wheel. Not sure if this is acceptable in your case as this seems to be a homework problem, but this is the easiest way to get the dot product of two matrices.


问:
Use a subtype with mypy
I have a function that takes a list of objects and prints it.

```<code>bc_directives = t.Union[
    data.Open,
    data.Close,
    data.Commodity,
    data.Balance,
    data.Pad,
    data.Transaction,
    data.Note,
    data.Event,
    data.Query,
    data.Price,
    data.Document,
    data.Custom,
]

def print_entries(entries: t.List[bc_directives], file: t.IO) -> None:
    pass
</code>```

but if I do :

```<code>accounts: t.List[bc_directives] = []

for entry in data.sorted(entries):
  if isinstance(entry, data.Open):
    accounts.append(entry)
    continue
accounts = sorted(accounts, key=lambda acc: acc.account)

# the attribute account does not exist for the other class.

print_entries(accounts)
</code>```

Here I have a problem.
mypy complain that the other class does not have account attribute. Of course it is designed like that.

Item "Commodity" of "Union[Open, Close, Commodity, Balance, Pad, Transaction, Note, Event, Query, Price, Document, Custom]" has no attribute "account"

If I change the definition of accounts to t.List[data.Open], mypy complains when I used print_entries. (but it should be the best).
So how can I use use a subset of a union and get mypy to not complain?

答:
You should make print_entries accept a Sequence, not a List. Here is a simplified example demonstrating a type-safe version of your code:

```<code>from typing import IO, List, Sequence, Union

class Open:
    def __init__(self, account: int) -> None:
        self.account = account

class Commodity: pass

Directives = Union[Open, Commodity]

def print_entries(entries: Sequence[Directives]) -> None:
    for entry in entries:
        print(entry)

accounts: List[Open] = [Open(1), Open(2), Open(3)]
print_entries(accounts)
</code>```

The reason why making print_entries accept a list of your directive types is because it would introduce a potential bug in your code -- if print_entries were to do entries.append(Commodities()), your list of accounts would no longer contain only Open objects, breaking type safety.

Sequence is a read-only version of a list and so sidesteps this problem entirely, letting it have fewer restrictions. (That is, List[T] is a subclass of Sequence[T]).

More precisely, we say that Sequence is a covariant type: if if we have some child type C that subclasses a parent type P (if P :> C), it is always true that Sequence[P] :> Sequence[C].

In contrast, Lists are invariant: List[P] and List[C] will have no inherent relationship to each other, and neither subclasses the other.

Here is a tabular summary of the different kinds of relationships generic types can be designed to have:

```<code>              | Foo[P] :> Foo[C] | Foo[C] :> Foo[P] | Used for
--------------------------------------------------------------------------------------
Covariant     | True             | False            | Read-only types
Contravariant | False            | True             | Write-only types
Invariant     | False            | False            | Both readable and writable types
Bivariant     | True             | True             | Nothing (not type safe)
</code>```

Title: Use a subtype with mypy

Body:
I have a function that takes a list of objects and prints it.

bc_directives = t.Union[
    data.Open,
    data.Close,
    data.Commodity,
    data.Balance,
    data.Pad,
    data.Transaction,
    data.Note,
    data.Event,
    data.Query,
    data.Price,
    data.Document,
    data.Custom,
]

def print_entries(entries: t.List[bc_directives], file: t.IO) -> None:
    pass

but if I do :

accounts: t.List[bc_directives] = []

for entry in data.sorted(entries):
  if isinstance(entry, data.Open):
    accounts.append(entry)
    continue
accounts = sorted(accounts, key=lambda acc: acc.account)

# the attribute account does not exist for the other class.

print_entries(accounts)

Here I have a problem.
mypy complain that the other class does not have account attribute. Of course it is designed like that.

Item "Commodity" of "Union[Open, Close, Commodity, Balance, Pad, Transaction, Note, Event, Query, Price, Document, Custom]" has no attribute "account"

If I change the definition of accounts to t.List[data.Open], mypy complains when I used print_entries. (but it should be the best).
So how can I use use a subset of a union and get mypy to not complain?

Body:
You should make print_entries accept a Sequence, not a List. Here is a simplified example demonstrating a type-safe version of your code:

from typing import IO, List, Sequence, Union

class Open:
    def __init__(self, account: int) -> None:
        self.account = account

class Commodity: pass

Directives = Union[Open, Commodity]

def print_entries(entries: Sequence[Directives]) -> None:
    for entry in entries:
        print(entry)

accounts: List[Open] = [Open(1), Open(2), Open(3)]
print_entries(accounts)

The reason why making print_entries accept a list of your directive types is because it would introduce a potential bug in your code -- if print_entries were to do entries.append(Commodities()), your list of accounts would no longer contain only Open objects, breaking type safety.

Sequence is a read-only version of a list and so sidesteps this problem entirely, letting it have fewer restrictions. (That is, List[T] is a subclass of Sequence[T]).

More precisely, we say that Sequence is a covariant type: if if we have some child type C that subclasses a parent type P (if P :> C), it is always true that Sequence[P] :> Sequence[C].

In contrast, Lists are invariant: List[P] and List[C] will have no inherent relationship to each other, and neither subclasses the other.

Here is a tabular summary of the different kinds of relationships generic types can be designed to have:

              | Foo[P] :> Foo[C] | Foo[C] :> Foo[P] | Used for
--------------------------------------------------------------------------------------
Covariant     | True             | False            | Read-only types
Contravariant | False            | True             | Write-only types
Invariant     | False            | False            | Both readable and writable types
Bivariant     | True             | True             | Nothing (not type safe)


问:
Angular | Bootstrap - Close function on modal
I have been looking on how to simply close the modal that is popped up after clicking an image. I am using bootstrap with angular.

```<code>                    <img id="1" data-toggle="modal" data-target="#myModal" data-dismiss="modal" src='assets/barrel.jpg' alt='Text dollar code part one.' />
                <div id="myModal" class="modal fade" >
                        <div class=" modal-lg center">
                            <div class="modal-header">
                                <button type="button" #closebutton class="close" data-dismiss="modal">×</button>
                                    <div class="modal-content">
                                            <div class="modal-body">
                                                    <img id="1"src="assets/barrel.jpg" class="img-responsive">
                                                    <img id="2"src="assets/car.jpg" class="img-responsive">
                                            </div>
                                    </div>
                            </div>
                        </div>
                </div>
</code>```

this above is my html snippit

```<code>import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NgModule } from '@angular/core';

@Component({
  selector: 'app-portfolio',
  templateUrl: './portfolio.component.html',
  styleUrls: ['./portfolio.component.scss']
})
export class PortfolioComponent implements OnInit {
  @ViewChild('closebutton') closebutton;

  constructor(private fb: FormBuilder) { }

  public ngOnInit() {

  }

  public onSave() {
    this.closebutton.nativeElement.click();
  }

}
</code>```

this is my component typescript

答:
You can simply use ngIf with a boolean that you can toggle.

JS

```<code>isModalShowing: boolean;

toggleModal() {
  this.isModalShowing = !this.isModalShowing;
}
</code>```

HTML

```<code><div id="myModal" class="modal fade" *ngIf="isModalShowing">
      <div class=" modal-lg center">
      <div class="modal-header">
        <button type="button" class="close" (click)="toggleModal()">×</button>
        <div class="modal-content">
          <div class="modal-body">
          <img id="1"src="assets/barrel.jpg" class="img-responsive">
          <img id="2"src="assets/car.jpg" class="img-responsive">
          </div>
          </div>
        </div>
      </div>
    </div>
</code>```

Body:
I have been looking on how to simply close the modal that is popped up after clicking an image. I am using bootstrap with angular.

                                <button type="button" #closebutton class="close" data-dismiss="modal">×</button>

this above is my html snippit

import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NgModule } from '@angular/core';

@Component({
  selector: 'app-portfolio',
  templateUrl: './portfolio.component.html',
  styleUrls: ['./portfolio.component.scss']
})
export class PortfolioComponent implements OnInit {
  @ViewChild('closebutton') closebutton;

  constructor(private fb: FormBuilder) { }

  public ngOnInit() {

  }

  public onSave() {
    this.closebutton.nativeElement.click();
  }

}

this is my component typescript

Body:
You can simply use ngIf with a boolean that you can toggle.

JS

isModalShowing: boolean;

toggleModal() {
  this.isModalShowing = !this.isModalShowing;
}

HTML

<div id="myModal" class="modal fade" *ngIf="isModalShowing">
      <div class=" modal-lg center">
      <div class="modal-header">
        <button type="button" class="close" (click)="toggleModal()">&times;</button>
        <div class="modal-content">
          <div class="modal-body">
          <img id="1"src="assets/barrel.jpg" class="img-responsive">
          <img id="2"src="assets/car.jpg" class="img-responsive">
          </div>
          </div>
        </div>
      </div>
    </div>


问:
NavController crashes upon orientation change
I'm not really sure what I'm doing wrong here. Simple setup, single activity with fragments controlled by a bottom bar inside, so far so good. The start fragment has a button inside which should navigate to another fragment.

Here's the onclicklistener for the button inside my fragment class:

```<code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    add_step_fab.setOnClickListener {
        Navigation.findNavController(view).navigate(R.id.fragmentAtoB)
    }
}
</code>```

Here's my action in the navigation.xml:

```<code><fragment android:id="@+id/navigation_main" android:name="com.test.test.fragments.AFragment"
          android:label="Fragment A" tools:layout="@layout/fragment_a">
    <action android:id="@+id/fragmentAtoB"
            app:destination="@id/fragmentB" app:enterAnim="@anim/nav_default_enter_anim"
            app:exitAnim="@anim/nav_default_exit_anim" app:popEnterAnim="@anim/nav_default_pop_enter_anim"
            app:popExitAnim="@anim/nav_default_pop_exit_anim"/>
</fragment>
</code>```

The navigation works, but I get the standard

```<code>java.lang.IllegalArgumentException: navigation destination com.test.test:id/fragmentAtoB is unknown to this NavController
</code>```

error when I click on the button after rotating my screen, split screening the app, or sometimes seemingly randomly. Looks like it has something to do with the configuration change?

EDIT:
I also tried using

```<code>val clickListener: View.OnClickListener = Navigation.createNavigateOnClickListener(R.id.fragmentAtoB)
    add_step_fab.setOnClickListener(clickListener)
</code>```

with the same issue as above.

Checking if i'm actually in the same fragment, as some suggested for users who are having the same exception (but for unrelated reasons), such as:

```<code>if (controller.currentDestination?.id == R.id.navigation_main) {
            controller.navigate(R.id.fragmentAtoB)
        }
</code>```

also didn't help.

答:
I also experienced this recently after months of an app working correctly. I originally had added navigation to an app that was utilizing a "MainActivity" class and then had other activities that would be launched from a menu (as opposed to having the Navigation component navigate between fragments off of a single Activity).

So the app is organized such that the MainActivity is the "hub", and choices from menu options cause other activities to be launched, and when the user returns from them they are back at the MainActivity - so a pure "hub (MainActivity) and spoke (5 other activities)" model.

Within MainActivity.onCreate() is called a setupNavigation() method which originally looked like:

```<code>private void setupNavigation() {
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    drawerLayout = findViewById(R.id.drawer_layout);

    // This class implements the listener interface for the NavigationView, handler is below.
    NavigationView navigationView = findViewById(R.id.nav_view);
    navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout);
    NavigationUI.setupWithNavController(navigationView, navController);

    // MainActivity implements the listener for navigation events
    navigationView.setNavigationItemSelectedListener(this);

}
</code>```

As I mentioned, this was working just fine even with configuration changes until recently. Even just changing the configuration from portrait to landscape on the MainActivity would cause an exception:

```<code>ComponentInfo{com.reddragon.intouch/com.reddragon.intouch.ui.MainActivity}: java.lang.IllegalStateException: You must call setGraph() before calling getGraph()
</code>```

I found I had to add this line:

```<code>navController.setGraph(R.navigation.nav_host);
</code>```

Right after the Naviation.findNavController() call, and then it handled configuration changes just fine.

Body:
I'm not really sure what I'm doing wrong here. Simple setup, single activity with fragments controlled by a bottom bar inside, so far so good. The start fragment has a button inside which should navigate to another fragment.

Here's the onclicklistener for the button inside my fragment class:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    add_step_fab.setOnClickListener {
        Navigation.findNavController(view).navigate(R.id.fragmentAtoB)
    }
}

Here's my action in the navigation.xml:

<fragment android:id="@+id/navigation_main" android:name="com.test.test.fragments.AFragment"
          android:label="Fragment A" tools:layout="@layout/fragment_a">
    <action android:id="@+id/fragmentAtoB"
            app:destination="@id/fragmentB" app:enterAnim="@anim/nav_default_enter_anim"
            app:exitAnim="@anim/nav_default_exit_anim" app:popEnterAnim="@anim/nav_default_pop_enter_anim"
            app:popExitAnim="@anim/nav_default_pop_exit_anim"/>
</fragment>

The navigation works, but I get the standard

java.lang.IllegalArgumentException: navigation destination com.test.test:id/fragmentAtoB is unknown to this NavController

error when I click on the button after rotating my screen, split screening the app, or sometimes seemingly randomly. Looks like it has something to do with the configuration change?

EDIT:
I also tried using

val clickListener: View.OnClickListener = Navigation.createNavigateOnClickListener(R.id.fragmentAtoB)
    add_step_fab.setOnClickListener(clickListener)

with the same issue as above.

Checking if i'm actually in the same fragment, as some suggested for users who are having the same exception (but for unrelated reasons), such as:

if (controller.currentDestination?.id == R.id.navigation_main) {
            controller.navigate(R.id.fragmentAtoB)
        }

also didn't help.

Body:
I also experienced this recently after months of an app working correctly. I originally had added navigation to an app that was utilizing a "MainActivity" class and then had other activities that would be launched from a menu (as opposed to having the Navigation component navigate between fragments off of a single Activity).

So the app is organized such that the MainActivity is the "hub", and choices from menu options cause other activities to be launched, and when the user returns from them they are back at the MainActivity - so a pure "hub (MainActivity) and spoke (5 other activities)" model.

Within MainActivity.onCreate() is called a setupNavigation() method which originally looked like:

private void setupNavigation() {
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    drawerLayout = findViewById(R.id.drawer_layout);

    // This class implements the listener interface for the NavigationView, handler is below.
    NavigationView navigationView = findViewById(R.id.nav_view);
    navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout);
    NavigationUI.setupWithNavController(navigationView, navController);

    // MainActivity implements the listener for navigation events
    navigationView.setNavigationItemSelectedListener(this);

}

As I mentioned, this was working just fine even with configuration changes until recently. Even just changing the configuration from portrait to landscape on the MainActivity would cause an exception:

ComponentInfo{com.reddragon.intouch/com.reddragon.intouch.ui.MainActivity}: java.lang.IllegalStateException: You must call setGraph() before calling getGraph()

I found I had to add this line:

navController.setGraph(R.navigation.nav_host);

Right after the Naviation.findNavController() call, and then it handled configuration changes just fine.


问:
Why the value of "count" is showig 1 instead of 2?
In my below code I was trying to find the number of words that are in between "-", so I used string.Equals(), but it is not working. And just incrementing the value of "count" in the print section.</p>

```<code>static void Main()
{
    int count=0, i;
    string inputString = "Anupam-Datta";
    Console.WriteLine(inputString.Length);
    for(i = 0; i < inputString.Length; i++)
    {
        if(inputString[i].Equals("-"))
            count++;
    }
    Console.WriteLine("Number of words: {0}", ++count);
}
</code>```

答:
In order to check a single character - that is what inputString[i] actually returns - you have to compare it to another char, not to a string.

Ths use the follwoing instead:

```<code>Console.WriteLine(inputString.Length);
for(i=0; i<inputString.Length; i++){
    if(inputString[i] == '-')
        count++;
}
Console.WriteLine("Number of words: {0}", count++);
</code>```

Alternativly this smart one-liner:

```<code>var count = inputString.Count(x => x == '-') + 1;
</code>```

Body:
In my below code I was trying to find the number of words that are in between "-", so I used string.Equals(), but it is not working. And just incrementing the value of "count" in the print section.

static void Main()
{
    int count=0, i;
    string inputString = "Anupam-Datta";
    Console.WriteLine(inputString.Length);
    for(i = 0; i < inputString.Length; i++)
    {
        if(inputString[i].Equals("-"))
            count++;
    }
    Console.WriteLine("Number of words: {0}", ++count);
}

Body:
In order to check a single character - that is what inputString[i] actually returns - you have to compare it to another char, not to a string.

Ths use the follwoing instead:

Console.WriteLine(inputString.Length);
for(i=0; i<inputString.Length; i++){
    if(inputString[i] == '-')
        count++;
}
Console.WriteLine("Number of words: {0}", count++);

Alternativly this smart one-liner:

var count = inputString.Count(x => x == '-') + 1;


问:
Comparing strings in a loop using Is Operator
Is Operator works fine when comparing two strings like:

```<code>Dim str1 As String = "TagnameX"
Dim str2 As String = "TagnameX"

Dim strChk as boolean = str1 Is str2
'strChk returns True

</code>```

But when one of the strings is extracted by Substring it returns false ! as below:

```<code>Dim str1 As String = "t#1TagnameX"
Dim str1Extract As String = str1.Substring(3, 8)
Dim strArr() = {"Tagname1", "Tagname2", "TagnameX"}

 For i = 0 To strArr.Length - 1
      If strArr(i) Is str1Extract Then
         MsgBox("TagnameX found!")
      else
         MsgBox("TagnameX was not found!")
      End If
 Next
'TagnameX was not found!
</code>```

so am i using it wrong in some how? thanks for your help! :)

答:
The Is-operator returns whether two references are equal: that is, whether the two variables refer to the same location in memory.

The first code snippet returns True because for literal strings, .NET interns duplicates rather than keeping separate identical copies in memory, so str1 and str2 refer to the same string in memory.

The second code snippet returns False because .NET does not necessarily intern intermediate strings, such as strings returned by Substring. So the variables str and strExtract do not refer to the same string.

You should use the equals operator = to compare the value of two strings.

Body:
Is Operator works fine when comparing two strings like:

Dim str1 As String = "TagnameX"
Dim str2 As String = "TagnameX"

Dim strChk as boolean = str1 Is str2
'strChk returns True

But when one of the strings is extracted by Substring it returns false ! as below:

Dim str1 As String = "t#1TagnameX"
Dim str1Extract As String = str1.Substring(3, 8)
Dim strArr() = {"Tagname1", "Tagname2", "TagnameX"}

 For i = 0 To strArr.Length - 1
      If strArr(i) Is str1Extract Then
         MsgBox("TagnameX found!")
      else
         MsgBox("TagnameX was not found!")
      End If
 Next
'TagnameX was not found!

so am i using it wrong in some how? thanks for your help! :)


问:
Does Cube.js support preAggregations when using Context Variables inside the SQL definition of a cube?
According to the Cube.js documentation, one can define cubes using something called Context Variables, that allows the injection of filters (such as a particular user email) when querying that cube.
I haven't tried it yet, but I want to know if this feature is compatible with preaggregations, and also if it handles empty filter cases.

For example, if I define this cube (same as the example from the docs):

    cube(`OrderFacts`, {
      sql: `SELECT * FROM orders WHERE ${FILTER_PARAMS.OrderFacts.date.filter('date')}`,

      measures: {
        count: {
          type: `count`
        }
      },

      dimensions: {
        date: {
          sql: `date`,
          type: `time`
        }
      }
    });
```

<p>will I be able to define a preAggregation such as this?</p>

<pre class="lang-js prettyprint-override"><code>  preAggregations: {
    date: {
      type: `rollup`,
      measureReferences: [someMeasure],
      dimensionReferences: [someDimension],
      timeDimensionReference: date,
      granularity: `month`
    }
  }
</code>```

and can I perform queries without a date dimension filter? (so the sql would end as SELECT * FROM orders WHERE;) ?

To sum up: is there a way of injecting filters to a cube's sql definition dynamically, but not at query time and instead at schema compile time?

I ask this because we are currently extending some cubes with information retrieved from our API, and we were overwriting the segment field from this cubes, but due to performance issues we would prefer to overwrite the cube's sql field (to filter unnecessary data from the start).

NOTE: We are using asyncModule to perform the queries to our API. We also need to build different cubes (for all our clients) referencing a common table, but with a dynamic SQL that will change depending on the client.

Our desired output should be (for an Orders table and F1, ..., Fn client filters from our API):

N cubes that extend a base Orders cube: OrdersC1, OrdersC2, ..., OrdersCn.

Each OrdersCi cube with a modified version of the base Orders sql, containing its Fi filter.

Each OrdersCi cube with the same dimensions, measures and preAggregations definitions, inherited from the base Orders cube.

We managed to implement all that I said before, but instead of modifying the sql field, we overwrote the segments field.

答:
In general only partitioned rollups pass FILTER_PARAMS for partitioned time dimensions.
All other pre-aggregations doesn't allow passing context variables.
There're two approaches you can use to leverage pre-aggregations in multi-tenant environments.

Override sql for each customer cube such as OrdersC1, OrdersC2, etc. In this case all pre-aggregations defined in base Orders cube will be inherited. Each customer cube will have it's own set of pre-aggregations. It means if there're N customers and M pre-aggregations then N * M pre-aggregation tables should be built which can be costly in some scenarios.

cube(`Orders`, {
  sql: `SELECT * FROM orders`,

  preAggregations: {
    date: {
      type: `rollup`,
      measureReferences: [someMeasure],
      dimensionReferences: [someDimension],
      timeDimensionReference: date,
      granularity: `month`
    },
    // ...
  }
});

cube(`OrdersC1`, {
  extends: Orders,
  sql: `SELECT * FROM orders WHERE customer_id = 'C1'`,
});
```

<ol start="2">
<li>Use tenant field as a dimension of rollup. Every segment can be converted to dimension which provides an opportunity to use single rollup table for all customers. To route requests to right tenant data queryTransformer can be used.</li>
</ol>

<pre class="lang-js prettyprint-override"><code>cube(`Orders`, {
  sql: `SELECT * FROM orders`,

  // ...

  dimensions: {
    // ...

    customerId: {
      sql: `customer_id`,
      type: `string`
    }
  },

  preAggregations: {
    date: {
      type: `rollup`,
      measureReferences: [someMeasure],
      dimensionReferences: [customerId, someDimension],
      timeDimensionReference: date,
      granularity: `month`
    },

    // ...
  }
});
</code>```

Body:
According to the Cube.js documentation, one can define cubes using something called Context Variables, that allows the injection of filters (such as a particular user email) when querying that cube.
I haven't tried it yet, but I want to know if this feature is compatible with preaggregations, and also if it handles empty filter cases.

For example, if I define this cube (same as the example from the docs):

    cube(`OrderFacts`, {
      sql: `SELECT * FROM orders WHERE ${FILTER_PARAMS.OrderFacts.date.filter('date')}`,

      measures: {
        count: {
          type: `count`
        }
      },

      dimensions: {
        date: {
          sql: `date`,
          type: `time`
        }
      }
    });

will I be able to define a preAggregation such as this?

  preAggregations: {
    date: {
      type: `rollup`,
      measureReferences: [someMeasure],
      dimensionReferences: [someDimension],
      timeDimensionReference: date,
      granularity: `month`
    }
  }

and can I perform queries without a date dimension filter? (so the sql would end as SELECT * FROM orders WHERE;) ?

To sum up: is there a way of injecting filters to a cube's sql definition dynamically, but not at query time and instead at schema compile time?

I ask this because we are currently extending some cubes with information retrieved from our API, and we were overwriting the segment field from this cubes, but due to performance issues we would prefer to overwrite the cube's sql field (to filter unnecessary data from the start).

NOTE: We are using asyncModule to perform the queries to our API. We also need to build different cubes (for all our clients) referencing a common table, but with a dynamic SQL that will change depending on the client.

Our desired output should be (for an Orders table and F1, ..., Fn client filters from our API):

N cubes that extend a base Orders cube: OrdersC1, OrdersC2, ..., OrdersCn.

Each OrdersCi cube with a modified version of the base Orders sql, containing its Fi filter.

Each OrdersCi cube with the same dimensions, measures and preAggregations definitions, inherited from the base Orders cube.

We managed to implement all that I said before, but instead of modifying the sql field, we overwrote the segments field.

Body:
In general only partitioned rollups pass FILTER_PARAMS for partitioned time dimensions.
All other pre-aggregations doesn't allow passing context variables.
There're two approaches you can use to leverage pre-aggregations in multi-tenant environments.

Override sql for each customer cube such as OrdersC1, OrdersC2, etc. In this case all pre-aggregations defined in base Orders cube will be inherited. Each customer cube will have it's own set of pre-aggregations. It means if there're N customers and M pre-aggregations then N * M pre-aggregation tables should be built which can be costly in some scenarios.

cube(`Orders`, {
  sql: `SELECT * FROM orders`,

  preAggregations: {
    date: {
      type: `rollup`,
      measureReferences: [someMeasure],
      dimensionReferences: [someDimension],
      timeDimensionReference: date,
      granularity: `month`
    },
    // ...
  }
});

cube(`OrdersC1`, {
  extends: Orders,
  sql: `SELECT * FROM orders WHERE customer_id = 'C1'`,
});

Use tenant field as a dimension of rollup. Every segment can be converted to dimension which provides an opportunity to use single rollup table for all customers. To route requests to right tenant data queryTransformer can be used.

cube(`Orders`, {
  sql: `SELECT * FROM orders`,

  // ...

  dimensions: {
    // ...

    customerId: {
      sql: `customer_id`,
      type: `string`
    }
  },

  preAggregations: {
    date: {
      type: `rollup`,
      measureReferences: [someMeasure],
      dimensionReferences: [customerId, someDimension],
      timeDimensionReference: date,
      granularity: `month`
    },

    // ...
  }
});


问:
Microsoft Graph APi not returning "Cancelled" Events
I am trying to get all the events in a Conference room's calendar with Microsoft graph API, given a startDateTime and endDateTime. I tried the following API's -

```<code>1. https://graph.microsoft.com/v1.0/users/{id}/events?startDateTime=2017-03-20T05:00:00.0000000&endDateTime=2017-04-06T21:00:00.0000000
2.https://graph.microsoft.com/v1.0/users/{id}/calendar/calendarView?startDateTime=2017-03-20T05:00:00.0000000&endDateTime=2017-04-06T21:00:00.0000000
</code>```

The response includes all events with isCancelled=false. How do I fetch events which were Cancelled?

&$filter=isCancelled%20eq%20true also returned empty as there are no events with isCancelled=true in response

答:
I just tried

```<code>https://graph.microsoft.com/v1.0/Users/xx/Calendar/Events/xx/instances
?startDateTime=2020-02-17&endDateTime=2020-03-01&isCancelled=true
</code>```

and what came back are all the non-cancelled events...
Ditto isCancelled=false

leaving off the &isCancelled=xx parameter returns all the events with the isCancelled attribute set to false for everything.

Body:
I am trying to get all the events in a Conference room's calendar with Microsoft graph API, given a startDateTime and endDateTime. I tried the following API's -

1. https://graph.microsoft.com/v1.0/users/{id}/events?startDateTime=2017-03-20T05:00:00.0000000&endDateTime=2017-04-06T21:00:00.0000000
2.https://graph.microsoft.com/v1.0/users/{id}/calendar/calendarView?startDateTime=2017-03-20T05:00:00.0000000&endDateTime=2017-04-06T21:00:00.0000000

The response includes all events with isCancelled=false. How do I fetch events which were Cancelled?

&$filter=isCancelled%20eq%20true also returned empty as there are no events with isCancelled=true in response

Body:
I just tried

https://graph.microsoft.com/v1.0/Users/xx/Calendar/Events/xx/instances
?startDateTime=2020-02-17&endDateTime=2020-03-01&isCancelled=true

and what came back are all the non-cancelled events...
Ditto isCancelled=false

leaving off the &isCancelled=xx parameter returns all the events with the isCancelled attribute set to false for everything.


答:
I don't think that the Is operator does what you think it does.

The Is operator determines if two object references refer to the same object. However, it does not perform value comparisons.

https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/is-operator

Instead just use = to compare string values.

```<code>If strArr(i) = str1Extract Then
</code>```

Title: Comparing strings in a loop using Is Operator

Body:
I don't think that the Is operator does what you think it does.

The Is operator determines if two object references refer to the same object. However, it does not perform value comparisons.

https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/is-operator

Instead just use = to compare string values.

If strArr(i) = str1Extract Then


问:
Calculating speed from 2 points
I know this question has been asked a lot, but not yet to my satisfaction. I am trying to use the GPS of an Android device to calculate speed. A lot of people seem to reply by saying to simply use the getSpeed() function of the Location object. From what I understand though, getSpeed() will only work on certain devices that have a speed sensor built into the GPS receiver chip. I want my application to work regardless of this, so I am using the following haversine formula:

```<code>private double CalculateHaversineMI(double lat1, double long1, double lat2,double long2) {
    double dlong = (long2 - long1) * (Math.PI / 180.0f);
    double dlat = (lat2 - lat1) * (Math.PI / 180.0f);
    double a = Math.pow(Math.sin(dlat / 2.0), 2)
        + Math.cos(lat1 * (Math.PI / 180.0f))
        * Math.cos(lat2 * (Math.PI / 180.0f))
        * Math.pow(Math.sin(dlong / 2.0), 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double d = 3956 * c;

    return d;
}
</code>```

Now what I'm trying to do is figure out how to calculate speed from this. Can anyone help me please?

答:
That calculates the distance. Now as you may recall, speed = distance / time, so somewhere along the line you need to capture the time as well as the position.

On another note, the formula that you are using is way OTT for what you are trying to do. You would be better off making a number of approximations based on the fact that the path you are traversing is much less than the circumference of the earth. Then you could arrive at a much simpler formula.

Title: Calculating speed from 2 points

Body:
I know this question has been asked a lot, but not yet to my satisfaction. I am trying to use the GPS of an Android device to calculate speed. A lot of people seem to reply by saying to simply use the getSpeed() function of the Location object. From what I understand though, getSpeed() will only work on certain devices that have a speed sensor built into the GPS receiver chip. I want my application to work regardless of this, so I am using the following haversine formula:

private double CalculateHaversineMI(double lat1, double long1, double lat2,double long2) {
    double dlong = (long2 - long1) * (Math.PI / 180.0f);
    double dlat = (lat2 - lat1) * (Math.PI / 180.0f);
    double a = Math.pow(Math.sin(dlat / 2.0), 2)
        + Math.cos(lat1 * (Math.PI / 180.0f))
        * Math.cos(lat2 * (Math.PI / 180.0f))
        * Math.pow(Math.sin(dlong / 2.0), 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double d = 3956 * c;

    return d;
}

Now what I'm trying to do is figure out how to calculate speed from this. Can anyone help me please?


问:
random forest - "perfect" confusion matrix
I have a classification problem in which I would like to identify prospective borrowers which should not be invited for a meeting at a bank.
In the data, ca. 25% of the borrowers should not be invited.
I have around 4500 observations and 86 features (many dummies).

After cleaning the data, I do:

```<code># Separate X_train and Y_train

X = ratings_prepared[:, :-1]
y= ratings_prepared[:,-1]

##################################################################################

# Separate test and train (stratified, 20% test)

import numpy as np
from sklearn.model_selection import StratifiedKFold

from sklearn.base import clone

skfolds = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

for train_index, test_index in skfolds.split(X,y):
    X_train = X[train_index]
    y_train = y[train_index]
    X_test = X[test_index]
    y_test = y[test_index]
</code>```

Then, I proceed to the training the models. A SGD classifier does not work very well:

```<code>def plot_roc_curve(fpr, tpr, label=None):
    plt.plot(fpr, tpr, linewidth=2, label =label)
    plt.plot([0,1], [0,1],'k--')
    plt.axis([0,1,0,1])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')

def plot_precision_recall_vs_threshold(precisions, recalls, thresholds):
    plt.plot(thresholds, precisions[:-1],"b--", label="Precision")
    plt.plot(thresholds, recalls[:-1], "g-", label="Recall")
    plt.xlabel("Threashold")
    plt.legend(loc="center left")
    plt.ylim([0,1])

############################# Train Models #############################

from sklearn.linear_model import SGDClassifier

sgd_clf =SGDClassifier(random_state=42)
sgd_clf.fit(X_train,y_train)
y_pred = sgd_clf.predict(X_train)

# f1 score

f1_score(y_train, y_pred)

# confusion matrix

tn, fp, fn, tp = confusion_matrix(y_train, y_pred).ravel()
(tn, fp, fn, tp)
from sklearn.metrics import plot_confusion_matrix
import matplotlib.pyplot as plt

disp = plot_confusion_matrix(sgd_clf, X_train, y_train,
                                 cmap=plt.cm.Blues,
                                 normalize='true')

# recall and precision

from sklearn.metrics import precision_score, recall_score
precision_score(y_train, y_pred)

# Precision Recall

from sklearn.metrics import precision_recall_curve

plot_precision_recall_vs_threshold(precisions, recalls, thresholds)
plt.show()

# Plot ROC curve
y_scores = cross_val_predict(sgd_clf, X_train, y_train, cv=3, method="decision_function")
fpr, tpr, thresholds = roc_curve(y_train, y_scores)

plot_roc_curve(fpr, tpr)
plt.show()

# recall and precision

from sklearn.metrics import precision_score, recall_score
precision_score(y_train, y_pred)
### Precision score: 0.5084427767354597
</code>```

I then move on to a random forest classifier, which should improve upon the SGD

```<code>from sklearn.ensemble import RandomForestClassifier

forest_clf = RandomForestClassifier(random_state=42)
y_probas_forest = cross_val_predict(forest_clf, X_train, y_train, cv=3, method='predict_proba')
y_scores_forest = y_probas_forest[:,1]
fpr_forest, tpr_forest, threshold_forest = roc_curve(y_train,y_scores_forest)

plt.plot(fpr, tpr, "b:", label="SGD")
plot_roc_curve(fpr_forest, tpr_forest, "Random Forest")
plt.legend(loc="lower right")
plt.show()
</code>```

Indeed the ROC curve looks better:

But the confusion matrix and the precision score are extremely weird:

```<code>from sklearn.ensemble import RandomForestClassifier

forest_clf = RandomForestClassifier(random_state=42)
y_probas_forest = cross_val_predict(forest_clf, X_train, y_train, cv=3, method='predict_proba')
y_scores_forest = y_probas_forest[:,1]
fpr_forest, tpr_forest, threshold_forest = roc_curve(y_train,y_scores_forest)

forest_clf.fit(X_train,y_train)
y_pred = forest_clf.predict(X_train)

# f1 score

f1_score(y_train, y_pred)

# confusion matrix

from sklearn.metrics import plot_confusion_matrix
import matplotlib.pyplot as plt

disp = plot_confusion_matrix(forest_clf, X_train, y_train,
                                 cmap=plt.cm.Blues,
                                 normalize='true')
</code>```

The F score is also 1. I do not understand what is going on here. I suspect I made a mistake, but the fact that the SGD classifier seems to work ok makes me think this is not about data cleaning.

Any idea of what might be going wrong?

#

UPDATE:

1) Confusion Matrix in absolute terms:

2) Reducing the threshold:

答:
The reason you have perfect score is because you are not doing your metrics on test data.

In the first paragraph, you're doing the 80/20 split for training and test data, but then all the metrics ROCs, confusion matrices etc. are done on the original training data instead on test data.

With setup like that, your reports would show you you're overfitting like crazy.

What you should do is to apply the trained model on your test data and look how that model does.

Body:
I have a classification problem in which I would like to identify prospective borrowers which should not be invited for a meeting at a bank.
In the data, ca. 25% of the borrowers should not be invited.
I have around 4500 observations and 86 features (many dummies).

After cleaning the data, I do:

# Separate X_train and Y_train

X = ratings_prepared[:, :-1]
y= ratings_prepared[:,-1]

##################################################################################

# Separate test and train (stratified, 20% test)

import numpy as np
from sklearn.model_selection import StratifiedKFold

from sklearn.base import clone

skfolds = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

for train_index, test_index in skfolds.split(X,y):
    X_train = X[train_index]
    y_train = y[train_index]
    X_test = X[test_index]
    y_test = y[test_index]

Then, I proceed to the training the models. A SGD classifier does not work very well:

def plot_roc_curve(fpr, tpr, label=None):
    plt.plot(fpr, tpr, linewidth=2, label =label)
    plt.plot([0,1], [0,1],'k--')
    plt.axis([0,1,0,1])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')

def plot_precision_recall_vs_threshold(precisions, recalls, thresholds):
    plt.plot(thresholds, precisions[:-1],"b--", label="Precision")
    plt.plot(thresholds, recalls[:-1], "g-", label="Recall")
    plt.xlabel("Threashold")
    plt.legend(loc="center left")
    plt.ylim([0,1])

############################# Train Models #############################

from sklearn.linear_model import SGDClassifier

sgd_clf =SGDClassifier(random_state=42)
sgd_clf.fit(X_train,y_train)
y_pred = sgd_clf.predict(X_train)

# f1 score

f1_score(y_train, y_pred)

# confusion matrix

tn, fp, fn, tp = confusion_matrix(y_train, y_pred).ravel()
(tn, fp, fn, tp)
from sklearn.metrics import plot_confusion_matrix
import matplotlib.pyplot as plt

disp = plot_confusion_matrix(sgd_clf, X_train, y_train,
                                 cmap=plt.cm.Blues,
                                 normalize='true')

# recall and precision

from sklearn.metrics import precision_score, recall_score
precision_score(y_train, y_pred)

# Precision Recall

from sklearn.metrics import precision_recall_curve

plot_precision_recall_vs_threshold(precisions, recalls, thresholds)
plt.show()

# Plot ROC curve
y_scores = cross_val_predict(sgd_clf, X_train, y_train, cv=3, method="decision_function")
fpr, tpr, thresholds = roc_curve(y_train, y_scores)

plot_roc_curve(fpr, tpr)
plt.show()

# recall and precision

from sklearn.metrics import precision_score, recall_score
precision_score(y_train, y_pred)
### Precision score: 0.5084427767354597

I then move on to a random forest classifier, which should improve upon the SGD

from sklearn.ensemble import RandomForestClassifier

forest_clf = RandomForestClassifier(random_state=42)
y_probas_forest = cross_val_predict(forest_clf, X_train, y_train, cv=3, method='predict_proba')
y_scores_forest = y_probas_forest[:,1]
fpr_forest, tpr_forest, threshold_forest = roc_curve(y_train,y_scores_forest)

plt.plot(fpr, tpr, "b:", label="SGD")
plot_roc_curve(fpr_forest, tpr_forest, "Random Forest")
plt.legend(loc="lower right")
plt.show()

Indeed the ROC curve looks better:

But the confusion matrix and the precision score are extremely weird:

from sklearn.ensemble import RandomForestClassifier

forest_clf = RandomForestClassifier(random_state=42)
y_probas_forest = cross_val_predict(forest_clf, X_train, y_train, cv=3, method='predict_proba')
y_scores_forest = y_probas_forest[:,1]
fpr_forest, tpr_forest, threshold_forest = roc_curve(y_train,y_scores_forest)

forest_clf.fit(X_train,y_train)
y_pred = forest_clf.predict(X_train)

# f1 score

f1_score(y_train, y_pred)

# confusion matrix

from sklearn.metrics import plot_confusion_matrix
import matplotlib.pyplot as plt

disp = plot_confusion_matrix(forest_clf, X_train, y_train,
                                 cmap=plt.cm.Blues,
                                 normalize='true')

The F score is also 1. I do not understand what is going on here. I suspect I made a mistake, but the fact that the SGD classifier seems to work ok makes me think this is not about data cleaning.

Any idea of what might be going wrong?

#

UPDATE:

1) Confusion Matrix in absolute terms:

2) Reducing the threshold:


问:
React Native - Difference between onChange vs onChangeText of TextInput
I'm not sure when to use onChange vs onChangeText in a TextInput component. I know onChangeText accepts the changed text as an arg in the callback, but is that why you would use onChangeText, since you can then update state within the callback?

答:
Use it like this:

```<code><Input label='First Name' onChange={this.onChange} value={this.state.first}/>
</code>```

```<code>onChange = (event) => {
  const {eventCount, target, text} = event.nativeEvent;
  this.setState({first:text});
};
</code>```

The target attribute seems useless. It doesn't look like you can attach data attributes to react-native elements and retrieve them from the target element like you can in react because the app is not a browser.

With react, we're told it's better practice to not attach inline functions to the onChange event for performance reasons.  We're supposed to use custom props or data-* attributes on the HTML element and retrieve the information from e.target inside the onChange handler.

But with react-native it seems this format of passing data is actually acceptable:

```<code><Input
      label='First Name'
      onChangeText={text=>this.onChange('first',text,'anotherValueIWantToPass')}
      value={this.state.first}/>
</code>```

Body:
Use it like this:

<Input label='First Name' onChange={this.onChange} value={this.state.first}/>

onChange = (event) => {
  const {eventCount, target, text} = event.nativeEvent;
  this.setState({first:text});
};

The target attribute seems useless. It doesn't look like you can attach data attributes to react-native elements and retrieve them from the target element like you can in react because the app is not a browser.

With react, we're told it's better practice to not attach inline functions to the onChange event for performance reasons.  We're supposed to use custom props or data-* attributes on the HTML element and retrieve the information from e.target inside the onChange handler.

But with react-native it seems this format of passing data is actually acceptable:

<Input
      label='First Name'
      onChangeText={text=>this.onChange('first',text,'anotherValueIWantToPass')}
      value={this.state.first}/>


问:
Can't kill Go Server
I tried to search for solution for this problem for hours but couldn't find it.

Problem: After I start a golang server by typing "go run server.go" then after Im done with it  I press Ctrl + C but the server is still up (I can still connect to server through reactjs frontend). Whats going on?

I even tried to kill terminal from VSCode but still it work as desired.

How to manually kill this server from terminal?

Mac OS Catalina

答:
This depends on your OS.  If you're running Windows, you can go into the windows process manager and find the process that's running your server.go and kill it manually.

If you're on MacOS or Linux, you should be able to handle this with a terminal:

Open another terminal and execute ps aux | grep server.go

Find the associated process ID (pid) with your server.go process (it should be the number listed second in the response from step 1)

Run a kill -9 PID where PID is the process ID you found in step 2.

Title: Can't kill Go Server


问:
Classic Asp cookie expires date does not always get set
I am trying to set cookie with addheader -method in Classic Asp which is the only way of adding among other things HttpOnly and Secure -flags to cookies. All work with the below code - but there is one exception and its is the expiration date/time.

```<code><%
Response.AddHeader "Set-Cookie", "testCookie=2000; path=/;HttpOnly;Secure;expires=" & dateAdd("d", 365, Now()) & ";samesite=Strict;HostOnly"
%>
</code>```

However, it seems to be browser-related issue. In firefox I can see in the Storage tab of developer tools that expiration time is set. But in Chrome it always stays as the default which is the expiration with the end of session. This same issue is with the Edge too.

Has anyone any experience with this issue?

答:
In addition to the accepted solution of Kul-Tigin I want to add also a vbscript solution for those who are missing that too.</p>

```<code><%
Response.AddHeader "Set-Cookie", "testCookie=2000; path=/;HttpOnly;Secure;expires=" & (New UTC).toUTCString(500,"d") & ";samesite=Strict;HostOnly;"

Class UTC

    Public Function toUTCString(ByVal offSet, ByVal offsetType)
        ' ***********************************
        ' Converts vbScript datetime format to
        ' Universal datetime string format:
        ' Tue, 16 Feb 2021 13:39:24 GMT
        '************************************

        Dim dt: dt = dateAdd(offsetType, offSet, UTCDate(Now()))
        Dim tdParts: tdParts = Split(dt, " ")
        Dim tPart: tPart = CDate(tdParts(1) & " " & tdParts(2))
        Dim dPart: dPart = CDate(tdParts(0))

        Dim timeTo24: timeTo24 = _
        Right("0" & Hour(tPart), 2) & ":" & _
        Right("0" & Minute(tPart), 2) & ":" & _
        Right("0" & Second(tPart), 2)

        toUTCString = WeekdayName(Weekday(dPart), True) & ", " & _
                      Day(dPart) & " " & _
                      MonthName(Month(dPart), True) & " " & _
                      Year(dPart) & " " & _
                      timeTo24 & " GMT"

    End Function

    Public Function UTCDate(ByVal dtDate)
        If Not IsDate(dtDate) Then Err.Raise 5
        dtDate = CDate(dtDate)
        Dim ZoneBias: ZoneBias = TimeZoneBias()
        If IsPDT(Now) <> IsPDT(dtDate) Then
            ZoneBias = ZoneBias - 60
        End If
        UTCDate = DateAdd("n", ZoneBias, dtDate)
    End Function

    Private Function IsPDT(ByVal dtDate)
        If Not IsDate(dtDate) Then Err.Raise 5
        dtDate = CDate(dtDate)
        Dim pdtLow, pdtUpr, nDaysBack

        pdtLow = DateSerial(Year(dtDate),  3, 31)
        pdtUpr = DateSerial(Year(dtDate), 10, 31)
        pdtLow = DateAdd("h", 2, pdtLow)
        pdtUpr = DateAdd("h", 2, pdtUpr)

        nDaysBack = Weekday(pdtLow) - 1
        If nDaysBack <> 0 Then
            pdtLow = DateAdd("d", -nDaysBack, pdtLow)
        End If

        nDaysBack = Weekday(pdtUpr) - 1
        If nDaysBack <> 0 Then
            pdtUpr = DateAdd("d", -nDaysBack, pdtUpr)
        End If

        IsPDT = (dtDate >= pdtLow And dtDate <= pdtUpr)
    End Function

    Private Function TimeZoneBias()
        Dim LTZone
        With GetObject("winmgmts:" & _
                "{impersonationLevel=impersonate}!\\.\root\cimv2")
            For Each LTZone In .ExecQuery(_
                    "Select * From Win32_ComputerSystem")
                TimeZoneBias = LTZone.CurrentTimeZone
            Next
        End With
        TimeZoneBias = TimeZoneBias * -1
    End Function

End Class

%>
</code>```

Body:
I am trying to set cookie with addheader -method in Classic Asp which is the only way of adding among other things HttpOnly and Secure -flags to cookies. All work with the below code - but there is one exception and its is the expiration date/time.

<%
Response.AddHeader "Set-Cookie", "testCookie=2000; path=/;HttpOnly;Secure;expires=" & dateAdd("d", 365, Now()) & ";samesite=Strict;HostOnly"
%>

However, it seems to be browser-related issue. In firefox I can see in the Storage tab of developer tools that expiration time is set. But in Chrome it always stays as the default which is the expiration with the end of session. This same issue is with the Edge too.

Has anyone any experience with this issue?

Body:
In addition to the accepted solution of Kul-Tigin I want to add also a vbscript solution for those who are missing that too.

<%
Response.AddHeader "Set-Cookie", "testCookie=2000; path=/;HttpOnly;Secure;expires=" & (New UTC).toUTCString(500,"d") & ";samesite=Strict;HostOnly;"

Class UTC

    Public Function toUTCString(ByVal offSet, ByVal offsetType)
        ' ***********************************
        ' Converts vbScript datetime format to
        ' Universal datetime string format:
        ' Tue, 16 Feb 2021 13:39:24 GMT
        '************************************

        Dim dt: dt = dateAdd(offsetType, offSet, UTCDate(Now()))
        Dim tdParts: tdParts = Split(dt, " ")
        Dim tPart: tPart = CDate(tdParts(1) & " " & tdParts(2))
        Dim dPart: dPart = CDate(tdParts(0))

        Dim timeTo24: timeTo24 = _
        Right("0" & Hour(tPart), 2) & ":" & _
        Right("0" & Minute(tPart), 2) & ":" & _
        Right("0" & Second(tPart), 2)

        toUTCString = WeekdayName(Weekday(dPart), True) & ", " & _
                      Day(dPart) & " " & _
                      MonthName(Month(dPart), True) & " " & _
                      Year(dPart) & " " & _
                      timeTo24 & " GMT"

    End Function

    Public Function UTCDate(ByVal dtDate)
        If Not IsDate(dtDate) Then Err.Raise 5
        dtDate = CDate(dtDate)
        Dim ZoneBias: ZoneBias = TimeZoneBias()
        If IsPDT(Now) <> IsPDT(dtDate) Then
            ZoneBias = ZoneBias - 60
        End If
        UTCDate = DateAdd("n", ZoneBias, dtDate)
    End Function

    Private Function IsPDT(ByVal dtDate)
        If Not IsDate(dtDate) Then Err.Raise 5
        dtDate = CDate(dtDate)
        Dim pdtLow, pdtUpr, nDaysBack

        pdtLow = DateSerial(Year(dtDate),  3, 31)
        pdtUpr = DateSerial(Year(dtDate), 10, 31)
        pdtLow = DateAdd("h", 2, pdtLow)
        pdtUpr = DateAdd("h", 2, pdtUpr)

        nDaysBack = Weekday(pdtLow) - 1
        If nDaysBack <> 0 Then
            pdtLow = DateAdd("d", -nDaysBack, pdtLow)
        End If

        nDaysBack = Weekday(pdtUpr) - 1
        If nDaysBack <> 0 Then
            pdtUpr = DateAdd("d", -nDaysBack, pdtUpr)
        End If

        IsPDT = (dtDate >= pdtLow And dtDate <= pdtUpr)
    End Function

    Private Function TimeZoneBias()
        Dim LTZone
        With GetObject("winmgmts:" & _
                "{impersonationLevel=impersonate}!\\.\root\cimv2")
            For Each LTZone In .ExecQuery(_
                    "Select * From Win32_ComputerSystem")
                TimeZoneBias = LTZone.CurrentTimeZone
            Next
        End With
        TimeZoneBias = TimeZoneBias * -1
    End Function

End Class

%>