问:
How to get the total storage of all previous version objects in an S3 bucket
For a version enabled bucket, I would like to see how much storage takes for current version vs. previous version in a s3 bucket. Currently I can only get the total storage size for a bucket including both current version and previous version</p>

答:
Since you wish to retrieve information on the objects in a "huge" bucket, I would recommend using Amazon S3 Inventory, which can provide a daily CSV file containing information about all objects in the bucket.

If your requirement is just one-off, you could turn it off after a day.

The Amazon S3 inventory report says:

You can configure what object metadata to include in the inventory, whether to list all object versions or only current versions, where to store the inventory list file output, and whether to generate the inventory on a daily or weekly basis.


来源: stackexchange

问:
How to iterate through a range of given keys in a nested dictionary
I am iterating through a nested dictionary of stock prices that has the key: dates.

I am having trouble in being able to only get the prices of stocks at start date and end date.

This is a link to the nested dictionary.
https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=TSLA&apikey=IMS80WN3J6S2ILKW

I've been trying a lot of different ways but not able to solve it for past 2 hrs:

```<code>starting_date  = '2020-02-13'
ending_date = '2020-02-11'

#data = the nested dictionary

opening_prices = []
series = data['Time Series (Daily)'] #Now were given the nested dictionary of the keys being dates and value being a dictionary of info: price.
for date in series:
    if date == starting_date:
        for data, price in date.items()
            opening_prices.append(float(price['1. open']))
#we are retrieving the opening prices of the nested dict.
#For this attempt, I get the error of date being str type.
#I still don't know how to stop at the end_date as I tried a while loop, but it failed.
</code>```

答:
```<code>starting_date  = '2020-02-01'
ending_date = '2020-02-13'

#data = the nested dictionary

opening_prices = []
series = data['Time Series (Daily)']
for date in series:
    if date >= starting_date and date <= ending_date:
        opening_price = series[date]['1. open']
        opening_prices.append(float(opening_price))

print(opening_prices)
</code>```

Output

```<code>[741.84, 777.87, 768.79, 800.0, 730.55, 699.92, 823.26, 882.96, 673.69]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am iterating through a nested dictionary of stock prices that has the key: dates.

I am having trouble in being able to only get the prices of stocks at start date and end date.

This is a link to the nested dictionary.
https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=TSLA&apikey=IMS80WN3J6S2ILKW

I've been trying a lot of different ways but not able to solve it for past 2 hrs:

starting_date  = '2020-02-13'
ending_date = '2020-02-11'

#data = the nested dictionary

opening_prices = []
series = data['Time Series (Daily)'] #Now were given the nested dictionary of the keys being dates and value being a dictionary of info: price.
for date in series:
    if date == starting_date:
        for data, price in date.items()
            opening_prices.append(float(price['1. open']))
#we are retrieving the opening prices of the nested dict.
#For this attempt, I get the error of date being str type.
#I still don't know how to stop at the end_date as I tried a while loop, but it failed.

Body:
starting_date  = '2020-02-01'
ending_date = '2020-02-13'

#data = the nested dictionary

opening_prices = []
series = data['Time Series (Daily)']
for date in series:
    if date >= starting_date and date <= ending_date:
        opening_price = series[date]['1. open']
        opening_prices.append(float(opening_price))

print(opening_prices)

Output

[741.84, 777.87, 768.79, 800.0, 730.55, 699.92, 823.26, 882.96, 673.69]


问:
Commited changes into detached Head and moved to master
I commited my changes into detached head and moved to master. Is it possible to checkout the detached head again?</p>

答:
I committed my changes into detached head ...

Technically, you committed (files) while on a detached HEAD or in detached-HEAD mode, rather than "into a detached HEAD".  The important thing, though, is that you did commit.  That's the key.

... and [then] moved to master.

This left the commit you made earlier behind.  That commit, like every commit, has a unique hash ID: a big ugly string of letters and numbers like c7a62075917b3340f908093f63f1161c44ed1475.

Is it possible to checkout the detached head again?

Again, "detached HEAD" is a mode—a way of using Git—not a commit.  The question you need here is: Can I get this commit again somehow?  The answer is yes, but you must find its hash ID, or something that finds its hash ID.

The easiest way to find its hash ID is if it's still on your screen.  If you can scroll back just a bit and see it, you can grab it with your mouse, with cut-and-paste, the way I grabbed the hash ID I quoted above.  Hash IDs are too big and ugly for humans to type in correctly, which is why we don't use them, but they're Git's "true name" for each commit, which is why Git does use (and need) them.

Normally, we have Git store them for us.  Just like using cut-and-paste, we don't try to type them in at all: we just tell Git using a name like master, find me a commit hash ID and do something with that commit.  But if you didn't, well, there are several ways to find it.

I already mentioned the scroll-back-and-look-at-your-screen method.  Another one is to use what Git calls reflogs.  Every time you check out some commit, whether by branch name, or tag name, or hash ID, and every time you make a new commit, so that there is a new unique hash ID in your repository, Git saves this hash ID as an entry in the reflog for the name HEAD.  Run:

```<code>git reflog
</code>```

to have Git print out the entire log, one line at a time.  You will get output similar to this:

```<code>$ git reflog
c7a6207591 (HEAD -> master, origin/master, origin/HEAD) HEAD@{0}: reset: moving to HEAD
c7a6207591 (HEAD -> master, origin/master, origin/HEAD) HEAD@{1}: merge refs/remotes/origin/master: Fast-forward
083378cc35 HEAD@{2}: checkout: moving from 1d2375ddfee18bd3effd2c1f98527cc2f8b1df0a to master
</code>```

The leftmost string is an abbreviated hash ID.  Note that c7a6...(something), for instance, starts with the same letters and numbers as the hash ID I pasted near the top of this answer (c7a62...(something)).  An abbreviated hash ID is almost1 as good as the full hash ID.  Or, you can use the HEAD@{number} string, but remember: every time you run git checkout or git commit, all the numbers go up by one, because Git just added another entry to the log.2

Once you find the hash ID, or a shortened version of it or a name like HEAD@{2}, you can run:

```<code>git checkout <hash>       # or git checkout HEAD@{2}
</code>```

and you'll be in "detached HEAD" mode again, at that commit.  You can now create a branch or tag name to have Git remember the hash ID for you.

If you're not sure which commit is which, run git reflog to see the hash IDs (and HEAD@{...} names) and then run:

```<code>git log <hash-id>       # or git log HEAD@{3} or whatever
</code>```

and git log will show you that commit, and its predecessor commits, as usual.  Use git show hash-id or git show HEAD@{number} to show that commit in detail.

1It falls short when it, well, falls short: the full hash ID definitely matches the actual hash ID, but a shortened one might match two or more hash IDs.  For instance, if we shorten c7a6...something to just c, that would match c10b...something too.  Git has a minimum of 4 characters for a shortened hash ID, and usually starts at out 7 and as the repository grows, starts adding more characters to hope that the shortened ID is always sufficient.

2Periodically, Git will clean out the reflogs.  There's one reflog for each ref: a branch name, or a tag name, or any other such name is a ref or reference.  Each holds one hash ID.  The branch names hold a hash ID that changes over time, while your tag names should never change.

Reflog entries generally last for at least 30 days by default, and at least 90 days by default in most cases.  So after you "lose" a commit, you can usually get it back for at least a month.  You can explicitly enable or disable reflogs in your own repository, but usually the default—enabled, for you—is right.  Server-side repositories as stored on commercial servers like GitHub usually don't have reflogs enabled, so that there's no 30-day grace period there.

Body:
I committed my changes into detached head ...

Technically, you committed (files) while on a detached HEAD or in detached-HEAD mode, rather than "into a detached HEAD".  The important thing, though, is that you did commit.  That's the key.

... and [then] moved to master.

This left the commit you made earlier behind.  That commit, like every commit, has a unique hash ID: a big ugly string of letters and numbers like c7a62075917b3340f908093f63f1161c44ed1475.

Is it possible to checkout the detached head again?

Again, "detached HEAD" is a mode—a way of using Git—not a commit.  The question you need here is: Can I get this commit again somehow?  The answer is yes, but you must find its hash ID, or something that finds its hash ID.

The easiest way to find its hash ID is if it's still on your screen.  If you can scroll back just a bit and see it, you can grab it with your mouse, with cut-and-paste, the way I grabbed the hash ID I quoted above.  Hash IDs are too big and ugly for humans to type in correctly, which is why we don't use them, but they're Git's "true name" for each commit, which is why Git does use (and need) them.

Normally, we have Git store them for us.  Just like using cut-and-paste, we don't try to type them in at all: we just tell Git using a name like master, find me a commit hash ID and do something with that commit.  But if you didn't, well, there are several ways to find it.

I already mentioned the scroll-back-and-look-at-your-screen method.  Another one is to use what Git calls reflogs.  Every time you check out some commit, whether by branch name, or tag name, or hash ID, and every time you make a new commit, so that there is a new unique hash ID in your repository, Git saves this hash ID as an entry in the reflog for the name HEAD.  Run:

git reflog

to have Git print out the entire log, one line at a time.  You will get output similar to this:

$ git reflog
c7a6207591 (HEAD -> master, origin/master, origin/HEAD) HEAD@{0}: reset: moving to HEAD
c7a6207591 (HEAD -> master, origin/master, origin/HEAD) HEAD@{1}: merge refs/remotes/origin/master: Fast-forward
083378cc35 HEAD@{2}: checkout: moving from 1d2375ddfee18bd3effd2c1f98527cc2f8b1df0a to master

The leftmost string is an abbreviated hash ID.  Note that c7a6...(something), for instance, starts with the same letters and numbers as the hash ID I pasted near the top of this answer (c7a62...(something)).  An abbreviated hash ID is almost1 as good as the full hash ID.  Or, you can use the HEAD@{number} string, but remember: every time you run git checkout or git commit, all the numbers go up by one, because Git just added another entry to the log.2

Once you find the hash ID, or a shortened version of it or a name like HEAD@{2}, you can run:

git checkout <hash>       # or git checkout HEAD@{2}

and you'll be in "detached HEAD" mode again, at that commit.  You can now create a branch or tag name to have Git remember the hash ID for you.

If you're not sure which commit is which, run git reflog to see the hash IDs (and HEAD@{...} names) and then run:

git log <hash-id>       # or git log HEAD@{3} or whatever

and git log will show you that commit, and its predecessor commits, as usual.  Use git show hash-id or git show HEAD@{number} to show that commit in detail.

1It falls short when it, well, falls short: the full hash ID definitely matches the actual hash ID, but a shortened one might match two or more hash IDs.  For instance, if we shorten c7a6...something to just c, that would match c10b...something too.  Git has a minimum of 4 characters for a shortened hash ID, and usually starts at out 7 and as the repository grows, starts adding more characters to hope that the shortened ID is always sufficient.

2Periodically, Git will clean out the reflogs.  There's one reflog for each ref: a branch name, or a tag name, or any other such name is a ref or reference.  Each holds one hash ID.  The branch names hold a hash ID that changes over time, while your tag names should never change.

Reflog entries generally last for at least 30 days by default, and at least 90 days by default in most cases.  So after you "lose" a commit, you can usually get it back for at least a month.  You can explicitly enable or disable reflogs in your own repository, but usually the default—enabled, for you—is right.  Server-side repositories as stored on commercial servers like GitHub usually don't have reflogs enabled, so that there's no 30-day grace period there.


问:
How to convert text files in a folder into a CSV file
I am trying to write a script to take a bunch of text files in a folder (which are all in the same format) and output them to a csv file. Each file has the same "header" information. I have been able to get information in a more easily usable format (removing the first and last lines, which aren't needed), but am having some trouble after that.

Here is the beginning of the text file, though there will be more than just these 7 lines, there will be a total of 36 lines per file:

```<code>TYPE       VOID
DOB        20200131
DATE       20200131
TIME       21:19:42
TERMINAL   3
ORGTERM    2
EMPLOYEE   1234 John Doe
</code>```

And here is what I have so far, though I know that it doesn't work:

```<code>$currentdir = '.\'
$results = @()
$outputfilename = 'data.csv'

