Swap first and last columns in matrix - powershell

For example, we have a matrix.
1, 2, 3, 4, 5
6, 7, 8, 9, 10
11, 12, 13, 14, 15
16, 17, 18, 19, 20
21, 22, 23, 24, 25
Perhaps the simplest way to resolve the problem sounded in the title of the topic in Perl6 looks like
my #matrix = [1..5], [6..10], [11..15], [16..20], [21..25];
#matrix.map:{.[0,*-1] = .[*-1,0]};
Result
5, 2, 3, 4, 1
10, 7, 8, 9, 6
15, 12, 13, 14, 11
20, 17, 18, 19, 16
25, 22, 23, 24, 21
How to do the same is also beautiful in PowerShell?

Your code snippet translated to PowerShell would look like this:
$matrix = (1..5), (6..10), (11..15), (16..20), (21..25)
$matrix | ForEach-Object { $_[0], $_[-1] = $_[-1], $_[0] }

Related

Observable.switchMap does not interrupt Observable

I don't understand why switchMap doesn't work as expected.
At first case switchMap doesn't interrupt Observable but at second case it works as expected. Please, explain that behaviour.
val test = TestObserver<Int>()
Observable.fromArray(10, 20)
.switchMap({
// 1. switchMap does not interrupt generator
Observable.generate(
Callable{
generateSequence(it, { n -> if (n < it + 9) n + 1 else null}).iterator()
},
BiConsumer<Iterator<Int>, Emitter<Int>>(){ data, emitter ->
if (data.hasNext()) {
Thread.sleep(100)
emitter.onNext(data.next())
}else {
emitter.onComplete()
}
}
)
// 2. switchMap disposes observable
//Observable.just(it).delay(1, TimeUnit.SECONDS)
},2)
.subscribeWith(test)
test.await()
// 1. >> [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
// But I expect [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
// 2. >> [20]
print(test.values())
What I want to do.
In reality my generator do hard work based on value from switchMap and I want interrupt this work if new value is appeared. At the beginning generator start transaction and at the end generator commits or cancels transaction.

rrule dates are offset by a week

I'm getting an unexpected result using the python-dateutil rrule module and I'm wondering if this is WAI.
I'm dynamically creating the rrule using:
dtstart = datetime.date(2019, 1, 7)
until = datetime.date(2029, 11, 29)
freq = MONTHLY
byweekday=MO(2)
interval = 4
This results in the following rrule
DTSTART:20190107T000000
RRULE:FREQ=MONTHLY;INTERVAL=4;UNTIL=20291129T000000;BYDAY=+2MO
However, when generating the dates (looping on the rrule for this python module), I get the following dates:
[datetime.datetime(2019, 1, 14, 0, 0),
datetime.datetime(2019, 5, 13, 0, 0),
datetime.datetime(2019, 9, 9, 0, 0),
datetime.datetime(2020, 1, 13, 0, 0),
datetime.datetime(2020, 5, 11, 0, 0),
datetime.datetime(2020, 9, 14, 0, 0),
datetime.datetime(2021, 1, 11, 0, 0),
datetime.datetime(2021, 5, 10, 0, 0),
datetime.datetime(2021, 9, 13, 0, 0),
datetime.datetime(2022, 1, 10, 0, 0),
datetime.datetime(2022, 5, 9, 0, 0),
datetime.datetime(2022, 9, 12, 0, 0),
datetime.datetime(2023, 1, 9, 0, 0),
datetime.datetime(2023, 5, 8, 0, 0),
datetime.datetime(2023, 9, 11, 0, 0),
datetime.datetime(2024, 1, 8, 0, 0),
datetime.datetime(2024, 5, 13, 0, 0),
datetime.datetime(2024, 9, 9, 0, 0),
datetime.datetime(2025, 1, 13, 0, 0),
datetime.datetime(2025, 5, 12, 0, 0),
datetime.datetime(2025, 9, 8, 0, 0),
datetime.datetime(2026, 1, 12, 0, 0),
datetime.datetime(2026, 5, 11, 0, 0),
datetime.datetime(2026, 9, 14, 0, 0),
datetime.datetime(2027, 1, 11, 0, 0),
datetime.datetime(2027, 5, 10, 0, 0),
datetime.datetime(2027, 9, 13, 0, 0),
datetime.datetime(2028, 1, 10, 0, 0),
datetime.datetime(2028, 5, 8, 0, 0),
datetime.datetime(2028, 9, 11, 0, 0),
datetime.datetime(2029, 1, 8, 0, 0),
datetime.datetime(2029, 5, 14, 0, 0),
datetime.datetime(2029, 9, 10, 0, 0)]
Notice that the first date is offset by a week! Why is this the case? And is this a bug in the library?
Thanks,
David
It's not a bug in the library. 2019-01-14 is the first date which matches your rule (it's the 2nd Monday of January 2019). Apparently python-dateutil has chosen to not include the start date you provide, which is completely legit.
RRULE is specified in RFC 5545, which states in Section 3.8.5.3 (under "Description"):
The recurrence set generated with a "DTSTART" property
value not synchronized with the recurrence rule is undefined.
Which essentially means there is no right or wrong interpretation because the input data is "broken" if the start date doesn't match the rule.
Note, many other implementations would probably return both, your start date 2019-01-07 and the result 2019-01-14. I don't think any implementation would omit 2019-01-14, simply because it is the first date which matches the rule. It's debatable whether the start date 2019-01-07 should be in the results or not, but 2019-01-14 should definitely be in there.
In Python by_weekly code could be implemented like this.
from calendar import isleap
from datetime import datetime
from dateutil.rrule import rrule, DAILY, WEEKLY, MONTHLY
def bi_weekly(start_date=datetime.now(),count=53,interval=2):
"""
dateTImeSart = bi_weekly(datetime.strptime('2021-01-01', '%Y-%m-%d'),53)
print(dateTImeSart[0].strftime("%Y-%m-%d"))
print(dateTImeSart[1].strftime("%Y-%m-%d"))
print(dateTImeSart[50].strftime("%Y-%m-%d"))
print(dateTImeSart[51].strftime("%Y-%m-%d"))
print(dateTImeSart[52].strftime("%Y-%m-%d"))
2021-01-01
2021-01-15
2022-12-02
2022-12-16
2022-12-30
"""
# returns the datetime for an year and calculates them for 1 By weekly
return list(rrule(WEEKLY, count=count,interval=interval, dtstart=start_date))

