问:
SQL Server: What are batching statements (i.e. using "GO") good for?
I know that in SQL Server GO is considered a batch separator.

My question is: What is the point of having a batch separator? What benefit does it give you and why would you want to use it?

Example: I've often seen it used in SQL code as follows and I can't see why it would be considered a best practice. As far as I can tell the code would the same without all the GO statements:

```<code>USE AdventureWorks2012;
GO
BEGIN TRANSACTION;
GO
IF @@TRANCOUNT = 0
BEGIN
    SELECT FirstName, MiddleName
    FROM Person.Person WHERE LastName = 'Adams';
    ROLLBACK TRANSACTION;
    PRINT N'Rolling back the transaction two times would cause an error.';
END;
ROLLBACK TRANSACTION;
PRINT N'Rolled back the transaction.';
GO
</code>```

(source: technet documentation):

答:
What is the point of having a batch separator?

Having read many of the answers, and contributed to comments, here is what I think.

The real question is "What is the point of having a batch?"

There are 2 implications of batching that have some meaning, and there is an additional usage of go that can be useful:

1. All statements in a batch are compiled into a single execution plan

How this impacts you, as a SQL developer, I don't know. But there it is. The implication of this is that you can't have some statements within the same batch. For example, you cannot ALTER a table to add a column, then select that column in the same batch - because while compiling the execution plan, that column does not exist for selecting.

I think there is an open argument as to whether SQL Server should be able to detect this by itself without requiring developers to include go statements in their scripts. Further, the docs say ODBC connections may never issue a go command. It is not clear to me how a script run through ODBC would behave if it included the ALTER / SELECT example just given.

2. Locally declared variables exist only within the scope of the batch in which they were declared

These two points combined kind of suck. I have a script that creates and alters DB structures (tables, procedures, etc) and I want to declare variables at the start of the script that will be used to govern the behaviour of the script overall. As soon as I need to wrap up a batch (due to, say, an ALTER statement - see my point 1, above), those "config" variables fall out of scope and can't be used further down the script. My workaround is to create a table, persist the config variables into the table, then read from that table all the way through my script, then drop the table at the end (in case anyone else is facing this).