foreach ($req in Get-ChildItem($currentdir)) {

(Get-Content $req)[1..((Get-Content $req).count - 2)] |
    ForEach-Object {
        $header = $_[0] -split '`t'
        $data = $_[1] -split '`t'
        $results = $header, $data
    }
}
</code>```

The final product would look something like this:

```<code>       A               B            C            D          E            F             G
1     TYPE            DOB          DATE         TIME     TERMINAL     ORGTERM       EMPLOYEE
2     VOID          20200131     20200131     21:19:42      3            2          1234 John Doe
3     AUTHORIZE     20200131     20200131     23:29:22      2                       4678 Jane Doe
</code>```

Full sample of VOID file:

```<code>BEGIN
TYPE       VOID
DOB        20200131
DATE       20200131
TIME       21:19:42
TERMINAL   3
ORGTERM    2
EMPLOYEE   1234 Jane Doe
TABLE      TBL 101
CHECK      20030
PAYMENT    20029
AUTHAMT    20.68
BATCHAMT   20.68
CARDTYPE   MASTERCARD
CARDMASK   XXXXXXXXXXXXXXXXX
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0423
REF        482
STANDALONE YES
PINDEX     1
APPROVEAMT 20.68
LOGTIME    21:07:01
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
ACTIONCODE 000
LASTSEND   1580585993
ORIGDATE   20200131
ORIGTIME   21:02:11
ORIGTYPE   AUTHORIZE
ORIGREF    482
ORGREFTIME 21:02:11
TENDER_NUM 12
CRCY       840
VPD        Sequence #: 107
REVID      2
REVNAME    712 Bar
END
</code>```

Sample AUTHORIZE file:

```<code>BEGIN
TYPE       AUTHORIZE
DOB        20200131
DATE       20200131
TIME       23:29:22
TERMINAL   2
EMPLOYEE   1234 Jane Doe
TABLE      Table 121
CHECK      20045
PAYMENT    20038
AUTHAMT    72.42
BATCHAMT   72.42
CARDTYPE   VISA
CARDMASK   XXXXXXXXXXXXXXXX
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0124
REF        485900
STANDALONE YES
PINDEX     1
LOGTIME    23:29:22
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
LASTSEND   1580586235
TENDER_NUM 13
CRCY       840
REVID      1
REVNAME    712 Restaurant
COMMERROR  TRUE
END
</code>```

Sample adjust file:

```<code>BEGIN
TYPE       ADJUST
DOB        20200131
DATE       20200131
TIME       22:18:27
TERMINAL   8
ORGTERM    8
EMPLOYEE   789 Judy Garland
TABLE      BAR GUEST
CHECK      80161
PAYMENT    80036
BATCHAMT   30.43
BATCHTIP   6
CARDTYPE   MASTERCARD
CARDMASK   XXXXXXXXXXXX8699
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0323
REF        1504602
STANDALONE YES
PINDEX     1
LOGTIME    22:18:27
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
LASTSEND   1580638928
TENDER_NUM 12
CRCY       840
REVID      4
REVNAME    712 Second Bar
END
</code>```

答:
here's one way to merge those text files into a CSV. it presumes the files are in a specific dir and can be loaded by matching the names OR by simply grabbing all the files.

what it does ...

sets the source dir

sets the file filter

grabs all the matching files

iterates thru the file list

loads each file into a $Var

uses the way that PoSh handles a collection on the LEFT side of a match

that gives you the matching item, not the usual [bool].

builds a PSCustomObject

it does that by matching the line with the target word, getting the 1st item in the returned array, replaces the unwanted part of the line with nothing, and finally assigns that value to the desired property.

this is rather inefficient, but i can't think of a better way. [blush]

sends the PSCO out to the $Results collection

shows what is in $Results on the screen

exports $Results to a CSV file

here's the code ...

```<code>$SourceDir = $env:TEMP
$Filter = 'harlan_*.txt'

$FileList = Get-ChildItem -LiteralPath $SourceDir -Filter $Filter -File

$Results = foreach ($FL_Item in $FileList)
    {
    $Lines = Get-Content -LiteralPath $FL_Item.FullName
    [PSCustomObject]@{
        Type = ($Lines -match '^type')[0] -replace '^type\s{1,}'
        DOB = ($Lines -match '^dob')[0] -replace '^dob\s{1,}'
        Date = ($Lines -match '^date')[0] -replace '^date\s{1,}'
        Time = ($Lines -match '^time')[0] -replace '^time\s{1,}'
        Terminal = ($Lines -match '^terminal')[0] -replace '^terminal\s{1,}'
        OrgTerm = ($Lines -match '^orgterm')[0] -replace '^orgterm\s{1,}'
        Employee = ($Lines -match '^employee')[0] -replace '^employee\s{1,}'
        }
    }

# show on screen
$Results

# save to CSV
$Results |
    Export-Csv -LiteralPath "$SourceDir\Harlan_-_MergedFiles.csv" -NoTypeInformation
</code>```

display on screen ...

```<code>Type     : ADJUST
DOB      : 20200131
Date     : 20200131
Time     : 22:18:27
Terminal : 8
OrgTerm  : 8
Employee : 789 Judy Garland

Type     : AUTHORIZE
DOB      : 20200131
Date     : 20200131
Time     : 23:29:22
Terminal : 2
OrgTerm  :
Employee : 1234 Jane Doe

Type     : VOID
DOB      : 20200131
Date     : 20200131
Time     : 21:19:42
Terminal : 3
OrgTerm  : 2
Employee : 1234 Jane Doe
</code>```

content of the csv file ...

```<code>"Type","DOB","Date","Time","Terminal","OrgTerm","Employee"
"ADJUST","20200131","20200131","22:18:27","8","8","789 Judy Garland"
"AUTHORIZE","20200131","20200131","23:29:22","2","","1234 Jane Doe"
"VOID","20200131","20200131","21:19:42","3","2","1234 Jane Doe"
</code>```

Body:
I am trying to write a script to take a bunch of text files in a folder (which are all in the same format) and output them to a csv file. Each file has the same "header" information. I have been able to get information in a more easily usable format (removing the first and last lines, which aren't needed), but am having some trouble after that.

Here is the beginning of the text file, though there will be more than just these 7 lines, there will be a total of 36 lines per file:

TYPE       VOID
DOB        20200131
DATE       20200131
TIME       21:19:42
TERMINAL   3
ORGTERM    2
EMPLOYEE   1234 John Doe

And here is what I have so far, though I know that it doesn't work:

$currentdir = '.\'
$results = @()
$outputfilename = 'data.csv'

foreach ($req in Get-ChildItem($currentdir)) {

(Get-Content $req)[1..((Get-Content $req).count - 2)] |
    ForEach-Object {
        $header = $_[0] -split '`t'
        $data = $_[1] -split '`t'
        $results = $header, $data
    }
}

The final product would look something like this:

       A               B            C            D          E            F             G
1     TYPE            DOB          DATE         TIME     TERMINAL     ORGTERM       EMPLOYEE
2     VOID          20200131     20200131     21:19:42      3            2          1234 John Doe
3     AUTHORIZE     20200131     20200131     23:29:22      2                       4678 Jane Doe

Full sample of VOID file:

BEGIN
TYPE       VOID
DOB        20200131
DATE       20200131
TIME       21:19:42
TERMINAL   3
ORGTERM    2
EMPLOYEE   1234 Jane Doe
TABLE      TBL 101
CHECK      20030
PAYMENT    20029
AUTHAMT    20.68
BATCHAMT   20.68
CARDTYPE   MASTERCARD
CARDMASK   XXXXXXXXXXXXXXXXX
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0423
REF        482
STANDALONE YES
PINDEX     1
APPROVEAMT 20.68
LOGTIME    21:07:01
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
ACTIONCODE 000
LASTSEND   1580585993
ORIGDATE   20200131
ORIGTIME   21:02:11
ORIGTYPE   AUTHORIZE
ORIGREF    482
ORGREFTIME 21:02:11
TENDER_NUM 12
CRCY       840
VPD        Sequence #: 107
REVID      2
REVNAME    712 Bar
END

Sample AUTHORIZE file:

BEGIN
TYPE       AUTHORIZE
DOB        20200131
DATE       20200131
TIME       23:29:22
TERMINAL   2
EMPLOYEE   1234 Jane Doe
TABLE      Table 121
CHECK      20045
PAYMENT    20038
AUTHAMT    72.42
BATCHAMT   72.42
CARDTYPE   VISA
CARDMASK   XXXXXXXXXXXXXXXX
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0124
REF        485900
STANDALONE YES
PINDEX     1
LOGTIME    23:29:22
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
LASTSEND   1580586235
TENDER_NUM 13
CRCY       840
REVID      1
REVNAME    712 Restaurant
COMMERROR  TRUE
END