Powershell "Padding is invalid and cannot be removed" error

I'm trying to decrypt a string in Powershell and am getting this error. What could be wrong?
This exception can represent a lot of different things, and not all of them are related to the padding, so I have tried to catalogue all the different scenarios where this can occur.
If you know of another situation where this padding exception is thrown, please add it.
To start, this is an example of encryption/decryption that works as expected.
$testData = "Hi there! This is a test of a string during encryption"
$enc = [system.Text.Encoding]::UTF8
$data = $enc.getBytes($testData)
# Encrypt some data
$encryptAlgorithm = [System.Security.Cryptography.SymmetricAlgorithm] (New-Object System.Security.Cryptography.AesCryptoServiceProvider)
$encryptAlgorithm.Mode = [System.Security.Cryptography.CipherMode]::CBC
$encryptAlgorithm.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7
$encryptAlgorithm.KeySize = 128
$encryptAlgorithm.BlockSize = 128
$encryptAlgorithm.Key = #(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
$encryptAlgorithm.IV = #(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
$encryptor = [System.Security.Cryptography.ICryptoTransform]$encryptAlgorithm.CreateEncryptor()
$encryptorMemoryStream = new-Object IO.MemoryStream
$encryptorCryptoStream = new-Object Security.Cryptography.CryptoStream $encryptorMemoryStream,$encryptor,"Write"
$encryptorCryptoStream.Write($data, 0, $data.Length)
$encryptorCryptoStream.FlushFinalBlock();
$encryptedData = $encryptorMemoryStream.ToArray()
Write-Host $enc.GetString($encryptedData)
Write-Host $encryptedData.Length
# Decrypt some data
$descryptAlgorithm = [System.Security.Cryptography.SymmetricAlgorithm] (New-Object System.Security.Cryptography.AesCryptoServiceProvider)
$descryptAlgorithm.Mode = [System.Security.Cryptography.CipherMode]::CBC
$descryptAlgorithm.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7
$descryptAlgorithm.KeySize = 128
$descryptAlgorithm.BlockSize = 128
$descryptAlgorithm.Key = #(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
$descryptAlgorithm.IV = #(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
$decryptor = [System.Security.Cryptography.ICryptoTransform]$descryptAlgorithm.CreateDecryptor()
$dataToDecrypt = $encryptedData
$decryptorMemoryStream = new-Object IO.MemoryStream #(,$dataToDecrypt)
$decryptorCryptoStream = new-Object Security.Cryptography.CryptoStream $decryptorMemoryStream,$decryptor,"Read"
$streamReader = new-Object IO.StreamReader $decryptorCryptoStream
try
{
Write-Output $streamReader.ReadToEnd()
}
catch
{
$e = $_.Exception
$msg = $e.Message
while ($e.InnerException) {
$e = $e.InnerException
$msg += "`n" + $e.Message
}
$msg
}
Let's look at some examples that trigger the padding exception.
Failing to flush the final block
This blog post has a good write up of this scenario.
#$encryptorCryptoStream.FlushFinalBlock();
Invalid keys
I've changed the byte array used for the decryption key slightly here to simulate keys that don't match.
$descryptAlgorithm.Key = #(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17)
RijndaelManaged with an empty input
$descryptAlgorithm = [System.Security.Cryptography.SymmetricAlgorithm] (New-Object System.Security.Cryptography.RijndaelManaged)
// ...
$dataToDecrypt = #()
Invalid padding
I've manually added some invalid padding to the end of the data to decrypt.
$dataToDecrypt = $encryptedData + #(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
Different padding schemes
Interestingly only some padding scheme combinations result in the padding error. A lot will decrypt without error, even if the resulting sting is incorrect.
$descryptAlgorithm.Padding = [System.Security.Cryptography.PaddingMode]::ANSIX923
Different block sizes
$descryptAlgorithm.BlockSize = 64