This second implication can actually be used to advantage - if your script is doing a lot of work and you simply want to clear out all your local variables, you can simply include a GO statement and then declare new variables (ie. and re-use the same names, if that's what you want).

3. GO has an optional parameter (named "count") which tells the server to repeat the batch actions multiple times

This usage seems to be nice additional functionality added on to the GO statement. I believe the initial or primary function of GO relates more to the compilation of a single execution plan, as mentioned in point 1 - otherwise the keyword may as well be something like REPEAT 10 - but repeat what? The batch. Without GO signifying a batch, a repeat command could only ever repeat the prior single statement. Therefore GO is a nice way to repeat batches.

Reference

All of this comes from trying to understand the MS documentation on GO. Many of the other answers - here, and on other questions - pick at pieces of the documentation but I think the documentation itself fails to really explain why there is a benefit to batching in the first place - hence my contribution to an already well-commented question.

Addendum

After writing the above, I did find the Rules for Using Batches mentioned by Microsoft in the GO documentation. The linked page explains that an execution plan consists of multiple statements. It also says that individual statements can be re-compiled into a new execution plan (ie by SQL Server, while processing the batch, automatically). So for example, following a statement to CREATE TABLE you might have an INSERT into that table. That INSERT statement will be recompiled after the table has been created in the prior statement.

This re-enforces the idea that SQL Server probably could detect those scenarios where an ALTER to a table is followed by a SELECT and that it needs to re-compile the SELECT (see my point 1 above), and possibly this is exactly what happens if using ODBC (see point 1 above).

None of this new information alters the 3 points given above. The link I just gave contains additional reading and ends with "the rules", which are these:

CREATE DEFAULT, CREATE FUNCTION, CREATE PROCEDURE, CREATE RULE, CREATE SCHEMA, CREATE TRIGGER, and CREATE VIEW statements cannot be combined with other statements in a batch. The CREATE statement must start the batch. All other statements that follow in that batch will be interpreted as part of the definition of the first CREATE statement.

A table cannot be changed and then the new columns referenced in the same batch.

If an EXECUTE statement is the first statement in a batch, the EXECUTE keyword is not required. The EXECUTE keyword is required if the EXECUTE statement is not the first statement in the batch.

Body:
I know that in SQL Server GO is considered a batch separator.

My question is: What is the point of having a batch separator? What benefit does it give you and why would you want to use it?

Example: I've often seen it used in SQL code as follows and I can't see why it would be considered a best practice. As far as I can tell the code would the same without all the GO statements:

USE AdventureWorks2012;
GO
BEGIN TRANSACTION;
GO
IF @@TRANCOUNT = 0
BEGIN
    SELECT FirstName, MiddleName
    FROM Person.Person WHERE LastName = 'Adams';
    ROLLBACK TRANSACTION;
    PRINT N'Rolling back the transaction two times would cause an error.';
END;
ROLLBACK TRANSACTION;
PRINT N'Rolled back the transaction.';
GO

(source: technet documentation):


来源: stackexchange

问:
how does compareTo and compare work?
I know that compare and compareTo returns an int value.

For example:

```<code>Returns
0 if a equal b
-1 if a < b
+1 if a > b
</code>```

sort method makes a call to either compareTo or compare() methods. But how does sort method arranges the list when compare or compareTo returns a int value. What is background scenario running after a compare or compareTo returns an int value to sort?how does sort method makes use of int values(-1 or 0 or 1) returned to it from compare and compareTo

答:
Hopefully, these implementations of compare() method would help you understand it better.

```<code>public int compare(Object obj1, Object obj2)
{
 Integer I1 = (Integer)obj1; // typecasting object type into integer type
 Integer I2 = (Integer)obj2; // same as above ..
 // 1.
 return I1.compareTo(I2); // ascending order [0, 5, 10, 15, 20]
 // 2.
 return -I1.compareTo(I2); // descending order [20, 15, 10, 5, 0]
 // 3.
 return I2.compareTo(I1); // descending order [20, 15, 10, 5, 0]
 // 4.
 return -I2.compareTo(I1); // ascending order [0, 5, 10, 15, 20]
 // 5.
 return +1; // insertion order [10, 0, 15, 5, 20, 20]
 // 6.
 return -1; // reverse of insertion order [20, 20, 5, 15, 0, 10]
 // 7.
 return 0; // only first element [10]
}
</code>```

How compare() method works in Java

ContentLicense: CC BY-SA 3.0

Title: how does compareTo and compare work?

Body:
I know that compare and compareTo returns an int value.

For example:

Returns
0 if a equal b
-1 if a  b

sort method makes a call to either compareTo or compare() methods. But how does sort method arranges the list when compare or compareTo returns a int value. What is background scenario running after a compare or compareTo returns an int value to sort?how does sort method makes use of int values(-1 or 0 or 1) returned to it from compare and compareTo

Body:
Hopefully, these implementations of compare() method would help you understand it better.

public int compare(Object obj1, Object obj2)
{
 Integer I1 = (Integer)obj1; // typecasting object type into integer type
 Integer I2 = (Integer)obj2; // same as above ..
 // 1.
 return I1.compareTo(I2); // ascending order [0, 5, 10, 15, 20]
 // 2.
 return -I1.compareTo(I2); // descending order [20, 15, 10, 5, 0]
 // 3.
 return I2.compareTo(I1); // descending order [20, 15, 10, 5, 0]
 // 4.
 return -I2.compareTo(I1); // ascending order [0, 5, 10, 15, 20]
 // 5.
 return +1; // insertion order [10, 0, 15, 5, 20, 20]
 // 6.
 return -1; // reverse of insertion order [20, 20, 5, 15, 0, 10]
 // 7.
 return 0; // only first element [10]
}

How compare() method works in Java

ContentLicense: CC BY-SA 4.0


问:
Will a git interactive rebase that deletes a commit truly remove exposure of API keys / secrets / passwords?
Its important to NOT store passwords and secrets in code repos.

Sometimes we hard code an API password while we are developing an application.  We remove it, often by turning it into an environmental variable that we set with export (Unix).  Obviously a better practice would be to use environmental variables from the start.

But what happens in the case where we are not that careful and we COMMIT that change that has the password exposed.

The first step is to quickly remove them and commit and push that change.

OK

But...

The password is still in the git history so anyone who has access to the git repository can get the pw.  Not good.

But...

We then do a git interactive rebase and delete (not squash) the offending commit = the one with the password added in history.

Will that fix the problem and ensure the password is no longer available in any way in git?

How will this affect the code when I pull this commit out.  If there is other code than the line(s) with the password(s) presumably I will need to redo those changes which would be lost.  If the commit is many ago I could imagine problems if any commit since has also changed the same line.  Hopefully not.

答:
There are lots of answers about how to remove sensitive commits, e.g., Remove sensitive files and their commits from Git history.  Any good answer warns you that it's probably too late anyway, which is true.  Not too many go into details about when and why it is too late, but the answer is pretty straightforward: it's not not a lot of use.  The rest of this answer is about when and why it's too late, and why just deleting the commit with an interactive rebase is not sufficient.

The heart of the problem is that commits cannot be changed, and Git is wired to add new commits.  Removing old / dead commits (and other dead objects) happens as a side effect, with little control on your part.  When you do virtually anything—no matter what: git commit --amend, git rebase -i, git reset --hard, none of this matters—any existing commit remains in your database of commits, unchanged, undisturbed, and still available by its hash ID.  Nonetheless, it is possible to remove a commit for real.  It's just hard to do it in a controlled and correct manner.

Representing and finding commits

Each commit—in fact, each object1 in Git's main database—is accessed by its hash ID.  The hash ID of the last commit in a branch is found in a second, smaller database.  Essentially, a branch name like master says: the tip commit of master is a123456..., which provides the hash ID of the commit object so that you—or Git—can go back to the main database and say: Get me object a123456....

Every commit can list the hash ID(s) of some previous, or parent, commits.  That is, having obtained object a123456..., you can then fish around inside it for the parent hash IDs.  If the (single) parent hash ID of a123456... is 9876543..., you then go back to the main database and say: *Get me object 9876543... and you have the previous commit.  That's how you—and Git—can start from end of a branch and work backwards, one commit at a time:

```<code>... <-grandparent <-parent <-last-commit   <--branchname
</code>```

If we use single uppercase letters to stand in for hash IDs, and just remember that the arrows (from child to parent) always point backwards, we get something that's easier to draw when you have multiple branches:

```<code>...--E--F--G   <-- master
         \
          H  <-- develop
</code>```

But in all cases, whenever you do something to "change" your history—for instance, if we decide commit G is bad and must be replaced—you don't actually change anything.  Instead, Git in effect just moves the bad commit out of the way:

```<code>          G
         /
...--E--F--I   <-- master
         \
          H  <-- develop
</code>```

The main object database is not cleaned out immediately, and if you have any way to remember the hash ID of commit G, you can ask Git for G by that hash ID.  Git will present it to you, because it's in the database!

This same description is true regardless of how you "delete" or "change" a commit: Git just ends up making copies of every other commit, so that the "deleted" or "changed" commit (here, G is to be deleted) is now on a different branch-line:

```<code>...--o--F--G--H--J--...   <-- branch
</code>```

becomes:

```<code>          G--H--J--...   [previous branch, now abandoned]
         /
...--o--F--H'-J'-...   <-- branch
</code>```

where H' is a copy of H adapted to come after F instead of G, J' is a copy of J adapted to come after H', and so on.  Again, G isn't really gone, it's just shoved up out of the way, along with all of its descendants.  All of its descendants are replaced by slightly-altered copies, with new, different hash IDs.

1There are four types of objects.  Commit, tree, and blob objects work together to store files in commits, with annotated tag objects making the fourth type.  Each commit refers to one tree; that tree refers to additional sub-trees if needed, and to blobs to hold the files that go with that commit.

Removing commits

So, when—and how and why—do commits eventually go away?  The answer is that Git has a maintenance command, git gc, whose job is to walk the entire main database of every object, while also walking the other database of all names by which one can find objects.  If there is no name by which we can find commit G, after an operation like the above, git gc will determine that this is the case, and—eventually—kick G out of the main database, using whatever the operating system's normal deletion functions are for deleting a file.2

More formally, for git gc to delete an object from the main database, the object must be unreachable.  For a pretty through discussion of the notion of reachability, see Think Like (a) Git.  Unfortunately for your particular use case, the set of names by which we can reach commits includes any commit in any reflog.

2Typically this is an insecure delete, so that if you have control of the underlying storage media, you can still get the data back that way, but now it's obviously that much harder.  In any case, now no one can just ask that Git repository for commit G by hash ID.  Beware of file systems that support snapshots, though: you can just wind back to a previous snapshot and recover the entire repository as it was at the time of the snapshot!

Finding commits part 2: the reflogs

There is a reflog for every branch name, such as master, plus one for HEAD.  (There are probably additional reflogs, but these are the two important ones here.)  In the example above, commit G is no longer reachable from the name master, but there are still two reflog entries, master@{1} and HEAD@{1}, both of which server to find commit G.  So git gc will not delete commit G—not yet, anyway.

The reflog entries that do find G will be deleted, eventually.  In particular, git reflog expire automatically deletes sufficiently-old and therefore expired reflog entries.  How old is sufficiently old is something you can configure, but it defaults to either 30 or 90 days,3 and in this case, to 30 days.

What this means is that by default, G will stick around until a git gc uses git reflog to delete the reflog entries, once they're sufficiently old—i.e., at least 30 days from now.  You can use git reflog (see the documentation) to delete or expire the entries for G sooner, if you want to speed that part up; or see cloning below.

Once the reflog entries are gone, so that G really is (globally) unreachable, git gc will remove it.  You can tell that this has happened because git show hash and git rev-parse hash will tell you that they have no idea what hash ID you are talking about.

Remember, too, that if your Git has contacted another Git, your Git may have given that other Git commit G.  In particular, when you run git push, you have your Git call up another Git and feed them commits.  If you've given them commit G, nothing you do in your own repository can take that back.  If you allow other users to git fetch from your repository, they may have taken a copy of G, and again, nothing you do in your own repository can take that back: you must convince them to discard the commit.

Reflogs are not copied by git clone, so another way to get rid of G, without waiting, is to clone your own repository.  What git clone does is to make a new repository, then fetch from the original repository.  The commits a fetch gets are those that are reachable from the names the source repository exposes.  So, rather than manually expiring some reflog entries and then running git gc, you can just clone your own repository.  There's a drawback here: you lose the safety net of all of your reflogs, and your own branch names become your new repository's origin/* names.4

3The choice between 30 and 90 days here depends on whether the value in the reflog is reachable from the commit to which the reference itself points.  In this case, the name master points to commit I, for instance, and it's not possible to walk back from I to G, so the value in master@{1}, which points to G, is not reachable from the value on master.  This means the expiration is gc.reflogExpireUnreachable—the one that defaults to 30 days—rather than gc.reflogExpire, which defaults to 90 days.

Note that once again, we depend on the concept of reachability through a directed graph.  This is one of the keys to understanding Git.

4You can use git clone --mirror, but that gets you a bare repository, and one with an inappropriate default fetch setting.  You can then fix those two, but if you know how to do all this, you'll probably want to use something other than --mirror anyway.

Summary

If:

you haven't shared the unwanted commits with anyone (no fetches or pushes), and

you remove all references to the commits, or wait 30 days, and then run git gc

then the commit will be truly gone, absent any sort of resurrection through file-system level snapshots.  You can feed the hash ID to git show or git rev-parse to verify that it is gone.  But if the commit might have been copied anywhere else, you no longer have any control over that.

The safe default is to assume that if the commit was visible to anyone else for any period of time, it has been copied, and the secrets that were in it, are no longer secret.

Body:
There are lots of answers about how to remove sensitive commits, e.g., Remove sensitive files and their commits from Git history.  Any good answer warns you that it's probably too late anyway, which is true.  Not too many go into details about when and why it is too late, but the answer is pretty straightforward: it's not not a lot of use.  The rest of this answer is about when and why it's too late, and why just deleting the commit with an interactive rebase is not sufficient.

The heart of the problem is that commits cannot be changed, and Git is wired to add new commits.  Removing old / dead commits (and other dead objects) happens as a side effect, with little control on your part.  When you do virtually anything—no matter what: git commit --amend, git rebase -i, git reset --hard, none of this matters—any existing commit remains in your database of commits, unchanged, undisturbed, and still available by its hash ID.  Nonetheless, it is possible to remove a commit for real.  It's just hard to do it in a controlled and correct manner.

Representing and finding commits

Each commit—in fact, each object1 in Git's main database—is accessed by its hash ID.  The hash ID of the last commit in a branch is found in a second, smaller database.  Essentially, a branch name like master says: the tip commit of master is a123456..., which provides the hash ID of the commit object so that you—or Git—can go back to the main database and say: Get me object a123456....

Every commit can list the hash ID(s) of some previous, or parent, commits.  That is, having obtained object a123456..., you can then fish around inside it for the parent hash IDs.  If the (single) parent hash ID of a123456... is 9876543..., you then go back to the main database and say: *Get me object 9876543... and you have the previous commit.  That's how you—and Git—can start from end of a branch and work backwards, one commit at a time:

... <-grandparent <-parent <-last-commit   <--branchname

If we use single uppercase letters to stand in for hash IDs, and just remember that the arrows (from child to parent) always point backwards, we get something that's easier to draw when you have multiple branches:

...--E--F--G   <-- master
         \
          H  <-- develop

But in all cases, whenever you do something to "change" your history—for instance, if we decide commit G is bad and must be replaced—you don't actually change anything.  Instead, Git in effect just moves the bad commit out of the way:

          G
         /
...--E--F--I   <-- master
         \
          H  <-- develop

The main object database is not cleaned out immediately, and if you have any way to remember the hash ID of commit G, you can ask Git for G by that hash ID.  Git will present it to you, because it's in the database!

This same description is true regardless of how you "delete" or "change" a commit: Git just ends up making copies of every other commit, so that the "deleted" or "changed" commit (here, G is to be deleted) is now on a different branch-line:

...--o--F--G--H--J--...   <-- branch

becomes:

          G--H--J--...   [previous branch, now abandoned]
         /
...--o--F--H'-J'-...   <-- branch

where H' is a copy of H adapted to come after F instead of G, J' is a copy of J adapted to come after H', and so on.  Again, G isn't really gone, it's just shoved up out of the way, along with all of its descendants.  All of its descendants are replaced by slightly-altered copies, with new, different hash IDs.

1There are four types of objects.  Commit, tree, and blob objects work together to store files in commits, with annotated tag objects making the fourth type.  Each commit refers to one tree; that tree refers to additional sub-trees if needed, and to blobs to hold the files that go with that commit.

Removing commits

So, when—and how and why—do commits eventually go away?  The answer is that Git has a maintenance command, git gc, whose job is to walk the entire main database of every object, while also walking the other database of all names by which one can find objects.  If there is no name by which we can find commit G, after an operation like the above, git gc will determine that this is the case, and—eventually—kick G out of the main database, using whatever the operating system's normal deletion functions are for deleting a file.2

More formally, for git gc to delete an object from the main database, the object must be unreachable.  For a pretty through discussion of the notion of reachability, see Think Like (a) Git.  Unfortunately for your particular use case, the set of names by which we can reach commits includes any commit in any reflog.

2Typically this is an insecure delete, so that if you have control of the underlying storage media, you can still get the data back that way, but now it's obviously that much harder.  In any case, now no one can just ask that Git repository for commit G by hash ID.  Beware of file systems that support snapshots, though: you can just wind back to a previous snapshot and recover the entire repository as it was at the time of the snapshot!

Finding commits part 2: the reflogs

There is a reflog for every branch name, such as master, plus one for HEAD.  (There are probably additional reflogs, but these are the two important ones here.)  In the example above, commit G is no longer reachable from the name master, but there are still two reflog entries, master@{1} and HEAD@{1}, both of which server to find commit G.  So git gc will not delete commit G—not yet, anyway.

The reflog entries that do find G will be deleted, eventually.  In particular, git reflog expire automatically deletes sufficiently-old and therefore expired reflog entries.  How old is sufficiently old is something you can configure, but it defaults to either 30 or 90 days,3 and in this case, to 30 days.

What this means is that by default, G will stick around until a git gc uses git reflog to delete the reflog entries, once they're sufficiently old—i.e., at least 30 days from now.  You can use git reflog (see the documentation) to delete or expire the entries for G sooner, if you want to speed that part up; or see cloning below.

Once the reflog entries are gone, so that G really is (globally) unreachable, git gc will remove it.  You can tell that this has happened because git show hash and git rev-parse hash will tell you that they have no idea what hash ID you are talking about.

Remember, too, that if your Git has contacted another Git, your Git may have given that other Git commit G.  In particular, when you run git push, you have your Git call up another Git and feed them commits.  If you've given them commit G, nothing you do in your own repository can take that back.  If you allow other users to git fetch from your repository, they may have taken a copy of G, and again, nothing you do in your own repository can take that back: you must convince them to discard the commit.

Reflogs are not copied by git clone, so another way to get rid of G, without waiting, is to clone your own repository.  What git clone does is to make a new repository, then fetch from the original repository.  The commits a fetch gets are those that are reachable from the names the source repository exposes.  So, rather than manually expiring some reflog entries and then running git gc, you can just clone your own repository.  There's a drawback here: you lose the safety net of all of your reflogs, and your own branch names become your new repository's origin/* names.4

3The choice between 30 and 90 days here depends on whether the value in the reflog is reachable from the commit to which the reference itself points.  In this case, the name master points to commit I, for instance, and it's not possible to walk back from I to G, so the value in master@{1}, which points to G, is not reachable from the value on master.  This means the expiration is gc.reflogExpireUnreachable—the one that defaults to 30 days—rather than gc.reflogExpire, which defaults to 90 days.

Note that once again, we depend on the concept of reachability through a directed graph.  This is one of the keys to understanding Git.

4You can use git clone --mirror, but that gets you a bare repository, and one with an inappropriate default fetch setting.  You can then fix those two, but if you know how to do all this, you'll probably want to use something other than --mirror anyway.

Summary

If:

you haven't shared the unwanted commits with anyone (no fetches or pushes), and

you remove all references to the commits, or wait 30 days, and then run git gc

then the commit will be truly gone, absent any sort of resurrection through file-system level snapshots.  You can feed the hash ID to git show or git rev-parse to verify that it is gone.  But if the commit might have been copied anywhere else, you no longer have any control over that.

The safe default is to assume that if the commit was visible to anyone else for any period of time, it has been copied, and the secrets that were in it, are no longer secret.


问:
How to combine data frame columns where each represents a different response value?
I have demographic survey data in which responses for variable X were recorded into 3 separate columns. col1 contains only 1, col2 only 2 and col3 contains everything else. There is no overlap of responses so when the respondent answered "1" cells for col2 and col3 in that same row are empty. I'd like to combine all 3 columns (there are 3000+ responses so doing this manually is out of the question). I should note that there are 100+ columns in this data frame and I will need to use this on other variables as well.

I attempted gather() and apply() commands without much luck.

(see this question for reference: r collapsing data from multiple columns into one)

The apply command combined EVERY column, so I'm guessing I just need to fix my parameters? Wasn't sure how to do this (a bit of a newbie here).

```<code>df$New <- apply(df, 1, function(x) paste(x, collapse = ","))
</code>```

Thanks for any help/advice!

答:
Can you use gather() %>% summarise(paste(..., collapse = ", "))? I am using the example you linked to above.

library(tidyverse)

df <-
  tibble(
    id = 1:4,
    variable_1 = c('Var1', NA, NA,'Var1'),
    variable_2 = c('Var2', 'No', NA, NA),
    variable_3 = c(NA, NA, 'Var3', NA),
    variable_4 = c(NA, 'Var4', NA, NA),
    variable_5 = c(NA, 'No', 'Var5', NA),
    variable_6 = c(NA, NA, 'Var6', NA)
  )

df %>%
  # pivot everything besides id
  gather(var, response, -id) %>%
  # optional
  filter(!is.na(response)) %>%
  # the method
  group_by(id) %>%
  summarise(sentence = paste(response, collapse = ", ")) %>%
  ungroup()

#    id sentence
#     1 Var1, Var2
#     2 No, Var4, No
#     3 Var3, Var5, Var6
#     4 Var1
```

Body:
I have demographic survey data in which responses for variable X were recorded into 3 separate columns. col1 contains only 1, col2 only 2 and col3 contains everything else. There is no overlap of responses so when the respondent answered "1" cells for col2 and col3 in that same row are empty. I'd like to combine all 3 columns (there are 3000+ responses so doing this manually is out of the question). I should note that there are 100+ columns in this data frame and I will need to use this on other variables as well.

I attempted gather() and apply() commands without much luck.

(see this question for reference: r collapsing data from multiple columns into one)

The apply command combined EVERY column, so I'm guessing I just need to fix my parameters? Wasn't sure how to do this (a bit of a newbie here).

df$New <- apply(df, 1, function(x) paste(x, collapse = ","))

Thanks for any help/advice!


问:
CMakeLists.txt - run process, then execute command
I have the following CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.0.0)
project(FlaAlgoTests)
...

include_directories("../lib")
...

add_executable(
        flamenco_algorithms_anomaly_stiction_tests
        ...
)

</code>```

The flamenco_algorithms_anomaly_stiction_tests executable generates a .xml file when it is complete.

I would like to run a process (I guess using ADD_CUSTOM_COMMAND?) after this executable is run, which converts that xml file to an html file.

How can I do this?

答:
The short answer is yes; you can use ADD_CUSTOM_COMMAND to first execute your built executable (flamenco_stiction_tests.exe), and second to run the additional process (my_additional_process.exe). Try something like this:

```<code>add_custom_command(TARGET flamenco_algorithms_anomaly_stiction_tests POST_BUILD
    COMMAND flamenco_stiction_tests.exe
    COMMAND my_additional_process.exe my_generated_file.xml
    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Debug
    COMMENT "Running built executable and additional process..."
)
</code>```

Per the CMake documentation, these will be executed in order. You may also configure a script to run after the executable is built instead, using a combination of configure_file() and add_custom_command. Guaranteeing your generated file is available for the second process may be easier and safer that way.

Body:
I have the following CMakeLists.txt:

cmake_minimum_required(VERSION 3.0.0)
project(FlaAlgoTests)
...

include_directories("../lib")
...

add_executable(
        flamenco_algorithms_anomaly_stiction_tests
        ...
)

The flamenco_algorithms_anomaly_stiction_tests executable generates a .xml file when it is complete.

I would like to run a process (I guess using ADD_CUSTOM_COMMAND?) after this executable is run, which converts that xml file to an html file.

How can I do this?

Body:
The short answer is yes; you can use ADD_CUSTOM_COMMAND to first execute your built executable (flamenco_stiction_tests.exe), and second to run the additional process (my_additional_process.exe). Try something like this:

add_custom_command(TARGET flamenco_algorithms_anomaly_stiction_tests POST_BUILD
    COMMAND flamenco_stiction_tests.exe
    COMMAND my_additional_process.exe my_generated_file.xml
    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/Debug
    COMMENT "Running built executable and additional process..."
)

Per the CMake documentation, these will be executed in order. You may also configure a script to run after the executable is built instead, using a combination of configure_file() and add_custom_command. Guaranteeing your generated file is available for the second process may be easier and safer that way.


问:
AWS S3 copy assets between two buckets
With the command line interface I can copy files between two buckets.

```<code>$ aws s3 sync s3://mybucket-src s3://mybucket-target --exclude *.tmp
</code>```

This will copy from one source bucket to another target bucket. But I want to copy file types (images, documents, videos) to their respective folders in target bucket.

Images go into source_files/images

Documents go into source_files/pdf

Videos go into source_files/videos

Also as soon as if new files hit source bucket, they should be copied to their respective folders in target bucket.

答:
You have two topics in your question:

Moving objects to different locations based on their type

Moving objects as soon as they appear

The ability to do something as soon as an object is created can be done by configuring an Amazon S3 Event. The event can trigger an AWS Lambda function, send a message to an Amazon SNS topic or put a message into an Amazon SQS queue.

For your use-case, you would use an AWS Lambda function. The function should:

Retrieve the bucket name and Key of the object from the provided event record

Retrieve metadata about the object via HeadObject()

Issue a CopyObject() command to copy the object to a desired location based upon the metadata

For an example of triggering a Lambda function when an S3 object is created, see: Tutorial: Using AWS Lambda with Amazon S3 - AWS Lambda

Title: AWS S3 copy assets between two buckets

Body:
With the command line interface I can copy files between two buckets.

$ aws s3 sync s3://mybucket-src s3://mybucket-target --exclude *.tmp

This will copy from one source bucket to another target bucket. But I want to copy file types (images, documents, videos) to their respective folders in target bucket.

Images go into source_files/images

Documents go into source_files/pdf

Videos go into source_files/videos

Also as soon as if new files hit source bucket, they should be copied to their respective folders in target bucket.


问:
How can I invert a boolean value inside an SQL query?
I am making an alarm app and I would to write a query that would toggle some alarm properties, here is my alarm class.

```<code>@Entity
data class Alarm(
    val label: String?,
    var isEnabled: Boolean,
    val ringTime: LocalTime,
    val occursOn: MutableSet<Day>,
    var isVibrationEnabled: Boolean,
    @PrimaryKey(autoGenerate = true) var id: Int? = null
)
</code>```

Here is my query that should invert vibration value

```<code>    @Query("UPDATE Alarm SET isVibrationEnabled = NOT isVibrationEnabled WHERE id = :alarmId")
    internal abstract fun toggleVibration(alarmId: Int): Completable
</code>```

The app compiles fine, so it seems that the query is valid, however after I execute it, the value is not inverted and it stays the same

答:
I believe that your issue is not the toggling, that works.

Rather that the issue is that the WHERE clause is not selecting a row (or the expected row) and thus that the value passed as the parameter when calling the toggleVibration function is not the id of an Alarm or the expected Alarm.

Example

Consider the following example (in Java rather than Kotlin for convenience) :-

The AlarmEntity Alarm.java

```<code>public class Alarm {

    @PrimaryKey(autoGenerate = true)
    private long id;
    private String label;
    private boolean isEnabled;
    private boolean isVibrationEnabled;

    public Alarm() {

    }

    public Alarm(String label, boolean isEnabled, boolean isVibrationEnabled) {
        this.label = label;
        this.isEnabled = isEnabled;
        this.isVibrationEnabled = isVibrationEnabled;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public boolean isEnabled() {
        return isEnabled;
    }

    public void setEnabled(boolean enabled) {
        isEnabled = enabled;
    }

    public boolean isVibrationEnabled() {
        return isVibrationEnabled;
    }

    public void setVibrationEnabled(boolean vibrationEnabled) {
        isVibrationEnabled = vibrationEnabled;
    }
}
</code>```

reduced set of columns for conveneience

AlarmDao.java

```<code>@Dao
public interface AlarmDao {

    @Insert
    long[] insertAlarm(Alarm... alarms);
    @Insert
    long insertAlarm(Alarm alarm);
    @Query("SELECT * FROM Alarm")
    List<Alarm> getAllAlarms();
    @Query("UPDATE Alarm SET isVibrationEnabled = NOT isVibrationEnabled WHERE id = :id")
    int toggleVibration(long id);
}
</code>```

Code from an Activity to test :-

```<code>    alarmDao = mDB.getAlarmDao();
    // Add a copule of alarms
    alarmDao.insertAlarm(
            new Alarm("Alarm001",true,true),
            new Alarm("Alarm002",false,false)
    );
    // Get the Alarms and output them to the log
    List<Alarm> myalarms = alarmDao.getAllAlarms();
    for (Alarm a: myalarms) {
        Log.d("ALARMBEFORE","Label = " + a.getLabel() + " Enabaled = " + String.valueOf(a.isEnabled()) + " Vibration =  " + a.isVibrationEnabled());
    }
    //<<<<<<<<<< Toggle the first alarm >>>>>>>>>>
    alarmDao.toggleVibration(myalarms.get(0).getId());
    // Again get all the alarams and output them to the log
    myalarms = alarmDao.getAllAlarms();
    for (Alarm a: myalarms) {
        Log.d("ALARMAFTER","Label = " + a.getLabel() + " Enabaled = " + String.valueOf(a.isEnabled()) + " Vibration =  " + a.isVibrationEnabled());
    }
</code>```

Result

```<code>05-30 10:34:33.853 D/ALARMBEFORE: Label = Alarm001 Enabaled = true Vibration =  true
05-30 10:34:33.853 D/ALARMBEFORE: Label = Alarm002 Enabaled = false Vibration =  false
05-30 10:34:33.856 D/ALARMAFTER: Label = Alarm001 Enabaled = true Vibration =  false
05-30 10:34:33.856 D/ALARMAFTER: Label = Alarm002 Enabaled = false Vibration =  false
</code>```

i.e. for Alarm001 the isVibrationEnabaled value has been toggled from true to false

Body:
I am making an alarm app and I would to write a query that would toggle some alarm properties, here is my alarm class.

@Entity
data class Alarm(
    val label: String?,
    var isEnabled: Boolean,
    val ringTime: LocalTime,
    val occursOn: MutableSet<Day>,
    var isVibrationEnabled: Boolean,
    @PrimaryKey(autoGenerate = true) var id: Int? = null
)

Here is my query that should invert vibration value

    @Query("UPDATE Alarm SET isVibrationEnabled = NOT isVibrationEnabled WHERE id = :alarmId")
    internal abstract fun toggleVibration(alarmId: Int): Completable

The app compiles fine, so it seems that the query is valid, however after I execute it, the value is not inverted and it stays the same

Body:
I believe that your issue is not the toggling, that works.

Rather that the issue is that the WHERE clause is not selecting a row (or the expected row) and thus that the value passed as the parameter when calling the toggleVibration function is not the id of an Alarm or the expected Alarm.

Example

Consider the following example (in Java rather than Kotlin for convenience) :-

The AlarmEntity Alarm.java

public class Alarm {

    @PrimaryKey(autoGenerate = true)
    private long id;
    private String label;
    private boolean isEnabled;
    private boolean isVibrationEnabled;

    public Alarm() {

    }

    public Alarm(String label, boolean isEnabled, boolean isVibrationEnabled) {
        this.label = label;
        this.isEnabled = isEnabled;
        this.isVibrationEnabled = isVibrationEnabled;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public boolean isEnabled() {
        return isEnabled;
    }

    public void setEnabled(boolean enabled) {
        isEnabled = enabled;
    }

    public boolean isVibrationEnabled() {
        return isVibrationEnabled;
    }

    public void setVibrationEnabled(boolean vibrationEnabled) {
        isVibrationEnabled = vibrationEnabled;
    }
}

reduced set of columns for conveneience

AlarmDao.java

@Dao
public interface AlarmDao {

    @Insert
    long[] insertAlarm(Alarm... alarms);
    @Insert
    long insertAlarm(Alarm alarm);
    @Query("SELECT * FROM Alarm")
    List<Alarm> getAllAlarms();
    @Query("UPDATE Alarm SET isVibrationEnabled = NOT isVibrationEnabled WHERE id = :id")
    int toggleVibration(long id);
}

Code from an Activity to test :-

    alarmDao = mDB.getAlarmDao();
    // Add a copule of alarms
    alarmDao.insertAlarm(
            new Alarm("Alarm001",true,true),
            new Alarm("Alarm002",false,false)
    );
    // Get the Alarms and output them to the log
    List<Alarm> myalarms = alarmDao.getAllAlarms();
    for (Alarm a: myalarms) {
        Log.d("ALARMBEFORE","Label = " + a.getLabel() + " Enabaled = " + String.valueOf(a.isEnabled()) + " Vibration =  " + a.isVibrationEnabled());
    }
    //<<<<<<<<<< Toggle the first alarm >>>>>>>>>>
    alarmDao.toggleVibration(myalarms.get(0).getId());
    // Again get all the alarams and output them to the log
    myalarms = alarmDao.getAllAlarms();
    for (Alarm a: myalarms) {
        Log.d("ALARMAFTER","Label = " + a.getLabel() + " Enabaled = " + String.valueOf(a.isEnabled()) + " Vibration =  " + a.isVibrationEnabled());
    }

Result

05-30 10:34:33.853 D/ALARMBEFORE: Label = Alarm001 Enabaled = true Vibration =  true
05-30 10:34:33.853 D/ALARMBEFORE: Label = Alarm002 Enabaled = false Vibration =  false
05-30 10:34:33.856 D/ALARMAFTER: Label = Alarm001 Enabaled = true Vibration =  false
05-30 10:34:33.856 D/ALARMAFTER: Label = Alarm002 Enabaled = false Vibration =  false

i.e. for Alarm001 the isVibrationEnabaled value has been toggled from true to false


问:
Datastax - Cassandra php-driver: Uncaught Cassandra\Exception\LogicException:
I'm on Ubuntu right now trying to connect to Cassandra with PHP. I have installed Datastax php-driver and all of its dependencies but i get this error when trying to run a testfile:

```<code>    PHP Fatal error:  Uncaught Cassandra\Exception\LogicException: Not    implemented in /home/philip/Documents/test.php:3
Stack trace:
#0 /home/user/Documents/test.php(3): Cassandra\Cluster\Builder->build()
#1 {main}
  thrown in /home/user/Documents/test.php on line 3
</code>```

The code looks like this:

```<code> <?php
// Connect to the cluster and keyspace "killrvideo"
$cluster  = Cassandra::cluster()->build();
$keyspace  = 'killrvideo';
$session  = $cluster->connect($keyspace);
</code>```

I manage to connect to cassandra using the shell cqlsh and i can see the table i have setup. The php code doesnt seem to work though. Any ideas why?

答:
well this is not very clear for me but you call this from the same server ?
witch strategy you use ? simples or network topology  ?
but something that I'm sure will work with this  </p>

<p>$cluster  = Cassandra::cluster()->withContactPoints('127.0.0.1')->build();  </p>

<p>// or if you call from a different server just replace the ip </p>

Body:
I'm on Ubuntu right now trying to connect to Cassandra with PHP. I have installed Datastax php-driver and all of its dependencies but i get this error when trying to run a testfile:

    PHP Fatal error:  Uncaught Cassandra\Exception\LogicException: Not    implemented in /home/philip/Documents/test.php:3
Stack trace:
#0 /home/user/Documents/test.php(3): Cassandra\Cluster\Builder->build()
#1 {main}
  thrown in /home/user/Documents/test.php on line 3

The code looks like this:

 <?php
// Connect to the cluster and keyspace "killrvideo"
$cluster  = Cassandra::cluster()->build();
$keyspace  = 'killrvideo';
$session  = $cluster->connect($keyspace);

I manage to connect to cassandra using the shell cqlsh and i can see the table i have setup. The php code doesnt seem to work though. Any ideas why?

Body:
well this is not very clear for me but you call this from the same server ?
witch strategy you use ? simples or network topology  ?
but something that I'm sure will work with this

$cluster  = Cassandra::cluster()->withContactPoints('127.0.0.1')->build();

// or if you call from a different server just replace the ip


问:
AWS api gateway will not allow custom domain name association to certificate
AWS API gateway refuses to allow me to associate a custom domain to a certificate. However, it allowed me to associated the certificate just fine to another domain. The certificate is a wildcard cert. A picture is worth a thousand words:

答:
On April 2019, There is some enhancement for CloudFront about the security for adding alternate domain names to a distribution.

It seems that the self-signed certificate is not allowed after the enhancement.

Amazon CloudFront enhances the security for adding alternate domain names to a distribution

The certificate must be valid and come from a publicly trusted Certificate Authority like AWS Certificate Manager which provides public SSL/TLS certificates for free.


问:
How to select number content in element and add commas with jquery or js
I need to simply add commas to numbers in my code. I have tried a lot of hints here but something seems to be wrong.

I have tried with regex and the toLocalString() method and both haven't worked, can someone help me find the correct solution.

```<code><script type="text/javascript">
   $(document).ready(function () {
      // $("#price").toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      $('#price').html.toLocaleString('en');
   });
</script>
</code>```

Here's my element:

```<code><strong id="price"><%# Eval("OfferPrice") %></strong>
</code>```

Everything seems ok, can anyone help please. Thanks a lot!

答: If you trying to add commas after any instance of a number, you need to have a number in the output string 'Everything seems ok, can anyone help please. Thanks a lot!' </p>

Body:
I need to simply add commas to numbers in my code. I have tried a lot of hints here but something seems to be wrong.

I have tried with regex and the toLocalString() method and both haven't worked, can someone help me find the correct solution.

Here's my element:

<%# Eval("OfferPrice") %>

Everything seems ok, can anyone help please. Thanks a lot!


问:
unexpected to_f call
I'm currently creating an action that accepts a file from the user and reads the file line by line. Each line contains several words, seperated by a comma.
The idea is to read each line, convert the line into an array of strings and then process each word individually.

I have created a basic class called Word, which has just an ID and value.
I also have a basic class called Synonym, which has an ID, value and word_id to link to a word.

I receive an exception when parsing the words:

```<code>undefined method `to_f' for
#<Array:0x7ff6627074d8>
</code>```

This is the code causing the problem for me:

```<code># Processes the uploaded file from the upload form and extracts
  # all relevant information from the file to store it in the database
  def process_upload
    path = params[:file].tempfile.path
    open(path).each do |line|
      words = line.trim.split(',')
      first_word = words.first
      # Check if the word already exists as a synonym. If the word is a known synonym, save the
      # remaining words as synonyms for the parent word. But only save these words if they don't
      # exist yet
      if !Synonym.find_by_value(first_word).blank?
        parent_id = Synonym.find_by_value(first_word).word_id
        words.each do |word|
          Synonym.create(:value => word, :parent_id => parent_id) if Synonym.find_by_value(word).blank?
        end
      end

      # Check if the first word is already known as a word inside the application. If the first word is already
      # a known word, append all remaining words to the word as a synonym, but only if they don't exist yet.
      if !Word.find_by_value(first_word).blank?
        words.each do |word|
          parent_id = Word.find_by_value(first_word).id
          if (word != first_word) and Synonym.find_by_value(word).blank?
            Synonym.create(:value => word, :parent_id => parent_id)
          end
        end
      end

      # The word is not a known synonym, and not a known word. Create the word in the database and
      # append all remaining words to the database as synonyms.
      word = Word.create(:value => first_word)
      words.each do |w|
        if w.eql? word.value
          Synonym.create :value => w, :parent_id => word.id
        end
      end
    end
  end
</code>```

The problem occurs on the last part, Word.create(:value => first_word)
I receive an exception here that tries to cast it to a float for some reason, but I have no idea why.

The migration schema' for both models:

```<code>class CreateWords < ActiveRecord::Migration
  def self.up
    create_table :words do |t|
      t.string :value, :null => false
      t.timestamps
    end
  end

  def self.down
    drop_table :words
  end
end

class CreateSynonyms < ActiveRecord::Migration
  def self.up
    create_table :synonyms do |t|
      t.integer :word_id, :null => false
      t.string :value, :null => false
      t.timestamps
    end
  end

  def self.down
    drop_table :synonyms
  end
end
</code>```

What am I missing?

答:
In regards to the above comments, I found out what was causing this:

If you rely on the Classifier gem from rubyforge or rubygems, it will overwrite the Array#sum method. Since these gems are loaded AFTER rails is loaded, they overwrite this method for ActiveRecord as well, which causes errors.

There are branches of this gem avaialble that keep track of all this, but in the end, I decided to use the 'Ankusa' gem instead, as it was more suited to handeling large batches of text data and had better integrated support for saving the state.

Title: unexpected to_f call

Body:
I'm currently creating an action that accepts a file from the user and reads the file line by line. Each line contains several words, seperated by a comma.
The idea is to read each line, convert the line into an array of strings and then process each word individually.

I have created a basic class called Word, which has just an ID and value.
I also have a basic class called Synonym, which has an ID, value and word_id to link to a word.

I receive an exception when parsing the words:

undefined method `to_f' for
#<Array:0x7ff6627074d8>

This is the code causing the problem for me:

# Processes the uploaded file from the upload form and extracts
  # all relevant information from the file to store it in the database
  def process_upload
    path = params[:file].tempfile.path
    open(path).each do |line|
      words = line.trim.split(',')
      first_word = words.first
      # Check if the word already exists as a synonym. If the word is a known synonym, save the
      # remaining words as synonyms for the parent word. But only save these words if they don't
      # exist yet
      if !Synonym.find_by_value(first_word).blank?
        parent_id = Synonym.find_by_value(first_word).word_id
        words.each do |word|
          Synonym.create(:value => word, :parent_id => parent_id) if Synonym.find_by_value(word).blank?
        end
      end

      # Check if the first word is already known as a word inside the application. If the first word is already
      # a known word, append all remaining words to the word as a synonym, but only if they don't exist yet.
      if !Word.find_by_value(first_word).blank?
        words.each do |word|
          parent_id = Word.find_by_value(first_word).id
          if (word != first_word) and Synonym.find_by_value(word).blank?
            Synonym.create(:value => word, :parent_id => parent_id)
          end
        end
      end

      # The word is not a known synonym, and not a known word. Create the word in the database and
      # append all remaining words to the database as synonyms.
      word = Word.create(:value => first_word)
      words.each do |w|
        if w.eql? word.value
          Synonym.create :value => w, :parent_id => word.id
        end
      end
    end
  end

The problem occurs on the last part, Word.create(:value => first_word)
I receive an exception here that tries to cast it to a float for some reason, but I have no idea why.

The migration schema' for both models:

class CreateWords < ActiveRecord::Migration
  def self.up
    create_table :words do |t|
      t.string :value, :null => false
      t.timestamps
    end
  end

  def self.down
    drop_table :words
  end
end

class CreateSynonyms < ActiveRecord::Migration
  def self.up
    create_table :synonyms do |t|
      t.integer :word_id, :null => false
      t.string :value, :null => false
      t.timestamps
    end
  end

  def self.down
    drop_table :synonyms
  end
end

What am I missing?


问:
String list multiplication in Python
Beginner question:
If I have 2 lists containing only strings, how do I concatenate them in a third list containing all the elements + each element of one list + each element in the other list? I thought about for loops, but isn't there a more simple way to do it?
Example:

```<code>listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun']

resulting list = ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun', 'catbinsun', 'catsunbin', 'catcat', 'catdog', 'dogbin', 'dogcat']
</code>```

EDIT: Thank you all for replies, but i didn't explain what I want to do well enough.
The number of string in each list should be indefinite, and every word has to be concatenated with every other word, but not only in the form "x + y".
I want also to concatenate it to the other words. Like u = x+y+z

答:
If you're only looking for combinations (i.e. x+y,x+y+z but not y+x or z+y+x), you could use the combinations functions from itertools to form a power set:

```<code>from itertools import combinations

words  = listone+listtwo
result = ["".join(c) for r in range(1,len(words)+1) for c in combinations(words, r)]

print(result)

# ['cat', 'dog', 'bin', 'sun', 'catdog', 'catbin', 'catsun', 'dogbin',
#  'dogsun', 'binsun', 'catdogbin', 'catdogsun', 'catbinsun', 'dogbinsun',
#  'catdogbinsun']
</code>```

note: combinations power sets grow exponentially with the number of source items: 2^n - 1

If you want to obtain permutations instead, replace combinations by permutationsfrom itertools. (this will produce an order of magnitude more elements than combinations)

Title: String list multiplication in Python

Body:
Beginner question:
If I have 2 lists containing only strings, how do I concatenate them in a third list containing all the elements + each element of one list + each element in the other list? I thought about for loops, but isn't there a more simple way to do it?
Example:

listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun']

resulting list = ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun', 'catbinsun', 'catsunbin', 'catcat', 'catdog', 'dogbin', 'dogcat']

EDIT: Thank you all for replies, but i didn't explain what I want to do well enough.
The number of string in each list should be indefinite, and every word has to be concatenated with every other word, but not only in the form "x + y".
I want also to concatenate it to the other words. Like u = x+y+z

Body:
If you're only looking for combinations (i.e. x+y,x+y+z but not y+x or z+y+x), you could use the combinations functions from itertools to form a power set:

from itertools import combinations

words  = listone+listtwo
result = ["".join(c) for r in range(1,len(words)+1) for c in combinations(words, r)]

print(result)

# ['cat', 'dog', 'bin', 'sun', 'catdog', 'catbin', 'catsun', 'dogbin',
#  'dogsun', 'binsun', 'catdogbin', 'catdogsun', 'catbinsun', 'dogbinsun',
#  'catdogbinsun']

note: combinations power sets grow exponentially with the number of source items: 2^n - 1

If you want to obtain permutations instead, replace combinations by permutationsfrom itertools. (this will produce an order of magnitude more elements than combinations)


问:
SQL Server trigger case statement NOT catching
I am trying to create a trigger that when the SAMPLE table column is updated, it uses a case statement to update a column in another table. Currently the trigger does not catch any of the WHEN clauses. The value in the ELSE clause is what is used to do the update.

```<code>CREATE TRIGGER dbo.SAMPVAL
ON dbo.SAMPLE
FOR UPDATE
AS
BEGIN
    UPDATE U
    SET U.VALIDATED = CASE
                         WHEN (U.VALIDATED IS NULL AND LEN(INSERTED.VALUSER) > 0)
                            THEN 'VAL1'
                         WHEN (LEN(U.VALIDATED) > 0 AND U.VALIDATED = 'VAL1')
                            THEN 'VAL2'
                         WHEN (LEN(U.VALIDATED) = 0)
                            THEN 'NEWERVAL'
                         WHEN (LEN(U.VALIDATED) > 0)
                            THEN 'NEWERVAL1'
                         ELSE '-'
                      END
    FROM INSERTED
    INNER JOIN SUSERFLDS U ON U.SAMPNO = INSERTED.SAMPNO
END;
</code>```

If the U.VALIDATED field is empty and SAMPLE.VALUSER column length is greater than zero, then the SUSERFLDS.VALIDATED = 'VAL1'. When I test this, the SUSERFLDS.VALIDATED column gets updated to "-".

答:
```<code>CREATE TRIGGER dbo.SAMPVAL
ON dbo.SAMPLE
FOR UPDATE
AS BEGIN
  UPDATE U
    SET U.VALIDATED = CASE
    WHEN (U.VALIDATED IS NULL AND LEN(INSERTED.VALUSER) > 0) THEN 'VAL1'
    WHEN (LEN(U.VALIDATED) > 0 AND U.VALIDATED = 'VAL1') THEN 'VAL2'
    WHEN (LEN(U.VALIDATED) = 0) THEN 'NEWERVAL'
    WHEN (LEN(U.VALIDATED) > 0) THEN 'NEWERVAL1'
    ELSE U.VALIDATED
    END
  FROM INSERTED
  INNER JOIN SUSERFLDS U ON U.SAMPNO =INSERTED.SAMPNO
END;
</code>```

Changing ELSE '-' to ELSE U.VALIDATED fixed the issue.

Body:
I am trying to create a trigger that when the SAMPLE table column is updated, it uses a case statement to update a column in another table. Currently the trigger does not catch any of the WHEN clauses. The value in the ELSE clause is what is used to do the update.

CREATE TRIGGER dbo.SAMPVAL
ON dbo.SAMPLE
FOR UPDATE
AS
BEGIN
    UPDATE U
    SET U.VALIDATED = CASE
                         WHEN (U.VALIDATED IS NULL AND LEN(INSERTED.VALUSER) > 0)
                            THEN 'VAL1'
                         WHEN (LEN(U.VALIDATED) > 0 AND U.VALIDATED = 'VAL1')
                            THEN 'VAL2'
                         WHEN (LEN(U.VALIDATED) = 0)
                            THEN 'NEWERVAL'
                         WHEN (LEN(U.VALIDATED) > 0)
                            THEN 'NEWERVAL1'
                         ELSE '-'
                      END
    FROM INSERTED
    INNER JOIN SUSERFLDS U ON U.SAMPNO = INSERTED.SAMPNO
END;

If the U.VALIDATED field is empty and SAMPLE.VALUSER column length is greater than zero, then the SUSERFLDS.VALIDATED = 'VAL1'. When I test this, the SUSERFLDS.VALIDATED column gets updated to "-".

Body:
CREATE TRIGGER dbo.SAMPVAL
ON dbo.SAMPLE
FOR UPDATE
AS BEGIN
  UPDATE U
    SET U.VALIDATED = CASE
    WHEN (U.VALIDATED IS NULL AND LEN(INSERTED.VALUSER) > 0) THEN 'VAL1'
    WHEN (LEN(U.VALIDATED) > 0 AND U.VALIDATED = 'VAL1') THEN 'VAL2'
    WHEN (LEN(U.VALIDATED) = 0) THEN 'NEWERVAL'
    WHEN (LEN(U.VALIDATED) > 0) THEN 'NEWERVAL1'
    ELSE U.VALIDATED
    END
  FROM INSERTED
  INNER JOIN SUSERFLDS U ON U.SAMPNO =INSERTED.SAMPNO
END;

Changing ELSE '-' to ELSE U.VALIDATED fixed the issue.


问:
How can I make two joined open arcs(without the horizontal line) in HTML canvas?
I am new to canvas element in HTML, and am trying to make something like ~ using .arc() method.

Here's my code: (or JSFiddle)

HTML

```<code>    <canvas height = "500" width = "500" id = "myCanvas"></canvas>
</code>```

Javascript

```<code>    let canvas = document.getElementById('myCanvas');
    let ctx = canvas.getContext("2d");

    ctx.strokeStyle = '#000';
    ctx.fillStyle = "red";
    ctx.lineWidth = 3;

    ctx.beginPath();
    ctx.arc(50, 50, 50, 0, Math.PI, true);
    ctx.arc(150, 50, 50, 0, Math.PI);
    ctx.fill();
    ctx.stroke();
</code>```

I am getting a horizontal line connecting the start and the end of the two joined semicircles. How can I remove that?

答:
You need to moveTo the beginning of your second arc: cx + rad, cy

let canvas = document.getElementById('myCanvas');
let ctx = canvas.getContext("2d");

ctx.strokeStyle = '#000';
ctx.fillStyle = "red";
ctx.lineWidth = 3;

ctx.beginPath();
ctx.arc(50, 50, 50, 0, Math.PI, true);
// move the pointer to the next drawing point without tracing anything
ctx.moveTo(150 + 50, 50);
ctx.arc(150, 50, 50, 0, Math.PI);
ctx.fill();
ctx.stroke();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas height="500" width="500" id="myCanvas"></canvas></code>```

Body:
I am new to canvas element in HTML, and am trying to make something like ~ using .arc() method.

Here's my code: (or JSFiddle)

HTML

    <canvas height = "500" width = "500" id = "myCanvas"></canvas>

Javascript

    let canvas = document.getElementById('myCanvas');
    let ctx = canvas.getContext("2d");

    ctx.strokeStyle = '#000';
    ctx.fillStyle = "red";
    ctx.lineWidth = 3;

    ctx.beginPath();
    ctx.arc(50, 50, 50, 0, Math.PI, true);
    ctx.arc(150, 50, 50, 0, Math.PI);
    ctx.fill();
    ctx.stroke();

I am getting a horizontal line connecting the start and the end of the two joined semicircles. How can I remove that?

Body:
You need to moveTo the beginning of your second arc: cx + rad, cy

let canvas = document.getElementById('myCanvas');
let ctx = canvas.getContext("2d");

ctx.strokeStyle = '#000';
ctx.fillStyle = "red";
ctx.lineWidth = 3;

ctx.beginPath();
ctx.arc(50, 50, 50, 0, Math.PI, true);
// move the pointer to the next drawing point without tracing anything
ctx.moveTo(150 + 50, 50);
ctx.arc(150, 50, 50, 0, Math.PI);
ctx.fill();
ctx.stroke();

<canvas height="500" width="500" id="myCanvas"></canvas>


问:
How to convert an image to buffered image using java default libraries
I am working on a project that involves pattern detection. I have to scale the input images to a specific size and test for pixel colour.

I tried to take in a java.awt.Image so I could resize it, then convert it to BufferedImage to test for the RGB value for each independent pixel.
However, casting BufferedImage to Image does not work.

Since java.awt.Image cannot access the color value of each individual pixel, I have to use the .getRBG functions of a BufferedImage. However, I have to take in a java.awt.Image because BufferedImage cannot be resized. I did some research about resizing the BufferedImage but all the result I found is about resizing it on screen, but not the actual image. I am NOT trying to display the BufferedImage on screen, I am trying to access the colour value of each pixel on an image.

These are the ways that could fix my issue:
Please suggest a way to...

Scale a BufferedImage (that doesn't involve drawing on the screen, just resizing the BufferedImage itself)

or

Access the colour value of a pixel in java.awt.Image

```<code>Image img = ImageIO.read(inputFile).getScaledInstance(400, 400, 0);

BufferedImage scaledImage = (BufferedImage)img;
</code>```

The following code does not compile because BufferedImage cannot be cast to java.awt.Image

答:
```<code>String imagePath = "path/to/your/image.jpg";
BufferedImage myPicture = ImageIO.read(new File(imagePath));
</code>```

You can use ImageIO, check this documentation: Converting Image to BufferedImage

Or this amazing tutorial: https://www.baeldung.com/java-images
Or even this same question in 2012: Converting Image to BufferedImage

If I answer wrong your question, let me know.

For resize your image, you can try use something like that:

```<code>public static BufferedImage resize(BufferedImage img, int newW, int newH) {
    Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
    BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2d = dimg.createGraphics();
    g2d.drawImage(tmp, 0, 0, null);
    g2d.dispose();

    return dimg;
}
</code>```

this answer come from: Bufferedimage resize

Body:
I am working on a project that involves pattern detection. I have to scale the input images to a specific size and test for pixel colour.

I tried to take in a java.awt.Image so I could resize it, then convert it to BufferedImage to test for the RGB value for each independent pixel.
However, casting BufferedImage to Image does not work.

Since java.awt.Image cannot access the color value of each individual pixel, I have to use the .getRBG functions of a BufferedImage. However, I have to take in a java.awt.Image because BufferedImage cannot be resized. I did some research about resizing the BufferedImage but all the result I found is about resizing it on screen, but not the actual image. I am NOT trying to display the BufferedImage on screen, I am trying to access the colour value of each pixel on an image.

These are the ways that could fix my issue:
Please suggest a way to...

Scale a BufferedImage (that doesn't involve drawing on the screen, just resizing the BufferedImage itself)

or

Access the colour value of a pixel in java.awt.Image

Image img = ImageIO.read(inputFile).getScaledInstance(400, 400, 0);

BufferedImage scaledImage = (BufferedImage)img;

The following code does not compile because BufferedImage cannot be cast to java.awt.Image

Body:
String imagePath = "path/to/your/image.jpg";
BufferedImage myPicture = ImageIO.read(new File(imagePath));

You can use ImageIO, check this documentation: Converting Image to BufferedImage

Or this amazing tutorial: https://www.baeldung.com/java-images
Or even this same question in 2012: Converting Image to BufferedImage

If I answer wrong your question, let me know.

For resize your image, you can try use something like that:

public static BufferedImage resize(BufferedImage img, int newW, int newH) {
    Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
    BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2d = dimg.createGraphics();
    g2d.drawImage(tmp, 0, 0, null);
    g2d.dispose();

    return dimg;
}

this answer come from: Bufferedimage resize


问:
PHP, MySQL - Geo location query doesnt seem to be returning all possible locations
I have 100 property listings as wordpress posts and each post has two custom fields attached holding the property co-ordinates; property_address_lat and property_address_lng.

I'm providing a way for our website visitors to type in an address or location of their choice where the co-ordinates are returned and also they can enter a radius in miles. And what should happen is the properties that are within those paremeters are returned. So here is the code Im using:

```<code>// Work out square radius
if(!empty($_SESSION['s_property_radius'])) {$dist = $_SESSION['s_property_radius'];}else{$dist = 50;}
$orig_lat = $_SESSION['s_property_address_lat'];
$orig_lon = $_SESSION['s_property_address_lng'];
$lon1 = $orig_lon - $dist / abs( cos( deg2rad( $orig_lat ) ) * 69 );
$lon2 = $orig_lon + $dist / abs( cos( deg2rad( $orig_lat ) ) * 69 );
$lat1 = $orig_lat - ( $dist / 69 );
$lat2 = $orig_lat + ( $dist / 69 );

// Compile a map search query to get all property ID's.
$mapsearchquery = "
            SELECT `t`.`ID`
            , 3956 * 2 * ASIN( SQRT( POWER( SIN( ( ".$orig_lat." - `t`.`property_address_lat` ) * pi() / 180 / 2), 2 ) + COS( ".$orig_lat." * pi() / 180) * COS( `t`.`property_address_lat` * pi() / 180 ) * POWER( SIN( ( ".$orig_lon." - `t`.`property_address_lng` ) * pi() / 180 / 2 ), 2 ) ) ) AS `distance`
            FROM (

            SELECT `$wpdb->posts`.`ID`
            , MAX(CASE WHEN `$wpdb->postmeta`.`meta_key` = 'property_address_lng' THEN `$wpdb->postmeta`.`meta_value` END ) AS `property_address_lng`
            , MAX(CASE WHEN `$wpdb->postmeta`.`meta_key` = 'property_address_lat' THEN `$wpdb->postmeta`.`meta_value` END ) AS `property_address_lat`
            FROM `$wpdb->posts`
            LEFT JOIN `$wpdb->postmeta` ON ( `$wpdb->posts`.`ID` = `$wpdb->postmeta`.`post_id` )
            WHERE `$wpdb->posts`.`post_status` = 'publish'
            AND `$wpdb->posts`.`post_type` = 'property'
            GROUP BY `$wpdb->posts`.`ID`
            HAVING `property_address_lng` BETWEEN '".$lon1."' AND '".$lon2."' AND `property_address_lat` BETWEEN '".$lat1."' AND '".$lat2."'

            ) AS `t`
            HAVING `distance` < ".$dist."
        ";
// Just get the ID's
$mapsearchresults = $wpdb->get_col($mapsearchquery);
</code>```

The $_SESSION data holds the users chosen paremeters. What I'm doing first is working out a rough square box around the chosen area. This does an initial query on the data to make sure that the posts are within that box. Then once that runs I run over the top of the results a distance checker to make sure each property is inside a circle radius. Im sure I dont need to explain why Im doing the two steps and not one.

So I come to put it to the test. I set the centerpoint to London and set a 50Mile radius. I get returned about 16 properties which seems about right. I checked them all and yes they are within the radius. So great I think this is working but then I go and set the radius to 1000Miles which should cover all of the properties and I should expect all properties to be returned. Well when I run this only about half of the properties are returned...

So what has got me thinking is that this code is just not right and it seems to fail when the radius is ramped up. Can any of you see if I've done something stupid with my code? all the mathematics to this should be done so working in miles and not KM.

If anyone can shed some light onto this I'd really apreciate it.

答:
While working on another project I found the answer to this.

Because the longitude and latitude is stored in the meta data it is stored as LONGTEXT. When doing my calculations in the SQL they were not seeing the values as floating point numbers bu instead rounding to whole numbers which was throwing my results way off.

Anyway the way to fix was to use CAST() and cast to DECIMAL().

So the SQL would look something like this instead:

```<code>HAVING CAST(`property_address_lng` AS DECIMAL(9,6)) BETWEEN '".$lon1."' AND '".$lon2."' AND CAST(`property_address_lat` AS DECIMAL(9,6)) BETWEEN '".$lat1."' AND '".$lat2."'
</code>```

Body:
I have 100 property listings as wordpress posts and each post has two custom fields attached holding the property co-ordinates; property_address_lat and property_address_lng.

I'm providing a way for our website visitors to type in an address or location of their choice where the co-ordinates are returned and also they can enter a radius in miles. And what should happen is the properties that are within those paremeters are returned. So here is the code Im using:

// Work out square radius
if(!empty($_SESSION['s_property_radius'])) {$dist = $_SESSION['s_property_radius'];}else{$dist = 50;}
$orig_lat = $_SESSION['s_property_address_lat'];
$orig_lon = $_SESSION['s_property_address_lng'];
$lon1 = $orig_lon - $dist / abs( cos( deg2rad( $orig_lat ) ) * 69 );
$lon2 = $orig_lon + $dist / abs( cos( deg2rad( $orig_lat ) ) * 69 );
$lat1 = $orig_lat - ( $dist / 69 );
$lat2 = $orig_lat + ( $dist / 69 );

// Compile a map search query to get all property ID's.
$mapsearchquery = "
            SELECT `t`.`ID`
            , 3956 * 2 * ASIN( SQRT( POWER( SIN( ( ".$orig_lat." - `t`.`property_address_lat` ) * pi() / 180 / 2), 2 ) + COS( ".$orig_lat." * pi() / 180) * COS( `t`.`property_address_lat` * pi() / 180 ) * POWER( SIN( ( ".$orig_lon." - `t`.`property_address_lng` ) * pi() / 180 / 2 ), 2 ) ) ) AS `distance`
            FROM (

            SELECT `$wpdb->posts`.`ID`
            , MAX(CASE WHEN `$wpdb->postmeta`.`meta_key` = 'property_address_lng' THEN `$wpdb->postmeta`.`meta_value` END ) AS `property_address_lng`
            , MAX(CASE WHEN `$wpdb->postmeta`.`meta_key` = 'property_address_lat' THEN `$wpdb->postmeta`.`meta_value` END ) AS `property_address_lat`
            FROM `$wpdb->posts`
            LEFT JOIN `$wpdb->postmeta` ON ( `$wpdb->posts`.`ID` = `$wpdb->postmeta`.`post_id` )
            WHERE `$wpdb->posts`.`post_status` = 'publish'
            AND `$wpdb->posts`.`post_type` = 'property'
            GROUP BY `$wpdb->posts`.`ID`
            HAVING `property_address_lng` BETWEEN '".$lon1."' AND '".$lon2."' AND `property_address_lat` BETWEEN '".$lat1."' AND '".$lat2."'

            ) AS `t`
            HAVING `distance` < ".$dist."
        ";
// Just get the ID's
$mapsearchresults = $wpdb->get_col($mapsearchquery);

The $_SESSION data holds the users chosen paremeters. What I'm doing first is working out a rough square box around the chosen area. This does an initial query on the data to make sure that the posts are within that box. Then once that runs I run over the top of the results a distance checker to make sure each property is inside a circle radius. Im sure I dont need to explain why Im doing the two steps and not one.

So I come to put it to the test. I set the centerpoint to London and set a 50Mile radius. I get returned about 16 properties which seems about right. I checked them all and yes they are within the radius. So great I think this is working but then I go and set the radius to 1000Miles which should cover all of the properties and I should expect all properties to be returned. Well when I run this only about half of the properties are returned...

So what has got me thinking is that this code is just not right and it seems to fail when the radius is ramped up. Can any of you see if I've done something stupid with my code? all the mathematics to this should be done so working in miles and not KM.

If anyone can shed some light onto this I'd really apreciate it.

Body:
While working on another project I found the answer to this.

Because the longitude and latitude is stored in the meta data it is stored as LONGTEXT. When doing my calculations in the SQL they were not seeing the values as floating point numbers bu instead rounding to whole numbers which was throwing my results way off.

Anyway the way to fix was to use CAST() and cast to DECIMAL().

So the SQL would look something like this instead:

HAVING CAST(`property_address_lng` AS DECIMAL(9,6)) BETWEEN '".$lon1."' AND '".$lon2."' AND CAST(`property_address_lat` AS DECIMAL(9,6)) BETWEEN '".$lat1."' AND '".$lat2."'


问:
Linux application project for zynq7000 in the Xilinx SDK
I'm trying to create a Linux application to run on my Zynq7020. However I don't understand how the Xilinx SDK generate the executable file.

When I create a hello world, for instance, it creates one .elf file and under the debug it creates one object (.o) and one dependency (.d). I want to run it under the Linux that is running on my board, how do I do it?

Thank you very much.

答: When creating the project in the Xilinx SDK, select that it runs on linux rather than standalone. See this official tutorial for an in-depth explanation.</p>


问:
How do I update code to show random walk?
I am working on plotting a random walk using MATPLOTLIB. What is the codew below missing?

```<code>from random import choice

class RandomWalk():
    def __init__(self, num_points=5000):
        self.num_points = num_points
        self.x_values = [0]
        self.y_values = [0]

def fill_walk(self):
    while len(self.x_values) < self.num_points:
        x_direction = choice([1, -1])
        x_distance = choice([0, 1, 2, 3, 4])
        x_step = x_direction * x_distance

        y_direction = choice([1, -1])
        y_distance = choice([0, 1, 2, 3, 4])
        y_step = y_direction * y_distance

        if x_step == 0 and y_step == 0:
            continue

        next_x = self.x_values[-1] + x_step
        next_y = self.y_values[-1] + y_step

        self.x_values.append(next_x)
        self.y_values.append(next_y)

import matplotlib.pyplot as plt
from random_walk import RandomWalk

rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()
</code>```

The error I get is as follows: "ModuleNotFoundError: No module named 'random_walk'"

答:
Unless you have saved the class in a file called random_walk.py located in the same directory as the file with rest of your code to plot an create the class instance, you just need to get rid of the from random_walk import RandomWalk and fix the indentation of your class' method called fill_walk(self)

```<code>from random import choice
import matplotlib.pyplot as plt

class RandomWalk():
    def __init__(self, num_points=5000):
        self.num_points = num_points
        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):
        while len(self.x_values) < self.num_points:
            x_direction = choice([1, -1])
            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_direction * x_distance

            y_direction = choice([1, -1])
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_direction * y_distance

            if x_step == 0 and y_step == 0:
                continue

            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step

            self.x_values.append(next_x)
            self.y_values.append(next_y)

rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()
</code>```

Body:
I am working on plotting a random walk using MATPLOTLIB. What is the codew below missing?

from random import choice

class RandomWalk():
    def __init__(self, num_points=5000):
        self.num_points = num_points
        self.x_values = [0]
        self.y_values = [0]

def fill_walk(self):
    while len(self.x_values) < self.num_points:
        x_direction = choice([1, -1])
        x_distance = choice([0, 1, 2, 3, 4])
        x_step = x_direction * x_distance

        y_direction = choice([1, -1])
        y_distance = choice([0, 1, 2, 3, 4])
        y_step = y_direction * y_distance

        if x_step == 0 and y_step == 0:
            continue

        next_x = self.x_values[-1] + x_step
        next_y = self.y_values[-1] + y_step

        self.x_values.append(next_x)
        self.y_values.append(next_y)

import matplotlib.pyplot as plt
from random_walk import RandomWalk

rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()

The error I get is as follows: "ModuleNotFoundError: No module named 'random_walk'"

Body:
Unless you have saved the class in a file called random_walk.py located in the same directory as the file with rest of your code to plot an create the class instance, you just need to get rid of the from random_walk import RandomWalk and fix the indentation of your class' method called fill_walk(self)

from random import choice
import matplotlib.pyplot as plt

class RandomWalk():
    def __init__(self, num_points=5000):
        self.num_points = num_points
        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):
        while len(self.x_values) < self.num_points:
            x_direction = choice([1, -1])
            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_direction * x_distance

            y_direction = choice([1, -1])
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_direction * y_distance

            if x_step == 0 and y_step == 0:
                continue

            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step

            self.x_values.append(next_x)
            self.y_values.append(next_y)

rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()


问:
Returning the index of an empty element inside an array
So I have an array let's say :

```<code>var arr = ['apples' , 'cherries' , 'strawberries']
</code>```

and after so much coding, I get hungry so I eat the 'cherries'
so now I have

```<code>arr = ['apples',null,'strawberries']
</code>```

So I was wondering if there is some sort of JavaScript function that can return the first null element inside an array ?

Let's say for instance my grandma gives me 'potatoes' and I want to add them inside the null space I have like a good boy I am, and I need the index of that null element so I may know where to place my sweet goods from grandma.

答:
Since null is a falsy value you can simply use Array.findIndex and match on falsy values:

var arr = ['apples',null,'strawberries']

let index = arr.findIndex(x => !x)

console.log(index)
console.log(arr[index])```

Body:
So I have an array let's say :

var arr = ['apples' , 'cherries' , 'strawberries']

and after so much coding, I get hungry so I eat the 'cherries'
so now I have

arr = ['apples',null,'strawberries']

So I was wondering if there is some sort of JavaScript function that can return the first null element inside an array ?

Let's say for instance my grandma gives me 'potatoes' and I want to add them inside the null space I have like a good boy I am, and I need the index of that null element so I may know where to place my sweet goods from grandma.


问:
What is an idiomatic Scala way to "remove" one element from an immutable List?
I have a List, which may contain elements that will compare as equal. I would like a similar List, but with one element removed. So from (A, B, C, B, D) I would like to be able to "remove" just one B to get e.g. (A, C, B, D). The order of the elements in the result does not matter.

I have working code, written in a Lisp-inspired way in Scala. Is there a more idiomatic way
to do this?

The context is a card game where two decks of standard cards are in play, so there may
be duplicate cards but still played one at a time.

```<code>def removeOne(c: Card, left: List[Card], right: List[Card]): List[Card] = {
  if (Nil == right) {
    return left
  }
  if (c == right.head) {
    return left ::: right.tail
  }
  return removeOne(c, right.head :: left, right.tail)
}

def removeCard(c: Card, cards: List[Card]): List[Card] = {
  return removeOne(c, Nil, cards)
}
</code>```

答:
How about

```<code>def removeCard(c: Card, cards: List[Card]) = {
  val (head, tail) = cards span {c!=}
  head :::
  (tail match {
    case x :: xs => xs
    case Nil => Nil
  })
}
</code>```

If you see return, there's something wrong.

Body:
I have a List, which may contain elements that will compare as equal. I would like a similar List, but with one element removed. So from (A, B, C, B, D) I would like to be able to "remove" just one B to get e.g. (A, C, B, D). The order of the elements in the result does not matter.

I have working code, written in a Lisp-inspired way in Scala. Is there a more idiomatic way
to do this?

The context is a card game where two decks of standard cards are in play, so there may
be duplicate cards but still played one at a time.

def removeOne(c: Card, left: List[Card], right: List[Card]): List[Card] = {
  if (Nil == right) {
    return left
  }
  if (c == right.head) {
    return left ::: right.tail
  }
  return removeOne(c, right.head :: left, right.tail)
}

def removeCard(c: Card, cards: List[Card]): List[Card] = {
  return removeOne(c, Nil, cards)
}

Body:
How about

def removeCard(c: Card, cards: List[Card]) = {
  val (head, tail) = cards span {c!=}
  head :::
  (tail match {
    case x :: xs => xs
    case Nil => Nil
  })
}

If you see return, there's something wrong.


问:
Create Athena on S3 , need to truncate reload the underlying data in the s3 bucket
Iam trying to setup athena queries for my users, but we need to refresh underlying data.

Not sure if we can refresh data from s3 like truncate and reload but no downtime for athena users.

答:
When an Amazon Athena query is executed, it reads through the files in the directory location associated with the table definition.

If you wish to update underlying data, simply update the files in Amazon S3. The new data shall be used when the next Athena query is issued.

If you are worried about "down time" while you are updating/replacing the data, then you could put the new data in a different folder. Once it is ready, modify the table definition to point to the new location instead of the previous location.

See: ALTER TABLE SET LOCATION - Amazon Athena


问:
Greedy Algorithms and Time Complexity #2
We have a bomb that is ticking and may explode. This bomb has n switches, that can be moved up or down. Certain combinations of these switches trigger the bomb, but only one combination disables it.

Our task is to move the switches from the current position to a position that disables the bomb, without exploding it in the meantime. The switches are big and awkward, so we can move only one switch at a time.

We have, lets say, n = 4 switches currently in position ^vvv. We need to get them to the position ^v^^. Forbidden positions are vvv^, ^vv^, ^v^v, and ^^^v.

a.) I had to draw this by hand and find the shortest sequence of switch movements that solves the task - result I got was 4 ...and I found two such sequences, if i am right...

b.) this is where it gets a hard - write a code that answers the above question/questions (the shortest sequence and how many). The code should be generalized so that it would work with another number of switches and other starting, targeted, and forbidden combinations; targeted and forbidden combinations may be multiple or even fewer. Only thing we know for sure is that the switches have only two positions. It should also provide the possibility that the desired condition is unavailable; in this case, the program should of course tell.

c.) Next questions is the time complexity of the code this but for now I think I will just stop here...

I used '0' and '1' instead, because it is easier for me to imagine this.

So my approach towards this was something of a greedy algorithm (I think) - starting position, you think of all the possible (allowed) positions, you ignore the forbidden ones, then pick the one that the sequence of positions has the fewest difference from our targeting sequence.

The key part of the code I am yet to write and that's the part I need help with.

```<code>
all_combinations = ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011' , '1100', '1101', '1110', '1111']

def distance (position1, position2):
     distance = 0
     for i in range (len (position1)):
         if position1 [i]! = position2 [i]:
             distance + = 1
     return distance

def allowed_positions (current, all_combinations):
     allowed = set ()
     for combination and all combinations:
         if the distance (current, combination) == 1:
             allowed.add (combination)
     return allowed

def best_name (current, all_combinations, target):
     list = []
     for option and permitted_mood (current, all_combinations):
         list.append (distance (option, target), option)

</code>```

答:
The task at hand is finding a shortest path in a graph.  For this there is one typical approach and that is a breadth-first search algorithm (https://en.wikipedia.org/wiki/Breadth-first_search).

There is no real need to go into the details of how this is done because it can be read elsewhere in more detail and far better explained than I can do this in a StackOverflow answer.

But what might need to be explained is how the switch-combinations you have at hand are represented by a graph.

Imagine you have just two switches.  Then you have exactly this graph:

```<code>^^---^v
|     |
|     |
v^---vv
</code>```

If your starting position is ^^ and your ending (defusing) position is vv while the position ^v is an exploding position, then your graph is reduced to this:

```<code>^^   ^v
|
|
v^---vv
</code>```

In this small example the shortest path is obvious and simple.

The graph at hand is easily sketched out in 2D, each dimension (x and y) representing one of the switches.  If you have more switches, then you just add one dimension for each switch.  For three switches this would look like this:

```<code>^^^--------^^v
 |\         |\
 | \        | \
 |  \       |  \
 |   \      |   \
 |   ^v^--- | --^vv
 |    |     |    |
 |    |     |    |
v^^--------v^v   |
  \   |      \   |
   \  |       \  |
    \ |        \ |
     \|         \|
     vv^--------vvv
</code>```

If the positions ^^v, v^^, and vv^ are forbidden, then this graph is reduced to this:

```<code>^^^        ^^v
  \
   \
    \
     \
     ^v^--------^vv
                 |
                 |
v^^        v^v   |
             \   |
              \  |
               \ |
                \|
     vv^        vvv
</code>```

Which already shows the clear way and the breadth-first search will easily find it.  It gets interesting only for many dimensions/switches, though.

Drawing this for more dimensions/switches gets confusing of course (look up tesseracts for 4D).  But it isn't necessary to have a visual image.  Once you have written the algorithm for creating the graph in 2D and 3D in a general way it easily scales to n dimensions/switches without adding any complexity.

Body:
We have a bomb that is ticking and may explode. This bomb has n switches, that can be moved up or down. Certain combinations of these switches trigger the bomb, but only one combination disables it.

Our task is to move the switches from the current position to a position that disables the bomb, without exploding it in the meantime. The switches are big and awkward, so we can move only one switch at a time.

We have, lets say, n = 4 switches currently in position ^vvv. We need to get them to the position ^v^^. Forbidden positions are vvv^, ^vv^, ^v^v, and ^^^v.

a.) I had to draw this by hand and find the shortest sequence of switch movements that solves the task - result I got was 4 ...and I found two such sequences, if i am right...

b.) this is where it gets a hard - write a code that answers the above question/questions (the shortest sequence and how many). The code should be generalized so that it would work with another number of switches and other starting, targeted, and forbidden combinations; targeted and forbidden combinations may be multiple or even fewer. Only thing we know for sure is that the switches have only two positions. It should also provide the possibility that the desired condition is unavailable; in this case, the program should of course tell.

c.) Next questions is the time complexity of the code this but for now I think I will just stop here...

I used '0' and '1' instead, because it is easier for me to imagine this.

So my approach towards this was something of a greedy algorithm (I think) - starting position, you think of all the possible (allowed) positions, you ignore the forbidden ones, then pick the one that the sequence of positions has the fewest difference from our targeting sequence.

The key part of the code I am yet to write and that's the part I need help with.

all_combinations = ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011' , '1100', '1101', '1110', '1111']

def distance (position1, position2):
     distance = 0
     for i in range (len (position1)):
         if position1 [i]! = position2 [i]:
             distance + = 1
     return distance

def allowed_positions (current, all_combinations):
     allowed = set ()
     for combination and all combinations:
         if the distance (current, combination) == 1:
             allowed.add (combination)
     return allowed

def best_name (current, all_combinations, target):
     list = []
     for option and permitted_mood (current, all_combinations):
         list.append (distance (option, target), option)

Body:
The task at hand is finding a shortest path in a graph.  For this there is one typical approach and that is a breadth-first search algorithm (https://en.wikipedia.org/wiki/Breadth-first_search).

There is no real need to go into the details of how this is done because it can be read elsewhere in more detail and far better explained than I can do this in a StackOverflow answer.

But what might need to be explained is how the switch-combinations you have at hand are represented by a graph.

Imagine you have just two switches.  Then you have exactly this graph:

^^---^v
|     |
|     |
v^---vv

If your starting position is ^^ and your ending (defusing) position is vv while the position ^v is an exploding position, then your graph is reduced to this:

^^   ^v
|
|
v^---vv

In this small example the shortest path is obvious and simple.

The graph at hand is easily sketched out in 2D, each dimension (x and y) representing one of the switches.  If you have more switches, then you just add one dimension for each switch.  For three switches this would look like this:

^^^--------^^v
 |\         |\
 | \        | \
 |  \       |  \
 |   \      |   \
 |   ^v^--- | --^vv
 |    |     |    |
 |    |     |    |
v^^--------v^v   |
  \   |      \   |
   \  |       \  |
    \ |        \ |
     \|         \|
     vv^--------vvv

If the positions ^^v, v^^, and vv^ are forbidden, then this graph is reduced to this:

^^^        ^^v
  \
   \
    \
     \
     ^v^--------^vv
                 |
                 |
v^^        v^v   |
             \   |
              \  |
               \ |
                \|
     vv^        vvv

Which already shows the clear way and the breadth-first search will easily find it.  It gets interesting only for many dimensions/switches, though.

Drawing this for more dimensions/switches gets confusing of course (look up tesseracts for 4D).  But it isn't necessary to have a visual image.  Once you have written the algorithm for creating the graph in 2D and 3D in a general way it easily scales to n dimensions/switches without adding any complexity.


问:
Writing different values to different BigQuery tables in Apache Beam
Suppose I have a PCollection<Foo> and I want to write it to multiple BigQuery tables, choosing a potentially different table for each Foo.

How can I do this using the Apache Beam BigQueryIO API?

答:
As of Beam 2.12.0, this feature is available in the Python SDK as well. It is marked as experimental, so you will have to pass --experiments use_beam_bq_sink to enable it. You'd do something like so:

def get_table_name(element):
  if meets_some_condition(element):
    return 'mytablename1'
  else:
    return 'mytablename2'

p = beam.Pipeline(...)

my_input_pcoll = p | ReadInMyPCollection()

my_input_pcoll | beam.io.gcp.bigquery.WriteToBigQuery(table=get_table_name)
```

The new sink supports a number of other options, which you can review in the pydoc

Body:
As of Beam 2.12.0, this feature is available in the Python SDK as well. It is marked as experimental, so you will have to pass --experiments use_beam_bq_sink to enable it. You'd do something like so:

def get_table_name(element):
  if meets_some_condition(element):
    return 'mytablename1'
  else:
    return 'mytablename2'

p = beam.Pipeline(...)

my_input_pcoll = p | ReadInMyPCollection()

my_input_pcoll | beam.io.gcp.bigquery.WriteToBigQuery(table=get_table_name)

The new sink supports a number of other options, which you can review in the pydoc