Sample adjust file:

BEGIN
TYPE       ADJUST
DOB        20200131
DATE       20200131
TIME       22:18:27
TERMINAL   8
ORGTERM    8
EMPLOYEE   789 Judy Garland
TABLE      BAR GUEST
CHECK      80161
PAYMENT    80036
BATCHAMT   30.43
BATCHTIP   6
CARDTYPE   MASTERCARD
CARDMASK   XXXXXXXXXXXX8699
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0323
REF        1504602
STANDALONE YES
PINDEX     1
LOGTIME    22:18:27
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
LASTSEND   1580638928
TENDER_NUM 12
CRCY       840
REVID      4
REVNAME    712 Second Bar
END

Body:
here's one way to merge those text files into a CSV. it presumes the files are in a specific dir and can be loaded by matching the names OR by simply grabbing all the files.

what it does ...

sets the source dir

sets the file filter

grabs all the matching files

iterates thru the file list

loads each file into a $Var

uses the way that PoSh handles a collection on the LEFT side of a match

that gives you the matching item, not the usual [bool].

builds a PSCustomObject

it does that by matching the line with the target word, getting the 1st item in the returned array, replaces the unwanted part of the line with nothing, and finally assigns that value to the desired property.

this is rather inefficient, but i can't think of a better way. [blush]

sends the PSCO out to the $Results collection

shows what is in $Results on the screen

exports $Results to a CSV file

here's the code ...

$SourceDir = $env:TEMP
$Filter = 'harlan_*.txt'

$FileList = Get-ChildItem -LiteralPath $SourceDir -Filter $Filter -File

$Results = foreach ($FL_Item in $FileList)
    {
    $Lines = Get-Content -LiteralPath $FL_Item.FullName
    [PSCustomObject]@{
        Type = ($Lines -match '^type')[0] -replace '^type\s{1,}'
        DOB = ($Lines -match '^dob')[0] -replace '^dob\s{1,}'
        Date = ($Lines -match '^date')[0] -replace '^date\s{1,}'
        Time = ($Lines -match '^time')[0] -replace '^time\s{1,}'
        Terminal = ($Lines -match '^terminal')[0] -replace '^terminal\s{1,}'
        OrgTerm = ($Lines -match '^orgterm')[0] -replace '^orgterm\s{1,}'
        Employee = ($Lines -match '^employee')[0] -replace '^employee\s{1,}'
        }
    }

# show on screen
$Results

# save to CSV
$Results |
    Export-Csv -LiteralPath "$SourceDir\Harlan_-_MergedFiles.csv" -NoTypeInformation

display on screen ...

Type     : ADJUST
DOB      : 20200131
Date     : 20200131
Time     : 22:18:27
Terminal : 8
OrgTerm  : 8
Employee : 789 Judy Garland

Type     : AUTHORIZE
DOB      : 20200131
Date     : 20200131
Time     : 23:29:22
Terminal : 2
OrgTerm  :
Employee : 1234 Jane Doe

Type     : VOID
DOB      : 20200131
Date     : 20200131
Time     : 21:19:42
Terminal : 3
OrgTerm  : 2
Employee : 1234 Jane Doe

content of the csv file ...

"Type","DOB","Date","Time","Terminal","OrgTerm","Employee"
"ADJUST","20200131","20200131","22:18:27","8","8","789 Judy Garland"
"AUTHORIZE","20200131","20200131","23:29:22","2","","1234 Jane Doe"
"VOID","20200131","20200131","21:19:42","3","2","1234 Jane Doe"


问:
Laravel: querying for all records with a timestamp from today
I have an Orders table that has a field scan_date in unix timecode.  I am trying to get all Orders with a scan_date WITHIN the current day.  I was originally using whereBetween() to grab orders within the last 24 hours of whenever it's run but I realized that's not doing exactly what I need.

```<code>->whereBetween('scan_date', [Carbon::now()->addDays(-1), Carbon::now()])
</code>```

If an order has a scan_date between 12:01AM and 11:59pm on the current day, I want to grab all those orders -- is this possible to query for?

答:
You can use whereDate, on Laravel < 5.7 you should format the date to Y-m-d before passing it:

->whereDate('scan_date', Carbon::now()->toDateString())
```

<p>On Laravel >= 5.7 you can pass an instance of <code>DateTimeInterface</code> directly:</p>

<pre class="lang-php prettyprint-override"><code>->whereDate('scan_date', Carbon::now())
</code>```

Body:
I have an Orders table that has a field scan_date in unix timecode.  I am trying to get all Orders with a scan_date WITHIN the current day.  I was originally using whereBetween() to grab orders within the last 24 hours of whenever it's run but I realized that's not doing exactly what I need.

->whereBetween('scan_date', [Carbon::now()->addDays(-1), Carbon::now()])

If an order has a scan_date between 12:01AM and 11:59pm on the current day, I want to grab all those orders -- is this possible to query for?

Body:
You can use whereDate, on Laravel < 5.7 you should format the date to Y-m-d before passing it:

->whereDate('scan_date', Carbon::now()->toDateString())

On Laravel >= 5.7 you can pass an instance of DateTimeInterface directly:

->whereDate('scan_date', Carbon::now())


问:
Why would a character array be unchanged after a for-loop?
I have built a function with the goal of taking text that is fed from elsewhere in the program and removing all whitespace and punctuation from it. I'm able to remove whitespace and punctuation, but the changes don't stay after they are made. For instance, I put the character array/string into a for-loop to remove whitespace and verify that the whitespace is removed by printing the current string to the screen. When I send the string through a loop to remove punctuation, though, it acts as though I did not remove whitespace from earlier. This is an example of what I'm talking about:

Example of output to screen

The function that I'm using is here.

```<code>//eliminates all punctuation, capital letters, and whitespace in plaintext
char *formatPlainText(char *plainText) {
    int length = strlen(plainText);

    //turn capital letters into lower case letters
    for (int i = 0; i < length; i++)
        plainText[i] = tolower(plainText[i]);

    //remove whitespace
    for (int i = 0; i < length; i++) {
        if (plainText[i] == ' ')
            plainText[i] = plainText[i++];

        printf("%c", plainText[i]);
    }
    printf("\n\n");

    //remove punctuation from text
    for (int i = 0; i < length; i++) {
        if (ispunct(plainText[i]))
            plainText[i] = plainText[i++];

        printf("%c", plainText[i]);
    }
}
</code>```

Any help as to why the text is unchanged after if exits the loop would be appreciated.

答:
Those for loops are not necessary. Your function can be modified as follows and I commented where I made those changes:

```<code>char* formatPlainText(char *plainText)
{
     char *dest = plainText; //dest to hold the modified version of plainText
     while ( *plainText ) // as far as *plainText is not '\0'
     {
         int k = tolower(*plainText);
         if( !ispunct(k) && k != ' ')     // check each char for ' ' and any punctuation mark
           *dest++ = tolower(*plainText);  // place the lower case of *plainText to *dest and increment dest
         plainText++;
      }

    *dest = '\0';   // This is important because in the while loop we escape it
     return dest;
}
</code>```

From main:

```<code>int main( void ){
  char str[] = "Practice ????? &&!!! makes ??progress!!!!!";
  char * res = formatPlainText(str);
  printf("%s \n", str);
}
</code>```

Body:
I have built a function with the goal of taking text that is fed from elsewhere in the program and removing all whitespace and punctuation from it. I'm able to remove whitespace and punctuation, but the changes don't stay after they are made. For instance, I put the character array/string into a for-loop to remove whitespace and verify that the whitespace is removed by printing the current string to the screen. When I send the string through a loop to remove punctuation, though, it acts as though I did not remove whitespace from earlier. This is an example of what I'm talking about:

Example of output to screen

The function that I'm using is here.

//eliminates all punctuation, capital letters, and whitespace in plaintext
char *formatPlainText(char *plainText) {
    int length = strlen(plainText);

    //turn capital letters into lower case letters
    for (int i = 0; i < length; i++)
        plainText[i] = tolower(plainText[i]);

    //remove whitespace
    for (int i = 0; i < length; i++) {
        if (plainText[i] == ' ')
            plainText[i] = plainText[i++];

        printf("%c", plainText[i]);
    }
    printf("\n\n");

    //remove punctuation from text
    for (int i = 0; i < length; i++) {
        if (ispunct(plainText[i]))
            plainText[i] = plainText[i++];

        printf("%c", plainText[i]);
    }
}

Any help as to why the text is unchanged after if exits the loop would be appreciated.

Body:
Those for loops are not necessary. Your function can be modified as follows and I commented where I made those changes:

char* formatPlainText(char *plainText)
{
     char *dest = plainText; //dest to hold the modified version of plainText
     while ( *plainText ) // as far as *plainText is not '\0'
     {
         int k = tolower(*plainText);
         if( !ispunct(k) && k != ' ')     // check each char for ' ' and any punctuation mark
           *dest++ = tolower(*plainText);  // place the lower case of *plainText to *dest and increment dest
         plainText++;
      }

    *dest = '\0';   // This is important because in the while loop we escape it
     return dest;
}

From main:

int main( void ){
  char str[] = "Practice ????? &&!!! makes ??progress!!!!!";
  char * res = formatPlainText(str);
  printf("%s \n", str);
}


问:
How can I export all functions from a file in JS?
I'm creating a unit converter, and I want to put all of the conversion functions into their own file. Using ES6 export, is there any way to export all of the functions in the file with their default names using only one line? For example:

export default all;

The functions are all just in the file, not within an object.

答:
You can also use module.exports as follows:

```<code>function myFunction(arg) {
  console.debug(arg);
}
function otherFunction(arg) {
  console.error(arg);
}

module.exports = {
  myFunction: myFunction,
  otherFunction: otherFunction,
};
</code>```

Then you can import it:

```<code>import {myFunction, otherFunction} from "./Functions.js";
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can also use module.exports as follows:

function myFunction(arg) {
  console.debug(arg);
}
function otherFunction(arg) {
  console.error(arg);
}

module.exports = {
  myFunction: myFunction,
  otherFunction: otherFunction,
};

Then you can import it:

import {myFunction, otherFunction} from "./Functions.js";


问:
Testing empty list [] with Eq type
Currently, I am writing a function in Haskell to check a list is symmetric or not.

```<code>isReflexive :: Eq a => [(a, a)] -> Bool
isReflexive [] = True
isReflexive xs = and [elem (x, x) xs | x <- [fst u | u <- xs] ++ [snd u | u <- xs]]

test = do
    print(isReflexive [])

main = test
</code>```

The function works fine on the list that is not empty. However, when I test the empty list with the function, it raised an error

Ambiguous type variable ‘a2’ arising from a use of ‘isReflexive’ prevents the constraint ‘(Eq a2)’ from being solved.

Probable fix: use a type annotation to specify what ‘a2’ should be.

These potential instances exist:

instance Eq Ordering -- Defined in ‘GHC.Classes’

instance Eq Integer  -- Defined in ‘integer-gmp-1.0.2.0:GHC.Integer.Type’

instance Eq a => Eq (Maybe a) -- Defined in ‘GHC.Maybe’
  ...plus 22 others

...plus 7 instances involving out-of-scope types

(use -fprint-potential-instances to see them all)

• In the first argument of ‘print’, namely ‘(isReflexive [])’
  How to fix this error?

答:
The problem is simply that, in order to apply isReflexive, GHC needs to know which type you are using it on.

The type signature of isReflexive - Eq a => [(a, a)] -> Bool doesn't tell GHC a concrete type that the function works on. That's perfectly fine, and usual, but most often the code that calls the function makes it clear what exactly a is in that particular application. That's not so here, because [] has itself a polymorphic (and therefore ambiguous) type, [a] (for any a).

To fix it you simply have to provide a concrete type for your [] here, which is consistent with the signature of isReflexive. It really doesn't matter what, but an example from many that will work is:

```<code>test = do
    print(isReflexive ([] :: [(Int, Int)]))
</code>```

(Note that this is exactly what GHC is telling you when it says Probable fix: use a type annotation to specify what 'a2' should be. 'a2' in that message corresponds to 'a' here, GHC tends to use 'a1', 'a2' etc to refer to all type variables.)

Title: Testing empty list [] with Eq type

Body:
Currently, I am writing a function in Haskell to check a list is symmetric or not.

isReflexive :: Eq a => [(a, a)] -> Bool
isReflexive [] = True
isReflexive xs = and [elem (x, x) xs | x <- [fst u | u <- xs] ++ [snd u | u <- xs]]

test = do
    print(isReflexive [])

main = test

The function works fine on the list that is not empty. However, when I test the empty list with the function, it raised an error

Ambiguous type variable ‘a2’ arising from a use of ‘isReflexive’ prevents the constraint ‘(Eq a2)’ from being solved.

Probable fix: use a type annotation to specify what ‘a2’ should be.

These potential instances exist:

instance Eq Ordering -- Defined in ‘GHC.Classes’

instance Eq Integer  -- Defined in ‘integer-gmp-1.0.2.0:GHC.Integer.Type’

instance Eq a => Eq (Maybe a) -- Defined in ‘GHC.Maybe’
  ...plus 22 others

...plus 7 instances involving out-of-scope types

(use -fprint-potential-instances to see them all)

• In the first argument of ‘print’, namely ‘(isReflexive [])’
  How to fix this error?

Body:
The problem is simply that, in order to apply isReflexive, GHC needs to know which type you are using it on.

The type signature of isReflexive - Eq a => [(a, a)] -> Bool doesn't tell GHC a concrete type that the function works on. That's perfectly fine, and usual, but most often the code that calls the function makes it clear what exactly a is in that particular application. That's not so here, because [] has itself a polymorphic (and therefore ambiguous) type, [a] (for any a).

To fix it you simply have to provide a concrete type for your [] here, which is consistent with the signature of isReflexive. It really doesn't matter what, but an example from many that will work is:

test = do
    print(isReflexive ([] :: [(Int, Int)]))

(Note that this is exactly what GHC is telling you when it says Probable fix: use a type annotation to specify what 'a2' should be. 'a2' in that message corresponds to 'a' here, GHC tends to use 'a1', 'a2' etc to refer to all type variables.)


问:
Custom TableView Cell Indentation Issue
I created a custom UITableViewCell in my app and the default indent when the Delete button is present is not happening, below is a screenshot of my settings. Anyone have any idea as to what I'm doing wrong?

Also, here's a shot of the IB properties:

答:
should happen by default, but in your UITableViewDelegate override

```<code>- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath{
     return YES;
}
</code>```

make sure you aren't doing anything strange in:

```<code>- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
</code>```

and that you are setting the cell's editingAccessoryType to UITableViewCellEditingStyleDelete or UITableViewCellEditingStyleInsert

and that you aren't returning No from :

```<code>- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
</code>```

ContentLicense: CC BY-SA 2.5

Title: Custom TableView Cell Indentation Issue

Body:
should happen by default, but in your UITableViewDelegate override

- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath{
     return YES;
}

make sure you aren't doing anything strange in:

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath

and that you are setting the cell's editingAccessoryType to UITableViewCellEditingStyleDelete or UITableViewCellEditingStyleInsert

and that you aren't returning No from :

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath


问:
Pandas multiple conditions groupby
How can i achieve to groupby multiple conditions. example:

column CL rows == a,b,c groupby column A & C .[TOTAL].min() and column CL rows == rows d,e,f groupby B [TOTAL].min()

```<code>CL  | A | B | C | TOTAL
a   | 1 | 6 | 5 | 125,000
b   | 2 | 5 | 5 | 140,000
c   | 3 | 4 | 5 | 148,000
d   | 4 | 3 | 6 | 125,000
e   | 5 | 2 | 6 | 136,000
f   | 6 | 1 | 6 | 156,000
</code>```

答:
I ended up resolving by adding an extra column 'test' with the following code:

```<code>z['test'] = np.where(z['ACTIVITY_PHASE'].isin(['FRAC','COIL']), z['TOTAL'],
                (np.where(z['ACTIVITY_PHASE']=='PREW', z.groupby(z['ACTIVITY_PHASE']=='PREW')['TOTAL'].transform('min'),
                (np.where(z['ACTIVITY_PHASE']=='WINF', z.groupby(z['ACTIVITY_PHASE']=='WINF')['TOTAL'].transform('min'),
                (np.where(z['ACTIVITY_PHASE']=='WOR', z.groupby(z['ACTIVITY_PHASE']=='WOR')['TOTAL'].transform('min'), 0)))))))
</code>```

Title: Pandas multiple conditions groupby

Body:
How can i achieve to groupby multiple conditions. example:

column CL rows == a,b,c groupby column A & C .[TOTAL].min() and column CL rows == rows d,e,f groupby B [TOTAL].min()

CL  | A | B | C | TOTAL
a   | 1 | 6 | 5 | 125,000
b   | 2 | 5 | 5 | 140,000
c   | 3 | 4 | 5 | 148,000
d   | 4 | 3 | 6 | 125,000
e   | 5 | 2 | 6 | 136,000
f   | 6 | 1 | 6 | 156,000

Body:
I ended up resolving by adding an extra column 'test' with the following code:

z['test'] = np.where(z['ACTIVITY_PHASE'].isin(['FRAC','COIL']), z['TOTAL'],
                (np.where(z['ACTIVITY_PHASE']=='PREW', z.groupby(z['ACTIVITY_PHASE']=='PREW')['TOTAL'].transform('min'),
                (np.where(z['ACTIVITY_PHASE']=='WINF', z.groupby(z['ACTIVITY_PHASE']=='WINF')['TOTAL'].transform('min'),
                (np.where(z['ACTIVITY_PHASE']=='WOR', z.groupby(z['ACTIVITY_PHASE']=='WOR')['TOTAL'].transform('min'), 0)))))))


问:
Removing loading package message in R
I am using the following packages in my R script:

```<code>library(uba)
library(performanceEstimation)
library(UBL)
library(DMwR)

</code>```

These packages always issue the message: 'loading package xyz'. If I don't suppress the 'loading package' messages as I am doing below:

```<code>suppressPackageStartupMessages(library(operators))
suppressPackageStartupMessages(library(class))
suppressPackageStartupMessages(library(fields))
suppressPackageStartupMessages(library(spam))
suppressPackageStartupMessages(library(dotCall64))
suppressPackageStartupMessages(library(grid))
suppressPackageStartupMessages(library(DMwR))
suppressPackageStartupMessages(library(uba))
suppressPackageStartupMessages(library(UBL))
suppressPackageStartupMessages(library(MBA))
suppressPackageStartupMessages(library(gstat))
suppressPackageStartupMessages(library(automap))
suppressPackageStartupMessages(library(sp))
suppressPackageStartupMessages(library(randomForest))

library(uba)  # util used below
library(performanceEstimation)
library(UBL)
library(DMwR)

</code>```

I get the following messages in my console:

```<code>Loading required package: operators

Attaching package: 'operators'

The following objects are masked from 'package:base':

    options, strrep

Loading required package: class
Loading required package: fields
Loading required package: spam
Loading required package: dotCall64
Loading required package: grid
Spam version 2.5-1 (2019-12-12) is loaded.
Type 'help( Spam)' or 'demo( spam)' for a short introduction
and overview of this package.
Help for individual functions is also obtained by adding the
suffix '.spam' to the function name, e.g. 'help( chol.spam)'.

Attaching package: 'spam'

The following objects are masked from 'package:base':

    backsolve, forwardsolve

Loading required package: maps
See https://github.com/NCAR/Fields for
 an extensive vignette, other supplements and source code
Loading required package: ROCR
Loading required package: gplots

Attaching package: 'gplots'

The following object is masked from 'package:stats':

    lowess

Loading required package: DMwR
Loading required package: lattice
Registered S3 method overwritten by 'quantmod':
  method            from
  as.zoo.data.frame zoo

Attaching package: 'DMwR'

The following object is masked from 'package:fields':

    unscale

Attaching package: 'uba'

The following object is masked from 'package:base':

    subset

Loading required package: MBA
Loading required package: gstat
Loading required package: automap
Loading required package: sp
Loading required package: randomForest
randomForest 4.6-14
Type rfNews() to see new features/changes/bug fixes.