Initial values in WinBUGS

I gave all values for stochastic nodes, but WinBUGS still gives me the message that a chain contains uninitialized variables. When I try to generate it, BUGS gives me an error undefined real result. What node I am missing here?
model {
# Population Model start on the 1 of October 2014
# Look up initial numbers in each age class
F1.2014 <- 4 # no. first-year females October 2014
F2.2014 <- 2 # no. older females October 2014
F.2014 <- F1.2014+F2.2014 # total no. of females in October 2014
F.trans <- 15 # no. of trans. juv females in March 2015
F2[1] ~ dbin(phi.af.annual, F.2014) # sample number older females alive October 2015 (12 mo)
mutot.2014 <- mu.1*F1.2014+mu.2*F2.2014 # expected number of fledglings 2014/15
J.2014 ~ dpois(mutot.2014) # sample actual number of fledglings
JF.2014 ~ dbin(0.5,J.2014) # sample no. juv females in January 2015
phi.trans<-pow((phi.jf.mo),6) # probability trans juvs survive from March to October
F1.trans ~ dbin(phi.trans, F.trans) # sample no. translocated female juven in October 2015
F1.juvs ~ dbin(phi.jf,JF.2014) # sample no. female juven in October 2015
F1[1]<-F1.juvs+F1.trans # total number of first year birds in October 2015
F[1] <- F1[1]+F2[1]
PE[1] <- step(-F[1]) # prob extinction by October 2015
# run simulations for 20 years
for (i in 1:20) {
mutot[i] <- mu.1*F1[i]*mu.2*F2[i] # expected number of total fledglings by females
J[i] ~ dpois(mutot[i]) # sample total fledglings
JF[i] ~ dbin(0.5,J[i]) # sample number female fledglings
F1[i+1] ~ dbin(phi.jf,JF[i]) # sample number female recruits next year
F2[i+1] ~ dbin(phi.af.annual,F[i]) # sample number adult females that survive to next year
F[i+1] <- F1[i+1]+F2[i+1] # total number of females next year
PE[i+1] <- step(-F[i+1]) # prob that population extinct next year
}
}
# Data
list(phi.af.annual=0.6, mu.1=2.5, mu.2=3.1, phi.jf.mo=0.8, phi.jf=0.87)
# Inits
list(F1=c(NA, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5),
F2=c(NA, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3),
F1.trans=10, F1.juvs=6, J.2014=20, JF.2014=10,
J=c(10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10),
JF=c(5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5)
)

ZXing library Reed Solomon example

I want to try the ReedSolomonDecoder from the ZXing library on the example given on page 10 of this paper
Basically, it encodes the message
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
using the generator polynomial
x^4 + 15x^3 + 3x^2 + x + 12
which results in
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 3, 3, 12, 12
I want to decode this in the following manner:
int[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 3, 3, 12, 12};
GenericGF field = new GenericGF(?, 16, 1); // what integer should I use for primitive here?
ReedSolomonDecoder decoder = new ReedSolomonDecoder(field);
decoder.decode(data, 4);
I don't know how to create a GenericGF object from the given generator polynomial. I know that it expects a binary integer representation of the polynomial, but to do that, I would need the polynomial to be in an irreducible form, i.e. all the coefficients to be either 0 or 1. How can I achieve that from this given generator polynomial?
I'm pretty new to this as well but I think you would want to use
public static GenericGF AZTEC_PARAM = new GenericGF(0x13, 16, 1);