Attaching package: 'UBL'

The following objects are masked from 'package:uba':

    phi, phi.control
</code>```

Is there a way to suppress messages in any other way ? I might be using these packages in many other R scripts and I don't want to do this each time.

答:
One way is to write a simple function, that takes in a vector of packages and suppresses the output in a way you want, as examplified below.

```<code>library_suppress <- function(packages, character.only = TRUE, ...){
    for(i in seq_along(packages))
        suppressPackageStartupMessages(
            library(packages[i], character.only = character.only, ...)
        )
}
packages <- c('operators', 'class', 'fields', 'spam', 'dotCall64', 'grid', 'MBA', 'gstat', 'automap', 'sp', 'randomForest')
library_suppress(packages)
</code>```

Note this does not suppress warning messages.

Title: Removing loading package message in R

Body:
I am using the following packages in my R script:

library(uba)
library(performanceEstimation)
library(UBL)
library(DMwR)

These packages always issue the message: 'loading package xyz'. If I don't suppress the 'loading package' messages as I am doing below:

suppressPackageStartupMessages(library(operators))
suppressPackageStartupMessages(library(class))
suppressPackageStartupMessages(library(fields))
suppressPackageStartupMessages(library(spam))
suppressPackageStartupMessages(library(dotCall64))
suppressPackageStartupMessages(library(grid))
suppressPackageStartupMessages(library(DMwR))
suppressPackageStartupMessages(library(uba))
suppressPackageStartupMessages(library(UBL))
suppressPackageStartupMessages(library(MBA))
suppressPackageStartupMessages(library(gstat))
suppressPackageStartupMessages(library(automap))
suppressPackageStartupMessages(library(sp))
suppressPackageStartupMessages(library(randomForest))

library(uba)  # util used below
library(performanceEstimation)
library(UBL)
library(DMwR)

I get the following messages in my console:

Loading required package: operators

Attaching package: 'operators'

The following objects are masked from 'package:base':

    options, strrep

Loading required package: class
Loading required package: fields
Loading required package: spam
Loading required package: dotCall64
Loading required package: grid
Spam version 2.5-1 (2019-12-12) is loaded.
Type 'help( Spam)' or 'demo( spam)' for a short introduction
and overview of this package.
Help for individual functions is also obtained by adding the
suffix '.spam' to the function name, e.g. 'help( chol.spam)'.

Attaching package: 'spam'

The following objects are masked from 'package:base':

    backsolve, forwardsolve

Loading required package: maps
See https://github.com/NCAR/Fields for
 an extensive vignette, other supplements and source code
Loading required package: ROCR
Loading required package: gplots

Attaching package: 'gplots'

The following object is masked from 'package:stats':

    lowess

Loading required package: DMwR
Loading required package: lattice
Registered S3 method overwritten by 'quantmod':
  method            from
  as.zoo.data.frame zoo

Attaching package: 'DMwR'

The following object is masked from 'package:fields':

    unscale

Attaching package: 'uba'

The following object is masked from 'package:base':

    subset

Loading required package: MBA
Loading required package: gstat
Loading required package: automap
Loading required package: sp
Loading required package: randomForest
randomForest 4.6-14
Type rfNews() to see new features/changes/bug fixes.

Attaching package: 'UBL'

The following objects are masked from 'package:uba':

    phi, phi.control

Is there a way to suppress messages in any other way ? I might be using these packages in many other R scripts and I don't want to do this each time.

Body:
One way is to write a simple function, that takes in a vector of packages and suppresses the output in a way you want, as examplified below.

library_suppress <- function(packages, character.only = TRUE, ...){
    for(i in seq_along(packages))
        suppressPackageStartupMessages(
            library(packages[i], character.only = character.only, ...)
        )
}
packages <- c('operators', 'class', 'fields', 'spam', 'dotCall64', 'grid', 'MBA', 'gstat', 'automap', 'sp', 'randomForest')
library_suppress(packages)

Note this does not suppress warning messages.


问:
How can we use drawerLockMode in React Navigation v5.0
I am using react navigation v5.0 in my project.
In previous version there is an option called "drawerLockMode" by which we could disable swipe gesture from opening the navigation drawer in an specific screen.
How can I use this option in v5.0 ?</p>

答:
Use gestureEnabled option

Whether you can use gestures to open or close the drawer. Defaults to true.

https://reactnavigation.org/docs/en/drawer-navigator.html#gestureenabled


问:
Multivariate Multiple Regression using Python libraries
Is there any library to perform a Multivariate Multiple Regression (a Multiple Regression with multiple dependent variables) in Python?

Greetings and thanks in advance

答:
You can try the modules in sklearn, the response variable can be 2 or more dimensional, and i think it works for OLS (linear regression), lasso, ridge.. The models in statsmodels can only do 1 response (just checked).

Example dataset:

```<code>import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(data= iris['data'],
                     columns= iris['feature_names'] )

df.shape
(150, 4)
</code>```

Now we do the fit:

```<code>from sklearn import linear_model
clf = linear_model.LinearRegression()
clf.fit(df[['sepal length (cm)']],df[['petal length (cm)','petal width (cm)']])
clf.coef_

array([[1.85843298],
       [0.75291757]])
</code>```

You can see the coefficients are the same as when you fit one response in this case:

```<code>clf.fit(df[['sepal length (cm)']],df[['petal width (cm)']])
clf.coef_
array([[0.75291757]])
</code>```

Body:
You can try the modules in sklearn, the response variable can be 2 or more dimensional, and i think it works for OLS (linear regression), lasso, ridge.. The models in statsmodels can only do 1 response (just checked).

Example dataset:

import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(data= iris['data'],
                     columns= iris['feature_names'] )

df.shape
(150, 4)

Now we do the fit:

from sklearn import linear_model
clf = linear_model.LinearRegression()
clf.fit(df[['sepal length (cm)']],df[['petal length (cm)','petal width (cm)']])
clf.coef_

array([[1.85843298],
       [0.75291757]])

You can see the coefficients are the same as when you fit one response in this case:

clf.fit(df[['sepal length (cm)']],df[['petal width (cm)']])
clf.coef_
array([[0.75291757]])


问:
forgotten key pair needed for bastion host to connect to rds
I am trying to set up a bastion host to connect to my rds in AWS, but I have forgotten the key pair that I need in order to configure it. Is there a way to retrieve it or make a new one so I can configure the bastion host? If so how would I go about it?</p>

答:
Frankly, if you have no important data or configuration on the Bastion server, then it would be easiest to terminate it and launch a replacement.

However, if you wish to regain access to the instance, there's a couple of methods.

Create an AMI

Create an image (AMI) of the current bastion

Launch a new Bastion from that AMI, specifying a new keypair

This works because software installed in Amazon Linux will automatically add the nominated keypair to the ec2-user user's ~/.ssh/authorized_keys file.

Manual editing

Stop the Bastion

Detach the root volume

Launch another (temporary) instance

Attach the disk from the Bastion as an additional drive

Edit the /home/ec2-user/.ssh/authorized_keys file and add the public half of new keypair

Detach drive

Reattach to Bastion

Start the Bastion

That makes the AMI method look easier, eh‽


问:
Running "ansible-playbook playbook.yml" outputs fatal: [localhost]: FAILED
Following the ansible 2-org-network example tutorial, when running "ansible-playbook playbook.yml" command, this outputs
"TASK [ibm.blockchain_platform_manager : Authenticate to IBM Blockchain Platform service] *****************************************************
fatal: [localhost]: FAILED! => {"changed": false, "connection": "close", "content": "{\"context\":{\"requestId\":\"3aed45737c8d4cc7a3a52b03cfbf7e64\",\"requestType\":\"incoming.Identity_Token\",\"userAgent\":\"ansible-httpget\",\"url\":\"https://iam.cloud.ibm.com\",\"instanceId\":\"iamid-5.2-7439-f51ff7a-6488f4d469-jxdn5\",\"threadId\":\"f61a\",\"host\":\"iamid-5.2-7439-f51ff7a-6488f4d469-jxdn5\",\"startTime\":\"15.02.2020 21:04:28:625 GMT\",\"endTime\":\"01.01.1970 00:00:00:000 GMT\",\"elapsedTime\":\"0\",\"locale\":\"en_US\",\"clusterName\":\"iam-id-prams03-igyr\"},\"errorCode\":\"BXNIM0415E\",\"errorMessage\":\"Provided API key could not be found\"}", "content_language": "en-US", "content_length": "517", "content_type": "application/json", "date": "Sat, 15 Feb 2020 21:04:28 GMT", "elapsed": 0, "json": {"context": {"clusterName": "iam-id-prams03-igyr", "elapsedTime": "0", "endTime": "01.01.1970 00:00:00:000 GMT", "host": "iamid-5.2-7439-f51ff7a-6488f4d469-jxdn5", "instanceId": "iamid-5.2-7439-f51ff7a-6488f4d469-jxdn5", "locale": "en_US", "requestId": "3aed45737c8d4cc7a3a52b03cfbf7e64", "requestType": "incoming.Identity_Token", "startTime": "15.02.2020 21:04:28:625 GMT", "threadId": "f61a", "url": "https://iam.cloud.ibm.com", "userAgent": "ansible-httpget"}, "errorCode": "BXNIM0415E", "errorMessage": "Provided API key could not be found"}, "msg": "Status code was 400 and not [200]: HTTP Error 400: Bad Request", "redirected": false, "set_cookie": "sessioncookie=76599c5849373452d151007c6314be2a; Path=/; Secure; HttpOnly", "status": 400, "transaction_id": "3aed45737c8d4cc7a3a52b03cfbf7e64", "url": "https://iam.cloud.ibm.com/identity/token", "x_powered_by": "Servlet/3.1"}
PLAY RECAP ***********************************************************************************************************************************
localhost                  : ok=4    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

"
I don't know if this an error, but a node file should be created but it's not. a screenshot of the output is attached

Edit: I'm using ibm blockchain platform vscode extension. changed the infrastructure.type from "saas" to "software" while the previous error is gone another one apperead "I'm using the ibm platform extension on vs code. changed the infrastructre.type from "saas" to "software" in the "playbook.yaml" file, that error is gone but a new appeared
"fatal: [localhost]: FAILED! => {"changed": false, "content": "", "elapsed": 0, "msg": "Status code was -1 and not [200]: Request failed: ", "redirected": false, "status": -1, "url": "https://ibp-console.example.org:32000/ak/api/v1/components?skip_cache=yes"}
PLAY RECAP ***********************************************************************************************************************************
localhost                  : ok=11   changed=3    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

"

答:
The ansible role provides support for 3 options, saas, software and docker.

saas refers to IBM Blockchain platform in the cloud, ie the software as a service offering in IBM Cloud, so you need to have provisioned IBM Blockchain platform on the IBM Cloud for this option.

software refers to IBM Blockchain platform software which you need to purchase from IBM and have it deployed.

docker refers to a local deployment on your machine using docker of the Open Source Hyperledger images it creates a local fabric network on your machine.

I'm guessing that you would want to use the docker option.


问:
Node's global variable vs. a variable called global created within a react component SSR
If I have a SSR react application running on node with a component that sets a variable like let global = {} and then do something like global.name = 'sam', would this global variable replace/overwrite node's global object OR would this global variable just be within the scope of the react component? Would this object be garbage collected when the component unmounts or would it stay in memory as node's global object?

I know that it is not best practice to use global as a variable name, but just wondering if this may lead to a memory leak.

答:
The let global variable will only replace node's global in the scope the new variable is defined in.

```<code>console.log(global) // Object [global] {...}
function go(){
  let global = {}
  console.log(global) // {}
}
go()
console.log(global) // Object [global] {...}
</code>```

Don't use a variable named global when using node.

Body:
The let global variable will only replace node's global in the scope the new variable is defined in.

console.log(global) // Object [global] {...}
function go(){
  let global = {}
  console.log(global) // {}
}
go()
console.log(global) // Object [global] {...}

Don't use a variable named global when using node.


问:
argv listing directory files
this very simple code is driving me nuts.

```<code>import sys,string,socket

maquina = sys.argv[1]
texto = string.join(sys.argv[2:], " ")
print '['+maquina+']'
print '['+texto+']'

mysock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
if  maquina == '*':
    for ip in range(18,254):
        mysock.sendto( texto, ('192.168.0.'+str(ip),8090) )
else:
    mysock.sendto( texto, (maquina,8090))
mysock.close()
</code>```

When I type

```<code>python send.py 192.168.0.135 several strings
</code>```

the output is:

```<code>[192.168.0.135]
[several strings]
</code>```

But if I type

```<code>python send.py * several strings
</code>```

I got:

```<code>[ajax]
[ajustaprofile.py build dia2django.py djangoajax django-cube django-evolution django_excel_templates-0.1 Doc google_appengine httpd.conf imagens jre1.5.0_08 lib list_mailbackup.py luma models.py netsend.py pip-log.txt reverse.py share testparamet.py tnsnames.ora util virttool-0.1 xlrd-0.7.1 xlutils-1.4.1 xlwt-0.7.2 several lines]
</code>```

This is the file list that I have on current directory!
Python translates somehow '*' to the files of current directory.

I tried to do the homework using this link but I got no clue.

http://docs.python.org/library/sys.html
http://www.faqs.org/docs/diveintopython/kgp_commandline.html

How can I use "*" on argv ?

答:
Another way to get file names is using the glob module:

```<code>>>> from glob import glob
>>> glob('*')
['file1.txt', 'file2.py', 'file3', ... ]
</code>```

It work just like the ls command.

Title: argv listing directory files

Body:
this very simple code is driving me nuts.

import sys,string,socket

maquina = sys.argv[1]
texto = string.join(sys.argv[2:], " ")
print '['+maquina+']'
print '['+texto+']'

mysock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
if  maquina == '*':
    for ip in range(18,254):
        mysock.sendto( texto, ('192.168.0.'+str(ip),8090) )
else:
    mysock.sendto( texto, (maquina,8090))
mysock.close()

When I type

python send.py 192.168.0.135 several strings

the output is:

[192.168.0.135]
[several strings]

But if I type

python send.py * several strings

I got:

[ajax]
[ajustaprofile.py build dia2django.py djangoajax django-cube django-evolution django_excel_templates-0.1 Doc google_appengine httpd.conf imagens jre1.5.0_08 lib list_mailbackup.py luma models.py netsend.py pip-log.txt reverse.py share testparamet.py tnsnames.ora util virttool-0.1 xlrd-0.7.1 xlutils-1.4.1 xlwt-0.7.2 several lines]

This is the file list that I have on current directory!
Python translates somehow '*' to the files of current directory.

I tried to do the homework using this link but I got no clue.

http://docs.python.org/library/sys.html
http://www.faqs.org/docs/diveintopython/kgp_commandline.html

How can I use "*" on argv ?

Body:
Another way to get file names is using the glob module:

>>> from glob import glob
>>> glob('*')
['file1.txt', 'file2.py', 'file3', ... ]

It work just like the ls command.


问:
Getting 'TypeError: invalid destination position for blit' in python
I'm new to python, and can't fix this. When trying to run my game, I get this error:

```<code>Traceback (most recent call last):
  File "C:\Users\soni801\Documents\GitHub\volleyball\Player.py", line 15, in draw
    window.blit(pygame.image.load("player.png"), 100, 100)
TypeError: invalid destination position for blit
</code>```

I know other people that have done very similar code without getting this error, and I have no idea why i am getting this.

How do I fix this? I've tried changing literally every single variable, with no luck. Any help appreciated. Here is my code:

In Game.py:

```<code>import pygame

from Player import Player

running = True
clock = pygame.time.Clock()

# Images
background = pygame.image.load("bg.png")

# Global variables
WIDTH = 800
HEIGHT = 600

# Player variables
player_size = 70
player_pos = [(WIDTH / 4) - (player_size / 2), HEIGHT - player_size]
player_speed = 5
jump_height = 22

jumping = False
jump_time = -jump_height

window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Volleyball")

player = Player(player_pos, player_size, player_speed, jump_height, pygame.image.load("player.png"))

def tick():
    player.movement()

def render():
    window.blit(background, (0, 0))

    player.draw(window)

    pygame.display.update()

if __name__ == '__main__':
    while running:
        clock.tick(60)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        tick()
        render()

pygame.quit()
</code>```

In Player.py:

```<code>import pygame

class Player(object):
    def __init__(self, pos, size, speed, jump_height, image):
        self.jump_height = jump_height
        self.speed = speed
        self.pos = pos
        self.image = image

        self.jumping = False
        self.jump_time = -jump_height

    def draw(self, window):
        window.blit(self.image, self.pos[0], self.pos[1])

    def movement(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_a] and self.pos[0] > 0:
            self.pos[0] -= self.speed
        if keys[pygame.K_d] and self.pos[0] < 800 - self.pos:
            self.pos[0] += self.speed
        if not self.jumping:
            if keys[pygame.K_SPACE]:
                self.jumping = True
        else:
            if self.jump_time <= self.jump_height:
                self.pos[1] += self.jump_time
                self.jump_time += 1
            else:
                self.jumping = False
                self.jump_time = -self.jump_height
</code>```

答:
I haven't tested yet but I think you just need to tuple the pos in your draw function:

not this:

```<code>    def draw(self, window):
        window.blit(self.image, self.pos[0], self.pos[1])
</code>```

this:

```<code>    def draw(self, window):
        window.blit(self.image, (self.pos[0], self.pos[1]))
</code>```

Body:
I'm new to python, and can't fix this. When trying to run my game, I get this error:

Traceback (most recent call last):
  File "C:\Users\soni801\Documents\GitHub\volleyball\Player.py", line 15, in draw
    window.blit(pygame.image.load("player.png"), 100, 100)
TypeError: invalid destination position for blit

I know other people that have done very similar code without getting this error, and I have no idea why i am getting this.

How do I fix this? I've tried changing literally every single variable, with no luck. Any help appreciated. Here is my code:

In Game.py:

import pygame

from Player import Player

running = True
clock = pygame.time.Clock()

# Images
background = pygame.image.load("bg.png")

# Global variables
WIDTH = 800
HEIGHT = 600

# Player variables
player_size = 70
player_pos = [(WIDTH / 4) - (player_size / 2), HEIGHT - player_size]
player_speed = 5
jump_height = 22

jumping = False
jump_time = -jump_height

window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Volleyball")

player = Player(player_pos, player_size, player_speed, jump_height, pygame.image.load("player.png"))

def tick():
    player.movement()

def render():
    window.blit(background, (0, 0))

    player.draw(window)

    pygame.display.update()

if __name__ == '__main__':
    while running:
        clock.tick(60)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        tick()
        render()

pygame.quit()

In Player.py:

import pygame

class Player(object):
    def __init__(self, pos, size, speed, jump_height, image):
        self.jump_height = jump_height
        self.speed = speed
        self.pos = pos
        self.image = image

        self.jumping = False
        self.jump_time = -jump_height

    def draw(self, window):
        window.blit(self.image, self.pos[0], self.pos[1])

    def movement(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_a] and self.pos[0] > 0:
            self.pos[0] -= self.speed
        if keys[pygame.K_d] and self.pos[0] < 800 - self.pos:
            self.pos[0] += self.speed
        if not self.jumping:
            if keys[pygame.K_SPACE]:
                self.jumping = True
        else:
            if self.jump_time <= self.jump_height:
                self.pos[1] += self.jump_time
                self.jump_time += 1
            else:
                self.jumping = False
                self.jump_time = -self.jump_height

Body:
I haven't tested yet but I think you just need to tuple the pos in your draw function:

not this:

    def draw(self, window):
        window.blit(self.image, self.pos[0], self.pos[1])

this:

    def draw(self, window):
        window.blit(self.image, (self.pos[0], self.pos[1]))


问:
Property 'map' does not exist on type 'TwitterserviceService'
I'm learning to create very simple and basic angular applications. I've decided to show my tweets from my twitter timeline. I followed some youtube tutorials and some blogs. Specially this- Connect to the Twitter API in an Angular 6 App. I was able to create a basic working angular-twiiter app (a made up name). I'll show you my code:

server.js
(nothing wrong with this code)

```<code>const express = require('express');
const Twitter = require('twit');
const app = express();

app.listen(3000, () => console.log('Server running'));

const api_client = new Twitter({
    consumer_key: 'MY_KEY',
    consumer_secret: 'MY_SECRET_KEY',
    access_token: 'MY_TOKEN',
    access_token_secret: 'MY_SECRET_TOKEN'
})

app.get('/home_timeline', (req, res) => {
    const params = { tweet_mode: 'extended', count: 10 };

    api_client
      .get('statuses/home_timeline', params)
      .then(timeline => {
        res.send(timeline);
      })
      .catch(error => {
      res.send(error);
    });
});
</code>```

Then I created twitterservice.service.ts
(error in this code)

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class TwitterserviceService {

  api_url = 'https:/localhost:3000';

  constructor(private http: HttpClient) { }

  getTimeline() {
    return this.http
      .get<any[]>(this.api_url+'/home_timeline')
      .pipe(this.map(data => data));  //ERROR: Property 'map' does not exist ...
  }
}
</code>```

For map I'm getting:

Property 'map' does not exist on type 'TwitterserviceService'.

However, My server.js is working absolutely fine. I've tested it on Postman and I'm getting the desired JSON output. I tried finding help on the internet, read some articles and questions like: Property 'map' does not exist on type 'Observable'. But still I'm not able to solve this. Please correct me.

答: Replace this.map with map. Using this keyword implies map is a member variable of 'TwitterserviceService' service.

Body:
I'm learning to create very simple and basic angular applications. I've decided to show my tweets from my twitter timeline. I followed some youtube tutorials and some blogs. Specially this- Connect to the Twitter API in an Angular 6 App. I was able to create a basic working angular-twiiter app (a made up name). I'll show you my code:

server.js
(nothing wrong with this code)

const express = require('express');
const Twitter = require('twit');
const app = express();

app.listen(3000, () => console.log('Server running'));

const api_client = new Twitter({
    consumer_key: 'MY_KEY',
    consumer_secret: 'MY_SECRET_KEY',
    access_token: 'MY_TOKEN',
    access_token_secret: 'MY_SECRET_TOKEN'
})

app.get('/home_timeline', (req, res) => {
    const params = { tweet_mode: 'extended', count: 10 };

    api_client
      .get('statuses/home_timeline', params)
      .then(timeline => {
        res.send(timeline);
      })
      .catch(error => {
      res.send(error);
    });
});

Then I created twitterservice.service.ts
(error in this code)

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class TwitterserviceService {

  api_url = 'https:/localhost:3000';

  constructor(private http: HttpClient) { }

  getTimeline() {
    return this.http
      .get<any[]>(this.api_url+'/home_timeline')
      .pipe(this.map(data => data));  //ERROR: Property 'map' does not exist ...
  }
}

For map I'm getting:

Property 'map' does not exist on type 'TwitterserviceService'.

However, My server.js is working absolutely fine. I've tested it on Postman and I'm getting the desired JSON output. I tried finding help on the internet, read some articles and questions like: Property 'map' does not exist on type 'Observable'. But still I'm not able to solve this. Please correct me.


问:
Error by trying installing docker repository on linux ubuntu 18.04 LTS
Sorry the language is german.

So I added the repository of the docker:

```<code>sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
</code>```

But I get Errors when I update the sources:

```<code>sudo apt-get update
</code>```

Ign:3 https://download.docker.com/linux/ubuntu bionic InRelease

Fehl:4 https://download.docker.com/linux/ubuntu bionic Release

  Certificate verification failed: The certificate is NOT trusted. The
  certificate issuer is unknown.  Could not handshake: Error in the
  certificate verification. [IP: 54.230.93.95 443]

Holen:5 http://archive.ubuntu.com/ubuntu bionic-backports InRelease
  [74,6 kB]

OK:6 http://archive.ubuntu.com/ubuntu bionic-security InRelease

Paketlisten werden gelesen... Fertig E: Das Depot
  »https://download.docker.com/linux/ubuntu bionic Release« enthält
  keine Release-Datei.

N: Eine Aktualisierung von solch einem Depot kann nicht auf eine
  sichere Art durchgeführt werden, daher ist es standardmäßig
  deaktiviert.

N: Weitere Details zur Erzeugung von Paketdepots sowie zu deren
  Benutzerkonfiguration finden Sie in der Handbuchseite apt-secure(8).

答:
For those still having this issue, here is a solution which I gleaned from the Ubuntu manpages.

The OP's post indicates a certificate verification error:

```<code>Certificate verification failed: The certificate is NOT trusted. The certificate issuer is unknown. Could not handshake: Error in the certificate verification. [IP: 54.230.93.95 443]
</code>```

I was having similar issues on a VM which sits behind a corporate proxy.  The proxy acts as a man-in-the-middle, decrypting and re-encrypting traffic as it flows through the proxy.  Even though I had the trusted certificate installed on my VM for the proxy, this error was still happening, caused by an invalid OCSP response.  To fix it, I ran this command:

```<code>touch /etc/apt/apt.conf.d/99verify-peer.conf \
&& echo >>/etc/apt/apt.conf.d/99verify-peer.conf "Acquire { https::Verify-Peer false }"
</code>```

This disables apt's OCSP verification, and is not recommended.

I chose a different solution, which may not be available to others.  Our company maintains a non-decrypting proxy for use cases like this, so I switched to using it.

Body:
Sorry the language is german.

So I added the repository of the docker:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

But I get Errors when I update the sources:

sudo apt-get update

Ign:3 https://download.docker.com/linux/ubuntu bionic InRelease

Fehl:4 https://download.docker.com/linux/ubuntu bionic Release

  Certificate verification failed: The certificate is NOT trusted. The
  certificate issuer is unknown.  Could not handshake: Error in the
  certificate verification. [IP: 54.230.93.95 443]

Holen:5 http://archive.ubuntu.com/ubuntu bionic-backports InRelease
  [74,6 kB]

OK:6 http://archive.ubuntu.com/ubuntu bionic-security InRelease

Paketlisten werden gelesen... Fertig E: Das Depot
  »https://download.docker.com/linux/ubuntu bionic Release« enthält
  keine Release-Datei.

N: Eine Aktualisierung von solch einem Depot kann nicht auf eine
  sichere Art durchgeführt werden, daher ist es standardmäßig
  deaktiviert.

N: Weitere Details zur Erzeugung von Paketdepots sowie zu deren
  Benutzerkonfiguration finden Sie in der Handbuchseite apt-secure(8).

Body:
For those still having this issue, here is a solution which I gleaned from the Ubuntu manpages.

The OP's post indicates a certificate verification error:

Certificate verification failed: The certificate is NOT trusted. The certificate issuer is unknown. Could not handshake: Error in the certificate verification. [IP: 54.230.93.95 443]

I was having similar issues on a VM which sits behind a corporate proxy.  The proxy acts as a man-in-the-middle, decrypting and re-encrypting traffic as it flows through the proxy.  Even though I had the trusted certificate installed on my VM for the proxy, this error was still happening, caused by an invalid OCSP response.  To fix it, I ran this command:

touch /etc/apt/apt.conf.d/99verify-peer.conf \
&& echo >>/etc/apt/apt.conf.d/99verify-peer.conf "Acquire { https::Verify-Peer false }"

This disables apt's OCSP verification, and is not recommended.

I chose a different solution, which may not be available to others.  Our company maintains a non-decrypting proxy for use cases like this, so I switched to using it.


问:
Write to a Text File and Copy File to Desktop from Phone's File System
I've made a mobile puzzle-like game that has some simple levels loaded from a text file line by line.

Now I am trying to make an editor in the game so when I draw a level from the editor, text file will be updated with the new line.

My Start() function looks like this:

```<code>void Start()
    {
        TextAsset file = Resources.Load("levels") as TextAsset;
        //text.text = file.text;
        levels = new List<string[]>();
        string[] linesFromfile = file.text.Split("\n"[0]);
        currentLevel = System.Convert.ToInt32(linesFromfile[0]);
        for(int i = 1; i < linesFromfile.Length; i++){
            levels.Add(linesFromfile[i].Split(';'));
        }
        loadLevel(currentLevel);
    }
</code>```

And my text file:

```<code>1
Side00-01,1;Side01-11,1;Side10-11,2;Side00-10,1;Side10-20,1
</code>```

In the first line of file I try to save the level number that player last played. Other lines represent each level. "Side00-01" part is the name of the side and the number next to it shows the color of the side. Maybe a dumb way to do this but it looked simple to me. loadLevel() function gets called after completing each level.

1) I've read many tutorials etc. and afaik we can't  simply write to a file in Android as simple as reading it like above, right? How should I do the writing part?

2) And another problem is I should send this editor part to some level designer friend and then I should get back the levels he drew. If we can't get the file from the file system of the phone how can I accomplish such thing?

Any advice will be appreciated. Thanks for all the help!

答:
1-) You should write and read your files from `Application.persistentDataPath, so you can store them cross platform.

2-) Create a button, which generates a UnityWebRequest. Read your friend's local file on Application.persistentDataPath with System.IO class then send all string as a post web request to your server. I think this part needs some server-side experience.

Body:
I've made a mobile puzzle-like game that has some simple levels loaded from a text file line by line.

Now I am trying to make an editor in the game so when I draw a level from the editor, text file will be updated with the new line.

My Start() function looks like this:

void Start()
    {
        TextAsset file = Resources.Load("levels") as TextAsset;
        //text.text = file.text;
        levels = new List<string[]>();
        string[] linesFromfile = file.text.Split("\n"[0]);
        currentLevel = System.Convert.ToInt32(linesFromfile[0]);
        for(int i = 1; i < linesFromfile.Length; i++){
            levels.Add(linesFromfile[i].Split(';'));
        }
        loadLevel(currentLevel);
    }

And my text file:

1
Side00-01,1;Side01-11,1;Side10-11,2;Side00-10,1;Side10-20,1

In the first line of file I try to save the level number that player last played. Other lines represent each level. "Side00-01" part is the name of the side and the number next to it shows the color of the side. Maybe a dumb way to do this but it looked simple to me. loadLevel() function gets called after completing each level.

1) I've read many tutorials etc. and afaik we can't  simply write to a file in Android as simple as reading it like above, right? How should I do the writing part?

2) And another problem is I should send this editor part to some level designer friend and then I should get back the levels he drew. If we can't get the file from the file system of the phone how can I accomplish such thing?

Any advice will be appreciated. Thanks for all the help!


问:
Select Parent Node without Child node. XSLT
I would like to select Parent node without Child node.

Example:

```<code><Shop>
    <Product>
       <ProductId>1</ProductId>
       <Description>ProductList</Description>
       <Milk>
         <MilkId></MilkId>
       </Milk>
    </Product>
</Shop>
</code>```

Desired Output:

```<code><Shop>
    <Product>
       <ProductId>1</ProductId>
       <Description>ProductList</Description>
    </Product>
</Shop>
</code>```

I tried below XSLT but it failed to return correct result:

```<code><xsl:copy-of select="//Product/not[Milk]"/>
</code>```

Thank you for any help.

Update:

XSLT:

```<code><xsl:copy-of select="Product/*[not(self::Milk)]" />
</code>```

Returns:

```<code><ProductId>1</ProductId>
</code>```

I need below structure to be returned:

```<code><Shop>
        <Product>
           <ProductId>1</ProductId>
           <Description>ProductList</Description>
        </Product>
    </Shop>
</code>```

答:
You can use a variant of the Identity template:

```<code><!-- Identity template variant -->
<xsl:template match="node()|@*">
    <xsl:copy>
         <xsl:apply-templates select="node()[local-name()!='Milk']|@*" />
    </xsl:copy>
</xsl:template>
</code>```

Or, as a more XSLT-2.0 way suggested in the comments

```<code><xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node() except Milk|@*" />
    </xsl:copy>
</xsl:template>
</code>```

It copies all nodes except for the ones named Milk and its children.

If you want to apply this only to Product nodes, you also have to use the Identity template and change the matching rule to

```<code><xsl:template match="Product">...
</code>```

A solution using only xsl:copy-of could be copying the Product element and then copy all of its children (except for the Milk ones) with

```<code><xsl:copy-of select="Product/*[not(self::Milk)]" />
</code>```

Or, in a whole XSLT-2.0 template

```<code><xsl:template match="//Product">
    <xsl:copy>
      <xsl:copy-of select="* except Milk" />
    </xsl:copy>
</xsl:template>
</code>```

A whole XSLT-1.0 stylesheet could look like

```<code><?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <!-- Identity template -->
    <xsl:template match="node()|@*">
        <xsl:copy>
             <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Product">
        <xsl:copy>
          <xsl:copy-of select="*[not(self::Milk)]" />
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
</code>```

Its output is:

```<code><?xml version="1.0"?>
<Shop>
    <Product>
        <ProductId>1</ProductId>
        <Description>ProductList</Description>
    </Product>
</Shop>
</code>```

Body:
I would like to select Parent node without Child node.

Example:

<Shop>
    <Product>
       <ProductId>1</ProductId>
       <Description>ProductList</Description>
       <Milk>
         <MilkId></MilkId>
       </Milk>
    </Product>
</Shop>

Desired Output:

<Shop>
    <Product>
       <ProductId>1</ProductId>
       <Description>ProductList</Description>
    </Product>
</Shop>

I tried below XSLT but it failed to return correct result:

<xsl:copy-of select="//Product/not[Milk]"/>

Thank you for any help.

Update:

XSLT:

<xsl:copy-of select="Product/*[not(self::Milk)]" />

Returns:

<ProductId>1</ProductId>

I need below structure to be returned:

<Shop>
        <Product>
           <ProductId>1</ProductId>
           <Description>ProductList</Description>
        </Product>
    </Shop>

Body:
You can use a variant of the Identity template:

<!-- Identity template variant -->
<xsl:template match="node()|@*">
    <xsl:copy>
         <xsl:apply-templates select="node()[local-name()!='Milk']|@*" />
    </xsl:copy>
</xsl:template>

Or, as a more XSLT-2.0 way suggested in the comments

<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node() except Milk|@*" />
    </xsl:copy>
</xsl:template>

It copies all nodes except for the ones named Milk and its children.

If you want to apply this only to Product nodes, you also have to use the Identity template and change the matching rule to

<xsl:template match="Product">...

A solution using only xsl:copy-of could be copying the Product element and then copy all of its children (except for the Milk ones) with

<xsl:copy-of select="Product/*[not(self::Milk)]" />

Or, in a whole XSLT-2.0 template

<xsl:template match="//Product">
    <xsl:copy>
      <xsl:copy-of select="* except Milk" />
    </xsl:copy>
</xsl:template>

A whole XSLT-1.0 stylesheet could look like

<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <!-- Identity template -->
    <xsl:template match="node()|@*">
        <xsl:copy>
             <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Product">
        <xsl:copy>
          <xsl:copy-of select="*[not(self::Milk)]" />
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Its output is:

<?xml version="1.0"?>
<Shop>
    <Product>
        <ProductId>1</ProductId>
        <Description>ProductList</Description>
    </Product>
</Shop>


问:
RSS aggregation packages
We are looking to add a news/articles section to an existing site which will be powered by aggregating content via RSS feeds. The requirements are

Be able to aggregate lots of feeds. Initially we will start with small number of and eventually we may be aggregating few hundreds of them.

We don't want to display the whole post on our site. We will display summary or short description and when user clicks on read more, he will be taken to the original post on external site.

We would like to grab the image/s related to a post and display that as a small thumbnail with a post on our site.

Create an automated tag cloud out of all the aggregated content.

Categorize aggregated content by using category/sub-category structure.

The aggregation piece should perform well.

Our web app is built using Django and so I am looking into selecting one the following packages. Based on our requirements, which package would you recommend?

django-planet

django-news

planetplanet

feedjack

答: If you have a good idea of what you want, why not just try them all? If you have pretty strict requirements, write it yourself, roll your own aggregator with feedparser.</p>

Title: RSS aggregation packages


问:
Matlab - ODE Function - Integrating myself vs ode45 Function
I am confused as to what the matlab ODE function does. If i have the system dynamics, why can't i just manually integrate it myself and get the result. What exactly is the purpose of the ode45 function?</p>

答:
You are asking about the preference between analytical (manual) vs numerical integration. If you can manually solve an ODE, then, yes, you don't need to use the ODE command to integrate it numerically. You can just plug in the initial/final time, initial conditions, and system model parameters into the analytical solution to compute the numerical value of the solution.

However, as it is often the case, finding the analytical solution of the ODE is very difficult or time consuming. Especially, if you have a system of nonlinear differential equations, manually computing the solution is practically impossible. In that case, the only practical solution is to use numerical integration, such as the capability provided by the ODE45 command.

Also, as you probably know, the solution of the ODEs might be quite complicated depending on the inputs to the system (ie, the forcing function). So, if your goal is to analyze the response of the system to various types of inputs (sinusoidal, step, impulse, etc), manually deriving the analytical solution for each input type would be very hard. Whereas, changing the input type and rerunning the ODE45 command is virtually trivial.


问:
Absence of texture on 3D model in AR application made with Unity 3D and Region Capture
I'm working on a little AR coloring book application using Unity and Vuforia. I did something similar a few years back, but now, with the new updates, they changed a lot of things (I'm using Unity 2017.3, Vuforia 7 and Texture Region Capture 2.0.6 available here https://github.com/maximrouf/RegionCapture).

When the Image Target is shown, a 3D model of that image appears and you should be able to color it. The problem is that on the 3D model I can see all the things captured by the camera, not only the texture, as shown in the image below.

Now, I don't know the reason for this, I tried looking at other tutorials, but even the scripts for this version of Region Capture differ. Below are some pictures containing the way I attached the cameras and the game object to the scripts..

Please help me find a solution.

答:
I have faced the same problem today so I post here the solution hoping that this will help people who encounter the same problem.

To solve it, I had to link the Region Capture to my Image Target and resize it to match the Image Target's size:


问:
While iterating through an array, how to make sure that the correct output is printed?
I am making a simple C program that takes a user input and checks if it is a valid password from an array. I am finding though that if it is the last password in the array (if there are 7 valid passwords) and I am using an if statement to iterate through each element in the array to check for validity, it prints "access denied" until the correct password is reached because it is not one of the first few allowed passwords.

Here's what I have:

```<code>int userPass = 1971;
int validPass [] = {1912, 1914, 1922, 1947, 1958, 1964, 1971};
int i = 0;

while (validPass[i])
{
    if (userPass == validPass[i])
        {
            printf("Access granted \n");
        }
    else
        {
            printf("Access denied \n");
        }
   i++;
}
</code>```

This printed 'access denied' 6 times then on the 7th time it prints 'access granted' because it the user password is correct as per the 7th element within the array. How can I get it to check each element for validity before printing access granted or denied, to ensure that even if it is the last element in the array the correct line will print? I tried moving my i++ to before the else statement and within the if statement, but the program did not like that.

答:
As you loop through the options don't print anything yet.  If you find the correct value set a flag.  Then print the text based on the value of the flag.</p>

```<code>int found = 0;
while (i<(sizeof(validPass)/sizeof(validPass[0])) {
    if (userPass == validPass[i]) {
        found = 1;
        break;
    }
    i++;
}

if (found) {
    printf("Access granted \n");
} else {
    printf("Access denied \n");
}
</code>```

Body:
I am making a simple C program that takes a user input and checks if it is a valid password from an array. I am finding though that if it is the last password in the array (if there are 7 valid passwords) and I am using an if statement to iterate through each element in the array to check for validity, it prints "access denied" until the correct password is reached because it is not one of the first few allowed passwords.

Here's what I have:

int userPass = 1971;
int validPass [] = {1912, 1914, 1922, 1947, 1958, 1964, 1971};
int i = 0;

while (validPass[i])
{
    if (userPass == validPass[i])
        {
            printf("Access granted \n");
        }
    else
        {
            printf("Access denied \n");
        }
   i++;
}

This printed 'access denied' 6 times then on the 7th time it prints 'access granted' because it the user password is correct as per the 7th element within the array. How can I get it to check each element for validity before printing access granted or denied, to ensure that even if it is the last element in the array the correct line will print? I tried moving my i++ to before the else statement and within the if statement, but the program did not like that.

Body:
As you loop through the options don't print anything yet.  If you find the correct value set a flag.  Then print the text based on the value of the flag.

int found = 0;
while (i<(sizeof(validPass)/sizeof(validPass[0])) {
    if (userPass == validPass[i]) {
        found = 1;
        break;
    }
    i++;
}

if (found) {
    printf("Access granted \n");
} else {
    printf("Access denied \n");
}