text:
Q: Why is ES7/array polyfill needed despite the tsconfig target is set to ES5 I have the following settings in thetsconfig.json. I added "es2017" to use Array.includes.:
{
  "compilerOptions": {
    "lib": [
      "es6",
      "es2017",
      "dom"
    ],
    "module": "es6",
    "target": "es5"
  }
}

Now, I realized, that I have to add import 'core-js/es7/array'; to the polyfills.ts, to use Array.includes also for the Internet Explorer 11. The target in the tsconfig.json is set to es5, which does not have Array.includes.
Why do I need to add the polyfill?

A: TypeScript does not auto-polyfill code (see microsoft/TypeScript#3101).  The "official" reason from the relevant GitHub issue seems to be, as @RyanCavanaugh said:

Having the compiler try to figure out which [ES20XX] methods you need, and where to emit them, and when, with controls for people who don't want the polyfills emitted, and ways to change where those polyfills come from, etc, is a big mess that isn't justified by the potential gains over simply including a normal [ES20XX] polyfill library in your script context.

And, as it's mentioned in that issue, emitting runtime code is a non-goal of TypeScript:

[Non-Goal #]6. Provide additional runtime functionality or libraries. Instead, use TypeScript to describe existing libraries.

I'm guessing that some of the confusion comes from the fact that TypeScript does downlevel some language features when targeting earlier EcmaScript versions.  The main criterion used when determining if a feature will be emitted as downleveled code or whether it needs a polyfill is syntax:
If the new language feature is syntactically invalid in the targeted version, then it will either be downleveled or you will get a compile time warning.  You can't polyfill invalid syntax. For example, class Foo {} is not and cannot be valid ES5 code... so it will be converted into a constructor function instead when targeting ES5.
If, on the other hand, the language feature is syntactically valid in the targeted version, it will be emitted as-is with no warning.  So [1,2,3].includes(0) is perfectly valid ES5 code in terms of syntax.  Assuming that someone adds an Array.prototype.includes method to an ES5 engine, it will even work at runtime.  So it is emitted as-is.  Note that when you include es2017 in your lib compiler options, you're telling TypeScript that the runtime will support ES2017 typings, and so there is no compile-time warning.  Adding typing libraries does not do anything to the runtime itself... so you're responsible for polyfilling/shimming anything you need.  From the compiler's perspective it can't deal with the situation where you lied to it about what methods exist at runtime.  Obviously that's not much consolation for someone frustrated by a runtime error, though.
Oh well, it is what it is, I guess.

Hope that helps.  Good luck!


text:
Q: Calculate the Poisson parameter given a probability I was looking at this question, but it never received an answer. Is it possible to calculate $\lambda$ (the expected number) from a probability?
I know that $\lambda$ is easily calculated if, say, we know that the P(X=0 crashes per month) = .05. Then $\lambda$ is $-\ln(.05)$ crashes per month.
But what if we are given that P(X=5 crashes per month)=.05. How would I find the expected number of crashes a month in that case? (if it is even possible)

A: I see in the comments you have reduced it to solving $$\lambda^5 e^{-\lambda} = 6$$ which has "exact" solutions in terms of the Lambert W-function, but as a practical matter you should graph it and find the solution using a computer or calculator. (You also asked about approximation methods. Though I think this is a bit of a waste of time for the question at hand... Newton's method?)
Hey, but wait... if you graph it you'll see pretty clearly that there are two real positive solutions, one between $2$ and $3$ and one between $9$ and $10$. Which one is right? Well, they actually both have to be right. In the Poisson distribution, $\lambda$ is allowed to be any positive real number, and if you set $\lambda$ to either of those in you'll get $P(X=5) = .05.$
What's going on? If you start with lambda really small, $P(X=5)$ will be tiny, and as you increase it, it will increase. Eventually it will pass $.05$. Then it will keep increasing until $\lambda=5$ and it is maximally probable that $X=5.$ Then as you increase $\lambda$ further, $X$ will start to prefer to be bigger than $5$ and the probability it is $5$ will decrease, crossing $.05$ again on the way down.
So it makes sense that there are two solutions. Also, if you picked a number much larger than $.05,$ you would risk picking it too high so that it has no solutions. In other words, even when $\lambda = 5,$ there is still not that much probability that $X=5.$

A: Given $X \sim \mathsf{Pois}(\lambda)$ and $P(X=5)=0.05,$ you seek
numerical approximations to $\lambda.$
This is to follow up on @spaceisdarkgreen's suggestion (+1). [I suggest you click to Accept that answer.]
I give code below
in R statistical software, to make the appropriate plot and get
some numerical results.
Some authors call the general method implemented in the code a grid search.
It is a brute force method that tries lots of evenly-spaced values of $\lambda$ and
picks satisfactory ones. Perhaps the method is inelegant and inefficient, but it is easy to program
and well within the capabilities of most personal computers.
There are indeed two possible solutions: (a) $\lambda_1 \approx 2.22950,$
but values between 2.157 and 2.319 give $P(X=5)=0.05$ to two places;
(b) $\lambda_2 \approx 9.42515,$ but values between 9.220 and 9.647 also
give two-place accuracy for the target probability.
With just a sketch and a bit of trial and error on a calculator you
should be able to get close enough values for $\lambda_1$ and $\lambda_2$
for your purposes.
lam = seq(.1, 12, by=.00001);  y = lam^5*exp(-lam)
plot(lam,y,type="l", col="blue", lwd=2); abline(h=6, col="darkgreen")
lam[y==max(y)]
## 5

lam = seq(.1, 3, by=.00001);  y = lam^5*exp(-lam)
lam1 = lam[abs(y-6)==min(abs(y-6))]; lam1
## 2.2395                                 # best val < 3
min(lam[round(dpois(5,lam),2)==.05])
## 2.15686
max(lam[round(dpois(5,lam),2)==.05])
## 2.31933

lam = seq(6, 10, by=.00001);  y = lam^5*exp(-lam)
lam2 = lam[abs(y-6)==min(abs(y-6))]; lam2
## 9.42515                                # best val > 6
min(lam[round(dpois(5,lam),2)==.05])
## 9.21958
max(lam[round(dpois(5,lam),2)==.05])
## 9.64665

abline(v=c(lam1,lam2), col="red")         # red lines on graph
dpois(5, lam1); dpois(5, lam2)            # probs corresp to best values
## 0.05000018
## 0.04999994

Note: The function $y(\lambda)$ of the program is the likelihood function
of $\lambda$ for data $X = 5$ (up to a constant factor). The third line
of code illustrates that, given $X = 5$, the maximum likelihood estimator
of $\lambda$ is $\hat \lambda = 5.$

redpajama_set_name: RedPajamaStackExchange


text:
Q: vector-of vs. vector in Clojure When would I use vector-of to create a vector, instead of the vector function.  Is the guideline to use vector most of the time and only for performance reason switch to vector-of?
I could not find good info on when to use vector-of.

A: vector-of is used for creating a vector of a single primitive type, :int, :long, :float, :double, :byte, :short, :char, or :boolean. It doesn't allow other types as it stores the values unboxed internally. So, if your vector need to include other types than those primitive types, you cannot use vector-of. But if you are sure that the vector will have data of a single primitive type, you can use vector-of for better performance.
user=> (vector-of :int 1 2 3 4 5)
[1 2 3 4 5]
user=> (vector-of :double 1.0 2.0)
[1.0 2.0]
user=> (vector-of :string "hello" "world")
Execution error (IllegalArgumentException) at user/eval5 (REPL:1).
Unrecognized type :string

As you can see, you should specify primitive type as an argument.
vector can be used to create a vector of any type.
user=> (vector 1 2.0 "hello")
[1 2.0 "hello"]

You can put any type when you use vector.
Also, there's another function vec, which is used for creating a new vector containing the contents of coll.
user=> (vec '(1 2 3 4 5))
[1 2 3 4 5]

Usually, you can get the basic information of a function/macro from the repl, like the following.
user=> (doc vector-of)
-------------------------
clojure.core/vector-of
([t] [t & elements])
  Creates a new vector of a single primitive type t, where t is one
  of :int :long :float :double :byte :short :char or :boolean. The
  resulting vector complies with the interface of vectors in general,
  but stores the values unboxed internally.

  Optionally takes one or more elements to populate the vector.

Reference:

*

*https://clojuredocs.org/clojure.core/vector-of

*https://clojuredocs.org/clojure.core/vector

*https://clojuredocs.org/clojure.core/vec

A: Nobody really ever uses vector-of. If you don't super care about performance, vector is fine, and if you do super care about performance you usually want a primitive array or some other java type. Honestly I would expect occasional weird snags when passing a vector-of to anything that expects an ordinary vector or sequence - maybe it works fine, but it's just such a rare thing to see that it wouldn't surprise me if it caused issues.


text:
Q: cakephp 2.6 retrieving data from database Here is my function edit in cakephp controller:
public function edit($id = null) {
if ($this->request->is('get')) {
            $this->request->data = $this->Topic->findById($id);
        }
...

First problem is that the parameter id passed to function is of type string not integer.
Second is that,in the database there is a topic with id = 14,and both these codes retrieve same result,i don't understand why:
http://localhost/cakephp1/topics/edit/14
http://localhost/cakephp1/topics/edit/14anyCharactersHere

A: The parameters being passed by the URL will of course by of type string because a URL is a string.
Assuming your id column in your database is integer Cake will cast the parameter passed to findById() to an integer: (int)"14" and (int)"14anyCharactersHere" both result in 14. Therefore, both URLs in your question will result in the same data being pulled from the database.
If you want to make sure that $id contains only an integer use ctype_digit():-
if (ctype_digit($id) === true) {
    // Is integer
}


text:
Q: Why the time cost nearly the same for 1 million rows insertion between 100 transactions and 10000 transactions in MySQL? Currently I'm working on MySQL performance investigation, speaking of the MySQL performance, I don't want the round trip to be involved, so I tested something like this:
drop table if exists tbl;
create table tbl (c1 bigint, c2 varchar(32), c3 datetime);
drop procedure if exists run_insert;
delimiter //
create procedure run_insert()
begin
    declare i int default 0;
    start transaction;
    while i < 1000000
    do
        insert into tbl values(i, rand(), now() + interval 1 second);
        set i = i + 1;
    end while;
    commit;
end//
delimiter ;
call run_insert();

It went out
mysql>
mysql> drop table if exists tbl;
Query OK, 0 rows affected (0.06 sec)

mysql>
mysql> create table tbl (c1 bigint, c2 varchar(32), c3 datetime);
Query OK, 0 rows affected (0.02 sec)

mysql>
mysql> drop procedure if exists run_insert;
Query OK, 0 rows affected (0.00 sec)

mysql>
mysql> delimiter //
mysql> create procedure run_insert()
    -> begin
    ->     declare i int default 0;
    ->     start transaction;
    ->     while i < 1000000
    ->     do
    ->         insert into tbl values(i, rand(), now() + interval 1 second);
    ->         set i = i + 1;
    ->     end while;
    ->     commit;
    -> end//
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql>
mysql> call run_insert();
Query OK, 0 rows affected (20.26 sec)

mysql>

Not bad for 20 seconds, but we all know that there is only 1 transaction despite of 1 million rows insertion, if we break it into 1 million transactions, the metrics will drop down heavily, but how the number of transactions impact the final metrics? so I did another 2 test
Break it into 100 transactions:
begin
    declare i int default 0;
    set autocommit = 0;
    while i < 1000000
    do
        insert into tbl values(i, rand(), now() + interval 1 second);
        set i = i + 1;
        if i % 10000 = 0 then
            commit;
        end if;
    end while;
    commit;
end//

Break it into 10000 transactions:
begin
    declare i int default 0;
    set autocommit = 0;
    while i < 1000000
    do
        insert into tbl values(i, rand(), now() + interval 1 second);
        set i = i + 1;
        if i % 100 = 0 then
            commit;
        end if;
    end while;
    commit;
end//

100 transaction VS 10000 transaction, with the same amount of data, there must be something different, but
mysql> call run_insert();
Query OK, 0 rows affected (22.86 sec)

VS
mysql> call run_insert();
Query OK, 0 rows affected (21.98 sec)

For the first and second code respectively, I don't get it, how it comes hardly any difference?
Update after I found something, I think this is the way how MySQL transaction works, first you let every insert a transaction, then next time you merge every two insert into a transaction, and then you merge every four insert into a transaction..., in this progress, the first several steps will bring significant performance improvement, but last ones will not, this is the reason why 100 transaction has not much diff with 10000 transactions
drop procedure if exists run_insert;
delimiter //
create procedure run_insert(in step int)
begin
    declare i int default 0;
    drop table if exists tbl;
    create table tbl (c1 bigint, c2 varchar(32), c3 datetime);
    set autocommit = 0;
    while i < 1000000
    do
        insert into tbl values(i, rand(), now() + interval 1 second);
        set i = i + 1;
        if i % step = 0 then
            commit;
        end if;
    end while;
    commit;
end//
delimiter ;
call run_insert(pow(2, 0));
call run_insert(pow(2, 1));
call run_insert(pow(2, 2));
call run_insert(pow(2, 3));
call run_insert(pow(2, 4));
call run_insert(pow(2, 5));
call run_insert(pow(2, 6));
call run_insert(pow(2, 7));
call run_insert(pow(2, 8));
call run_insert(pow(2, 10));
call run_insert(pow(2, 11));
call run_insert(pow(2, 12));
call run_insert(pow(2, 12));
call run_insert(pow(2, 14));
call run_insert(pow(2, 15));
call run_insert(pow(2, 16));
call run_insert(pow(2, 17));
call run_insert(pow(2, 18));
call run_insert(pow(2, 19));
call run_insert(pow(2, 20));

mysql> call run_insert(pow(2, 0));
Query OK, 0 rows affected (1 min 7.63 sec)

mysql> call run_insert(pow(2, 1));
Query OK, 0 rows affected (46.00 sec)

mysql> call run_insert(pow(2, 2));
Query OK, 0 rows affected (35.13 sec)

mysql> call run_insert(pow(2, 3));
Query OK, 0 rows affected (28.12 sec)

mysql> call run_insert(pow(2, 4));
Query OK, 0 rows affected (25.10 sec)

mysql> call run_insert(pow(2, 5));
Query OK, 0 rows affected (23.87 sec)

mysql> call run_insert(pow(2, 6));
Query OK, 0 rows affected (22.48 sec)

mysql> call run_insert(pow(2, 7));
Query OK, 0 rows affected (21.70 sec)

mysql> call run_insert(pow(2, 8));
Query OK, 0 rows affected (20.84 sec)

mysql> call run_insert(pow(2, 10));
Query OK, 0 rows affected (21.71 sec)

mysql> call run_insert(pow(2, 11));
Query OK, 0 rows affected (22.78 sec)

mysql> call run_insert(pow(2, 12));
Query OK, 0 rows affected (20.84 sec)

mysql> call run_insert(pow(2, 12));
Query OK, 0 rows affected (20.48 sec)

mysql> call run_insert(pow(2, 14));
Query OK, 0 rows affected (21.93 sec)

mysql> call run_insert(pow(2, 15));
Query OK, 0 rows affected (20.59 sec)

mysql> call run_insert(pow(2, 16));
Query OK, 0 rows affected (20.76 sec)

mysql> call run_insert(pow(2, 17));
Query OK, 0 rows affected (21.07 sec)

mysql> call run_insert(pow(2, 18));
Query OK, 0 rows affected (21.37 sec)

mysql> call run_insert(pow(2, 19));
Query OK, 0 rows affected (20.77 sec)

mysql> call run_insert(pow(2, 20));
Query OK, 0 rows affected (20.87 sec)

A: You're still not starting and committing the transactions properly.
When i == 0, the modulus condition succeeds, you start a transaction, insert a row, then commit that transaction.
On the next iteration, when i == 1, you don't start a transaction, you insert a row, then don't commit anything.
So you're doing every insert in its own transaction.
You need to start a new transaction after every commit, except the last one.
begin
    declare i int default 0;
    start transaction;
    while i < 1000000
    do
        insert into tbl values(i, rand(), now() + interval 1 second);
        if i % 100 = 0 then
            commit;
            if i != 999999 then
                begin transaction;
            end if;
        end if;
        set i = i + 1;
    end while;
    commit;
end//


text:
Q: Suspend/Hibernate/restore and Reboot problems 15.04 Dell Inspiron 3451 There are many posts and questions about problems with lid closing leading to operating system states which require hard reboots; these reports come from  across multiple kernels and releases of Ubuntu.  I am working with a 3.19.0.26 kernel, 15.04 Ubuntu (32 bit), and a Dell Inspriron 3451.  Some have suggested adding programs to the sleep.d folder (although this has not led to success for me, yet), others have suggested setting acpi=off in the boot loader options (also, not successful for me). Others have suggested moving to the upstream kernels (have not tried yet), and I am aware that these particular models are not certified by Canonical for Hibernate or Hybrid Suspend, but I do not yet understand if this rules out all options. Even a "stay running" option would be preferable.
All I am hoping to do is to have a valid OS when I re-open the lid.   It is not clear to me which path I might pursue - boot options, programs in sleep.d, etc. I'd welcome tactical advise and I am running from place to place without a plan.
Suggestions sought.
R

A: Is this laptop running on the newer Intel Atom SoC CPUs by any chance (Celeron / Pentium Nxxx)?
Did you experience problems while installing the system or did you take any advanced options (turning of ACPI before the installation, etc.)?
As far as I know, this problem is common with the above mentioned processors and the only solution I've found so far was to blacklist the module "dw_dmac", by doing the following:
Open a terminal window, then enter:
sudo nano /etc/modprobe.d/blacklist.conf

In the opened file, add the following lines:
blacklist dw_dmac
blacklist dw_dmac_core

Then save with Ctrl+O and close the file with Ctrl+X.
Now, hibernation should work.
If this does not work for you, I don't see an option for you besides reinstalling the system. You could either try the new kernel on 15.10 when it is released tomorrow or go back to 12.04, which should work reliably for you, if you are not in need of using a newer version, at least for a while.


text:
Q: How to import a certificate in java? I got a certificate .cer and I'd like a script to import it in the Trusted Publisher list of certificate.
I managed to do this thing in C#
X509Certificate2 certificate = new X509Certificate2(filePath.Text, "Telecomitalia1?12524", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
X509Store store = new X509Store(StoreName.TrustedPublisher);
store.Open(OpenFlags.ReadWrite);
store.Add(certificate);
store.Close();

Is there a way to do the same in Java?
Thanks a lot.

A: You can do the equivalent in Java. Check out the MSCAPI provider.

Provides direct read-write access to MS Window's keystores. The Windows-MY keystore contains the user's private keys and the associated certificate chains. The Windows-ROOT keystore contains all root CA certificates trusted by the machine.

KeyStore ks = KeyStore.getInstance("Windows-ROOT");
// Note: When a security manager is installed,
// the following call requires SecurityPermission
// "authProvider.SunMSCAPI".
ks.load(null, null);
ks.setCertificateEntry("alias", cert);
ks.store(null, null); //again the permissions here...

A: The way java handles certificates is very different to how Windows handles certificates. Windows provides predefined stores for certificates for the machine account, user accounts and service accounts, and distinguishes certificates based on their purpose (e.g. personal vs trussted CA.)
Java simply provides the concept of the Keystore - an arbitrary file of your choosing where certificates are stored. There is a default keystore used by the JDK for trusted CAs, located at$JAVA_HOME/jre/lib/security/cacerts.
To import the certificate into a keystore, you can use the keytool that is shipped with the JDK - which keystore you use depends upon your application.
See

*

*KeyTool

*Most common keytool commands

A: Using the keytool, like the Java tutorial explains so well.

A: If you want to do it from code (not with the keytool utility) then this article will get you started.


text:
Q: passing param to a method exposed from another controller I want to pass params to method declared in controller B, says it's conB.js and look like this
module.exports.verify = function(req,res,next){
// how to get it here?
}

Then now I'm have conA.js, how can I pass arguments to it?
I know firstly I have to include it,
var ConB = require('ConB');

but how to pass param to verify method like ConB.verify('param') so that I can get it in ConA.js?

A: Not sure I undestand what you are trying to do but if you want to call verify with a parameter you have to define as a function accepting the parameter. So conB.js is:
module.exports.verify = function(param){
   // do something with param
   return something;
}

Then in conA.js:
var conB = require('./conB.js');
var result = conB.verify(your_param);

Update after comment...
You can also write the different controllers as express middleware and pass parameters along using res.locals. See: http://expressjs.com/en/guide/using-middleware.html
In this case you need a route in you app that calls the middlewares in sequence:
app.use("/testUrl", consB.verify, cansA.doSomething);

Then consB.js is something like:
module.exports.verify = function(req, res, next){
   // do something with param and store something in res.locals
   res.locals.user = "foo";
   // then remember to call next
   next();
}

ConsA.js
module.exports.doSomething = function(req, res, next) {
    // use locals modified by previous middleware
    res.end("The user of the request is: "+res.locals.user);
}

A: file - conB.js
module.exports.verify = function(req,res,next){

}

file -  conA.js
//here you want to use exported object from conB.js
So what you can do this if both the files are in same folder otherwise you have to use relative paths.
 var conB = require('./conB.js')


text:
Q: Passing array from javascript to ASP.NET I have a simple 2D array in javascript. I want to pass this array to a ASP.NET page.
I wanted to know what would be the best option, going with JSON or XML.
The metric is speed and size of the data. In some cases, the array may be long in size.
Thank You.

A:
The metric is speed and size of the data.

JSON is faster then XML in terms of speed. It's smaller then XML in terms of size.
XML is bloated to allow you to represent and validate structures.
However there are various BSON formats around where people take JSON and then hand optimise the storage format excessively. (BSON is binary JSON)
Some BSON spec I picked from google
Bison, A JavaScript parser for some arbitary BSON format.
Now if you really have bottlenecks with transferring data (which you probably don't) you may want to use WebSockets to send data over TCP rather then HTTP, thus reducing the amount of traffic and data you send.
Of course you only care about that if you making say X000 requests per second.

A: JSON Should be your best bet XML datatype sending might be a big pain as sometimes you would have to add in new configs just to support XML datatype to be sent as form data to the server. Genreally it is not a recommended practice due to security concerns


text:
Q: Powershell function's default parameter does not work I have a function in a module I created:
   function New-MyAppDeployment {
   param
   (
        [string]$ConfigPath = "C:\Projects\MyApp\Environments",
        [string]$EnvName,
        [string]$EnvironmentFile
   )
   # Do some things with the above parameters
   if(!$EnvironmentFile)
   {
       $envFilename = $EnvName + ".json";
       $EnvironmentFile = Join-Path $ConfigPath $envFilename

   }

   $settings = Get-Content -Raw -Path $EnvironmentFile | ConvertFrom-Json

   return $settings
   }
   Export-ModuleMember -function New-MyAppDeployment

I then call it like this:
    Import-Module -Force $PSScriptRoot\myapp.psm1
       $newSettings = New-MyAppDeployment -EnvName "dev"
but $ConfigPath always is set to an empty string when I'm inside the function.
Any ideas what could cause this?

A: It seems to have corrected itself. Perhaps restarting the ISE did the trick, but now $ConfigPath has the correct value when stepping through the code.


text:
Q: Unit Testing Synchronous Method With Code Calling Task Given the following class:
public class TestAttribute : ActionFilterAttribute
{
    public bool SomeExampleBool = false;

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        Task.Factory.StartNew(() => { SomeExampleBool = true; });
    }
}

How would you write a valid unit test for OnActionExecuting that Asserts that SomeExampleBool is equal to true?
When writing a unit test and calling OnActionExecuting, then calling the Assert, the logic executes on a thread that will not have executed yet.  So the Assert fails.  Would you try something like Thread.Sleep for a couple of seconds?  Seems like a hack.  I'm sure there is a better way that I'm not thinking of but I'm reaching out to the community for some help.

A: You'll need to expose the Task returned by StartNew to anyone that you want to be able to:

*

*Know when the operation finishes (by adding a continuation to it)

*Know what the result is, if applicable

*Know what any exceptions were, if applicable

*Know if it was cancelled

*Wait until it has finished

Since you're not exposing the return Task to anyone, you're just dropping it on the floor, there's no way for anyone else to wait on it, or run a continuation when it's done.  Typically you'd return the Task from that method.  If you can't, because it's an event handler, then you could potentially store the Task in a field or some other form of state that the caller would be able to access.

A: Task.Factory.StartNew will return an instance of a Task.  If you call task.Wait(), you'll be guaranteed that the task will complete before executing the next line.  You should be able to just Wait for the task to complete, and then run your assertions after that.


text:
Q: Operations on only some values of a column filtered by ANOTHER COLUMN in a dataframe Given a dataframe like this:
df = pd.DataFrame([[11, 1, 1, 1, 1], [12, 2, 2, 2, 2], [12, 3, 3, 3, 3], [14, 4, 4, 4, 4]], columns=['a', 'b', 'c', 'd', 'e'])

    a   b   c   d   e
0   11  1   1   1   1
1   12  2   2   2   2
2   12  3   3   3   3
3   14  4   4   4   4

I want to exchange values in column 'd' for rows having value == 12 in column a.
Final output should look like this:
    a   b   c   d  e
0   11  1   1   1  1
1   12  2   2   3  2
2   12  3   3   2  3
3   14  4   4   4  4

How can I achieve this?
I have tried these:
df[df["a"] == 12]['d'] = df[df["a"] == 12]['d'].map({2: 3, 3: 2})

df.loc[df.a == 12]["d"].replace({2: 3, 3: 2}, inplace=True)

but these do not modify the original dataframe, though we can see changes in the series df[df["a"] == 12]['d'].map({2: 3, 3: 2}).

A: Can you show your code? If you use loc then, it changes the original one like below.
>>> df.loc[1, 'd'] = 3
>>> df
   a  b  c  d
0  1  1  1  1
1  2  2  2  3
2  3  3  3  3
3  4  4  4  4


text:
Q: Make variants based on alphabet-number junction in regex I have a list of words, some of which are single words, some multi-word and the words may or may not have digit characters.
An example -
word_list=['word', 'kap1','another word', 'another-1 word', 'another word 1']
I want to identify single-word entries in the list, of the form -
alphabets*Junction*digit(s)
where Junction can be either space, or hyphen or nothing. For example in the list above, kap1 qualifies (and no other entry does). Now, having found this entry, I want to create variants (based on the junction) of this entry, and add them to the list.
So for example, having found kap1, I want to add kap 1 and kap-1 to the list.
I was able to write the initial regex for identifying the entries -
Word_NumberRegex=re.compile(r"^[a-zA-Z]+[ -]?\d+$")
but I wanted to know a good algorithm for the creation of the variants, depending on the junction.

A: Use re, you can capture the matched patterns, and reformat with customized separators:
word_list=['word', 'kap1','another word', 'another-1 word', 'another word 1']

import re
p = r'([a-zA-Z]+)[- ]?([0-9]+)'
[re.sub(p, r'\1{}\2'.format(sep), w) for w in word_list if re.fullmatch(p, w) for sep in ['', ' ', '-']]

# ['kap1', 'kap 1', 'kap-1']

Precompile the pattern:
p = re.compile(r'([a-zA-Z]+)[- ]?([0-9]+)')
[p.sub(r'\1{}\2'.format(sep), w) for w in word_list if p.fullmatch(w) for sep in ['', ' ', '-']]

# ['kap1', 'kap 1', 'kap-1']

A: You can use 3 capturing groups and use the middle group to capture junction character. Use junction character to search a list of separators and get your desired output:
import re

word_list=['word', 'kap1', 'another word', 'abc-123', 'another-1 word', 'another word 1']

reg = re.compile(r'^([a-zA-Z]+)([- ]?)([0-9]+)$')

for w in word_list:
   m = reg.match(w)
   if m:
      result = []
      seps = ['', ' ', '-']
      seps.remove(m.group(2))
      for s in seps:
         result += [m.group(1) + s + m.group(3)]
      print result

Output:
['kap 1', 'kap-1']
['abc123', 'abc 123']

Code Demo


text:
Q: Definition List Alignment with Missing Definitions I frequently have applications where forms have optional fields. When these records are displayed in the Show view, the definitions "collapse" together and don't line up with their respective labels. For example, if I have 3 fields and they should look like this:
Phone:  312-555-1212
FAX:
Mobile: 312-555-1234

They end up looking like this:
Phone:  312-555-1212
FAX:    312-555-1234
Mobile:

I've figured a hack to throw a non-breaking space (%nbsp) just before every closing "dd" tag, but that doesn't seem very DRY.
Is there a better way to do this with CSS?
Here is my Rails/HTML code as it stands with the non breaking spaces. It works, but, I'm trying to see if there is a better way.

FAX:

<%= number_to_phone(@user.fax, :area_code => true) %>

Pager:

<%= number_to_phone(@user.pager, :area_code => true) %>

Mobile:

<%= number_to_phone(@user.mobile, :area_code => true) %>

So by putting the non-breaking space just before the closing "dd" tag, I'm tricking the system into thinking there is content in a field that doesn't have any content and putting the next item on the next line rather than moving it up so it doesn't align with it's label anymore.

A: I think you are missusing definition lists. Thy normally render like (dd of Honey is empty):

So you must use some positioning in your css to allign the "definitions"
use tables to display tables, labels to display labels and css to format it!


text:
Q: SOAP web API request returns HTML instead of XML I'm new to SOAP API.
I'm using the following code to access my API.
NSString *stringURL=[NSString stringWithFormat:@"http://tennispro.co.in/services.asmx"];

// Allocate and initialize an NSURLConnection with the given request and delegate. The asynchronous URL load process is started as part of this method.

NSString *soapMessage = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                         "<soap:Body>"
                         "<ReturnSyncMasterData xmlns=\"http://tempuri.org/\">"
                         "<datetime>%@</datetime>"
                         "</ReturnSyncMasterData>"
                         "</soap:Body>"
                         "</soap:Envelope>",@""];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:stringURL]];

[request addValue:@"text/html; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"2159" forHTTPHeaderField:@"Content-Length"];
[request addValue:@"private, max-age=0" forHTTPHeaderField:@"Cache-Control"];
[request addValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
[request addValue:@"http://tempuri.org/services/ReturnSyncMasterData" forHTTPHeaderField:@"SOAPAction"];
[request setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:@"POST"];

theConnection = [NSURLConnection connectionWithRequest:request delegate:self];

if (theConnection) {
    receivedData = [[NSMutableData alloc] init];
}

But in response I get HTML instead of XML. I want to access ReturnSyncMasterData soap action, but I'm unable to call it.

A: set content type to text/xml
[request addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"2159" forHTTPHeaderField:@"Content-Length"];
[request addValue:@"private, max-age=0" forHTTPHeaderField:@"Cache-Control"];
[request addValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
[request addValue:@"http://tempuri.org/services/ReturnSyncMasterData" forHTTPHeaderField:@"SOAPAction"];
[request setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:@"POST"];

theConnection = [NSURLConnection connectionWithRequest:request delegate:self];

if (theConnection) {
    receivedData = [[NSMutableData alloc] init];
}


text:
Q: Extracting all keyframes with FFmpeg as quickly as possible from .mp4 From other answers here I've found this to be the supposedly quickest way to extract all keyframes from .mp4 videos:
ffmpeg -skip_frame nokey -i in -vf "scale=320:-1" -vsync 0 -q:v 2 out%07d.png

However, when I try this on a 7.9 second .mp4 file, only 2 frames are outputted where I would expect 8 since the video is 30 fps and keyframes are once every 30 frames in this file.


text:
Q: How to set textfield character limit SwiftUI? I'm using SwiftUi version 2 for my application development. I'm facing issue with textfield available in SwiftUI. I don't want to use UITextField anymore. I want to limit the number of Characters in TextField. I searched a lot and i find some answer related to this but those answer doesn't work for SwiftUI version 2.
class textBindingManager: ObservableObject{
    let characterLimit: Int
    @Published var phoneNumber = "" {
        didSet {
            if phoneNumber.count > characterLimit && oldValue.count <= characterLimit {
                phoneNumber = oldValue
            }
        }
    }
    init(limit: Int = 10) {
        characterLimit = limit
    }
}

struct ContentView: View {
    @ObservedObject var textBindingManager = TextBindingManager(limit: 5)
    var body: some View {
        TextField("Placeholder", text: $textBindingManager.phoneNumber)
    }
}

A: No need to use didSet on your published property. You can add a modifier to TextField and limit the string value to its prefix limited to the character limit:
import SwiftUI

struct ContentView: View {
    @ObservedObject var textBindingManager = TextBindingManager(limit: 5)
    var body: some View {
        TextField("Placeholder", text: $textBindingManager.phoneNumber)
            .padding()
            .onChange(of: textBindingManager.phoneNumber, perform: editingChanged)
    }
    func editingChanged(_ value: String) {
        textBindingManager.phoneNumber = String(value.prefix(textBindingManager.characterLimit))
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

class TextBindingManager: ObservableObject {
    let characterLimit: Int
    @Published var phoneNumber = ""
    init(limit: Int = 10){
        characterLimit = limit
    }
}

A: The following should be the simpliest.  It limits the number of characters to 10.
struct ContentView: View {
    @State var searchKey: String = ""

    var body: some View {
        TextField("Enter text", text: $searchKey)
            .onChange(of: searchKey) { newValue in
                if newValue.count > 10 {
                    self.searchKey = String(newValue.prefix(10))
                }
            }
    }
}

A: This solution wraps everything up in a new Component. You could adapt this to perform other parsing / pattern checking quite easily.
struct ContentView : View {
    @State private var myTextValue: String = ""

    var body: some View {
        LimitedTextField(value: $myTextValue, charLimit: 2)
    }
}

struct LimitedTextField : View {
    @State private var enteredString: String = ""
    @Binding var underlyingString: String
    let charLimit : Int

    init(value: Binding<String>, charLimit: Int) {
        _underlyingString = value
        self.charLimit = charLimit
    }

    var body: some View {
        HStack {
            TextField("", text: $enteredString, onCommit: updateUnderlyingValue)
                .onAppear(perform: { updateEnteredString(newUnderlyingString: underlyingString) })
                .onChange(of: enteredString, perform: updateUndelyingString)
                .onChange(of: underlyingString, perform: updateEnteredString)
        }
    }

    func updateEnteredString(newUnderlyingString: String) {
        enteredString = String(newUnderlyingString.prefix(charLimit))
    }

    func updateUndelyingString(newEnteredString: String) {
        if newEnteredString.count > charLimit {
            self.enteredString = String(newEnteredString.prefix(charLimit))
            underlyingString = self.enteredString
        }
    }

    func updateUnderlyingValue() {
        underlyingString = enteredString
    }
}


text:
Q: What is the general solution to differential equation $\frac{d^{2}y}{dx^2} = [1 + \frac{dy}{dx}]^2$ What is the general solution to differential equation $\frac{d^{2}y}{dx^2} = [1 + \frac{dy}{dx}]^2$
I have tried squaring it both sides, but it didn't helped, please tell me how to solve the problems with degree more than 1.

A: $$\dfrac{dv}{dx}=(1+v)^2$$ where $v=\dfrac{dy}{dx}$
Integrate both sides
$-\dfrac1{1+v}=x+c$ where $c$ is an arbitrary constant
$\implies \dfrac{dy}{dx}=v=-\dfrac1{x+c}-1$
Integrate both sides

A: Take dy/dx=t
Then equation changes to:
$dt/dx=(1+t)^2$.can you proceed now?


text:
Q: PHP double line break between arrays in while loop Im stuck on an issue I just cant solve. Ive thought about how, looked it up, and have not yielded any results.
Im trying to use an array in an email, and I need a double line break between them.
Im creating two arrays from within a mysql query results loop like so:
while($row = $result->fetch_assoc()){
        $updated_email_array['Clinic']=$row['clinic_name'];
        $updated_email_array['Email_Credits_To_Add']=$row['email_allotment'];
        $updated_email_array['SMS_Credits_To_Add']=$row['sms_allotment'];
        $updated_email_array['Email_Credits_Rolling_Over']=$row['$email_left'];
        $display_email_array[] = $updated_email_array;
}

Im then parsing out the values and adding them to a variable to be nested in an email, like so:
$intouch_credit_refill_message = "Credit Refill Report\n\n";
foreach ($display_email_array as $each_member) {
    while (list($key, $value) = each ($each_member)) {

        $intouch_credit_refill_message .= "$key: $value\n";

    }

}

Lastly, im sending $intouch_credit_refill_message in an email
mail($email address,"Credit Refill Record",$intouch_credit_refill_message,"From: email@address.com");

This gives me:
Credit Refill Report

Clinic: Royal York Animal Hospital
Email_Credits_To_Add: 5000
SMS_Credits_To_Add: 500
Email_Credits_Rolling_Over: 100200
Smail_Credits_Rolling_Over: 10050
New_Email_Credit_Allotment: 105200
New_SMS_Credit_Allotment: 10550
Clinic: Jason's Test Clinic
Email_Credits_To_Add: 5000
SMS_Credits_To_Add: 500
Email_Credits_Rolling_Over: 75000
Smail_Credits_Rolling_Over: 7500
New_Email_Credit_Allotment: 80000
New_SMS_Credit_Allotment: 8000

But I Need:
Credit Refill Report

Clinic: Royal York Animal Hospital
Email_Credits_To_Add: 5000
SMS_Credits_To_Add: 500
Email_Credits_Rolling_Over: 100200
Smail_Credits_Rolling_Over: 10050
New_Email_Credit_Allotment: 105200
New_SMS_Credit_Allotment: 10550

Clinic: Jason's Test Clinic
Email_Credits_To_Add: 5000
SMS_Credits_To_Add: 500
Email_Credits_Rolling_Over: 75000
Smail_Credits_Rolling_Over: 7500
New_Email_Credit_Allotment: 80000
New_SMS_Credit_Allotment: 8000

I cant figure out how to add a break like that between the arrays in the loop where they are added to the email line.
Thank you for any help you might give.

A: Just add another new line in your foreach loop like this:
foreach ($display_email_array as $each_member) {
    while (list($key, $value) = each ($each_member)) {

        $intouch_credit_refill_message .= "$key: $value\n";

    }

    $intouch_credit_refill_message .= "\n";

}

A: At any-time in PHP if you need a line break or a tab just do this
echo "\r\n";

echo "\t";

You can also use PHP_EOL when you want a new line, and you want to be cross-platform.
php reference:
PHP_EOL (string)
    The correct 'End Of Line' symbol for this platform. Available since PHP 5.0.2


text:
Q: Make an android phone to pose as a Bluetooth input device (mouse or keyboard) Is it possible to make an android phone app that will make the phone implement and broadcast the required data to pose as a Bluetooth mouse so that other devices (PC, XBOX, PS, Other android devices) could recognize it as a mouse or a keyboard ?

A: Just googled it...try this apk and let us know your views:https://code.google.com/p/androhid/

A: blueputdroid and androhid are supposed to be able to do this. Both require root.
I couldn't get either app to work on CyanogenMod 11
blueputdroid
blueputdroid is supposed to work best on old versions of android as google supposedly changed something in their bluetooth stack in 4.2 that made it incompatible. From what i understand from this thread on xda it doesn't seem like there's any plans on supporting newer Android versions
androhid
Isn't available in the play store or f-droid repos. Download apk from: https://code.google.com/p/androhid/
I couldn't get this to work. Crashed with "unexpected error" on launch.


text:
Q: Configurar HTTPS em WebApi Fiz um Web Service utilizando WebApi MVC5, com Visual Studio 2017. Está funcionando, mas como faço para utilizar HTTPS ao invés de HTTP? Alguém tem algum material pra eu pesquisar? Encontrei algumas coisas mas com WCF e não com Web Api.

A: Segue link com 2 materiais bem interessantes sobre o assunto:
Working with SSL in Web API
https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/working-with-ssl-in-web-api
e Using SSL in ASP.NET Web API
http://www.codeguru.com/csharp/.net/using-ssl-in-asp.net-web-api.htm
Abs.


text:
Q: Algebra with congruence classes. Consider $x^2=[2]_7$ where $[2]_7$ is the congruence class of $a$ modulo $m$, or
$$[2]_7=\{x\in\mathbb{Z} \ | x\equiv 2 \ (\text{mod} \ 7)\}.$$
It is immediately obvious, by inspection, that $x=[3]_7$ and $x=[4]_7$, but is there any way to analytically attain these solutions?

A: $
x^2 \equiv 2
\iff
4x^2 \equiv 8
\iff
(2x)^2 \equiv 1
$
$\iff$
$7$ divides $(2x)^2 - 1 = (2x-1)(2x+1)$
$\iff$
$7$ divides $2x-1$ or $7$ divides $2x+1$
$
\iff
2x \equiv \pm 1
\iff
8x \equiv \pm 4
\iff
x \equiv \pm 4
$
In this case we are lucky that the inverse of $2$ is clearly a square.
In other cases, we might not be so lucky: if we replace $7$ by $23$, then the inverse of $2$ is $12$, not clearly the square of $14$.

A: Just compute the squares in $\mathbf Z/7\mathbf Z=\bigl\{0,\pm 1,\pm 2,\pm3\bigr\}$:
$$0^2=0,\quad (\pm1)^2=1,\quad (\pm2)^2=-3,\quad (\pm3)^2=2,$$
hence the solutions are $3$ and $-3\equiv 4\mod7$.


text:
Q: How does DNS work with websites that have large traffic and multiple servers? Based on what I learned from CS50x, each computer on the internet has its own unique public IP address. Some computers are used on the client-side to access websites, while other computers are used as servers that respond to requests (by providing data from their computers' databases, or more generally, fulfilling some "service(s)" for the client). When a client visits a website, they must make a request through their address bar for the specific server whose service they want to access, which they typically do by typing in a domain name (which was created for the purpose of not having to make users remember the IP addresses of websites that they visit). However, the domain name must then be "converted" to an IP address for the request to be processed, which the DNS is responsible for. Up until this point, there is one point that confuses me:
Why is it necessary for the domain names to be converted to IP addresses for a server to be accessed by the client? My hypothesis is that it has to do with the fact that a single domain name can "map to" multiple computers and hence IP addresses and so it is necessary to identify each computer separately. Also, perhaps it allows for "nodes" (computer networks) on the "global" network to be identified in a more standardized way (as computers that do not act as web servers do not have domain names). In any case, a more thorough explanation would be much appreciated.
Now, I also learned that some websites cannot be hosted on a single computer, as they have too much traffic, which would make them too slow to run on only one computer. This implies that the website would have multiple IP addresses used to host it. In that case, how would DNS convert a domain name into an IP address? If DNS chooses to return one IP address over another when the domain name is given to it, how would the client obtain access to the part of the website that is not "on that particular computer server"? What I mean by that is let's say we're considering a website with a huge database such as Yahoo Finance. There is likely more than one computer server hosting the website. Let's say that each computer stores a chunk of the database (as the database is too large for one computer to store in its entirety). Then, if a client makes a request to the server using a domain name, how would the DNS know to return the IP address of the particular computer that contains the information that a user is looking for?

A:
Why is it necessary for the domain names to be converted to IP addresses for a server to be accessed by the client?

Because the Internet works on IP addresses - either IPv4 or IPv6. It consists of a large number of IP networks that are interconnected by gateways.
There's no way you can use DNS names for routing. Any name needs to be translated into an IP address before you can send a request. You can consider DNS as an add-on or overlay. Basically, it's only there for us humans, so we don't have to remember IP addresses (not entirely true, but let's leave it at that here).

In that case, how would DNS convert a domain name into an IP address?

There's a large number of ways to do load balancing. You can resolve a single DNS name to multiple IP addresses, use a load balancer in front of a server cluster, distribute web data objects across multiple named servers, distribute servers with the same IP addresses geographically (anycast), and many more, in almost any combination.

If DNS chooses to return one IP address over another when the domain name is given to it, how would the client obtain access to the part of the website that is not "on that particular computer server"?

DNS simply provides records for name resolution. The client needs to make sense of it. If a DNS record resolves to multiple IP addresses, usually the clients just picks the first or a random one. The server(s) behind each address must be able to fulfill any reasonable request. There's no "dunno, ask another one" reply, the client only tries another one if it is unable to make a connection.
Distributed databases are something completely different altogether. Basically, they are not queried/used by the client directly but by the server backend.

A:
Why is it necessary for the domain names to be converted to IP addresses for a server to be accessed by the client? My hypothesis is that it has to do with the fact that a single domain name can "map to" multiple computers and hence IP addresses and so it is necessary to identify each computer separately. Also, perhaps it allows for "nodes" (computer networks) on the "global" network to be identified in a more standardized way (as computers that do not act as web servers do not have domain names). In any case, a more thorough explanation would be much appreciated.

It doesn't have anything to do with domain names being able to map to different IPs. That's just how the Internet is built, like @Zac67 says.
Every computer that is on the Internet has a public IP address assigned to it. For a computer to send a packet of data to another, it has to know the IP address of the computer it is sending the packet to (the IP is stored inside every packet sent).
When you access a website via a domain for e.g., you are basically sending packets to it to tell it "hey, give me the data for this webpage", so you need to know its IP address to do so in the first place.

In that case, how would DNS convert a domain name into an IP address?

The DNS works on many levels. You have a DNS lookup table on your own computer (try and find the hosts file on your computer). Your ISP will provide a set of DNS servers for you too, and you can also specify your own DNS servers for your modem if you know how.
Some of these DNS lookup tables will have precedence over others. Your local DNS lookup table for example, supercedes over everything (so you can use it to route traffic wherever you want).

If DNS chooses to return one IP address over another when the domain name is given to it, how would the client obtain access to the part of the website that is not "on that particular computer server"?

This is quite complex. Usually, big web servers split up their computers into application servers (which don't contain any data) and CDN servers / databases (which stores data such as photos or say your personal data). The DNS usually points to application servers, which just gives you the code needed to generate the webpage. These generated codes then 1) accesses data from databases to serve, as well as 2) tells the client (your browser) to retrieve media from CDN servers.
These databases and CDN servers have ways to synchronise their data across different servers, and they are specially built for that. If you want to see an example of a CDN, just look at the URL for any image on Facebook.

Then, if a client makes a request to the server using a domain name, how would the DNS know to return the IP address of the particular computer that contains the information that a user is looking for?

See the above point.


text:
Q: Need to do equivalent of .Any in Entity Framework without navigation property My database has two tables, Reads and Alarms.  There is a one to many relationship from the Reads (1) to the Alarms (many) table.  For various reasons, the foreign key constraint on the Alarms table was deleted.  I cannot restore this constraint.  The Read object in my Entity Framework model consequently does not have an Alarms navigation property.
I have a boolean property in my ReadViewModel class called HasAlarms.  I want this to be set to true if there is at least one row in the Alarms table that is related to the Read.  I know that if the Alarms navigation property were there, I could do this with something like this:
var reads = from read in context.Reads
            select new ReadViewModel { . . . };

foreach ( ReadViewModel read in reads ) {
    read.HasAlarms = read.Alarms.Any();
}

However, I don't have the Alarms navigation property any more.  What is the most efficient way to do this in my current situation?
Tony

A: You'll need something like this:
foreach ( ReadViewModel read in reads ) {
    read.HasAlarms = context.Alarms.Any(a => a.ReadId == read.Id);
}

Also you can perform join, to get state in one query:
var results = from r in reads
join a in context.Alarms on r.Id equals a.ReadId into ra // perform a left join
from a in ra.DefaultIfEmpty()                            // on Alarms
select new { Read = r, HasAlarm = a != null };

foreach (var res in results)
   res.Read.HasAlarm = res.HasAlarm;


text:
Q: python finditer get start end of capture group I am trying to capture the start and end of a capture group for each group found using the finditer() method in re.
For example:
strng = 'move 12345-!'
matches = re.finditer('move ([0-9]+).*?', strng)
for each in matches:
    print(*each.groups())
    print(each.start(), each.end())

This will yield the start and end index position, but of the matched pattern and not specifically the captured group. I essentially want to always capture the number as this will change. The word move will always be an anchor, but I don't want to include that in the position, as I need to capture the actual position of the numbers found within the text document so that I can do slicing for each number found.
Full document might be like:
move 12345-!
move 57496-!
move 96038-!
move 00528-!

And I would capture 57496 starting/ending document[17:21] where start of the 57496 is at 17 and end is at 21. The underlying positions are being used to train a model.

A: If you don't want move  to be part of the match, you can turn it into a positive lookbehind to assert it to the left.
Then you can use each.group() to get the match.
Note that you can omit .*? at the end of the pattern, as it is a non greedy quantifier without anything after that part and will not match any characters.
import re

strng = 'move 12345-!'
matches = re.finditer('(?<=move )[0-9]+', strng)
for each in matches:
    print(each.group())
    print(each.start(), each.end())

Output
12345
5 10

A: >>> import re
>>> strng = "move 12345-!"
>>> matches = re.finditer('move ([0-9]+).*?', strng)
>>> for each in matches:
    print(each.group(1))
    print(each.start(1), each.end(1))

12345
5 10
>>>


text:
Q: How to measure frequency in arduino using pulseIn() function? i am newbie in arduino and i have small project
 i read that pulseIn function return  length of the pulse in microseconds and

frequency(HZ)=1/time(second)

so i hope below code to measure frequency value is correct otherwise please notify me
int senserpin=8;
int sensordelay=1000;
float duration;
float freq;

void setup{
pinMode(senserpin,INPUT);
serial.begin(9600);
}

void loop()
{
duration=pulsein(senserpin,high)
freq=1/(duration*1000000)// multiply duration *1000000 to convert from microseconds to seconds
serail.print("frequency");
serail.print(freq);

delay(sensordelay)
}

A: You measured only high time. You need to measure both for calculating frequency and period. I hope this will work for you.
int highTime;    //integer for storing high time
int lowTime;     //integer for storing low time
float period;    // integer for storing period
float freq;      //storing frequency

void setup()
{
    pinMode(8,INPUT);  //Setting pin as input
}

void loop()
{
    highTime=pulseIn(8,HIGH);  //read high time
    lowTime=pulseIn(8,LOW);    //read low time
    period = highTime+lowTime; // Period = Ton + Toff
    freq=1000000/period;       //getting frequency with totalTime is in Micro seconds
    delay(1000);
}

A: Frequency is the time between two identical events (e.g. from one rising edge to the next rising edge)
pulseIn only measures the time of a part of that period (e.g. how long the signal is HIGH)
You either know that HIGH phase has the same duration as LOW phase, or you have to measure both.


text:
Q: Error EF Core PostgreSQL during an entity insert I am getting an error during an entity insert. I am using the Entity Framework Core with the PostgreSQL.
Here is a piece of code which produces an error:
public async Task Add(AddVideoDto dto)
{
    var videoModel = mapper.Map<Video>(dto);
    await context.Videos.AddAsync(videoModel);
    await context.SaveChangesAsync();
}

Here is the error log:
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]                                            et/oklike/oklikebe (master)
      An error occurred using the connection to database 'oklikedb' on server 'tcp://127.0.0.1:5432'.
fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HLVLRDVR67DK", Request id "0HLVLRDVR67DK:00000001": An unhandled exception was thrown by the application.
System.InvalidOperationException: Reset() called on connector with state Connecting
   at Npgsql.NpgsqlConnector.Reset()
   at Npgsql.ConnectorPool.Release(NpgsqlConnector connector)
   at Npgsql.NpgsqlConnection.<Close>g__FinishClose|76_1(NpgsqlConnection connection,
NpgsqlConnector connector)
   at Npgsql.NpgsqlConnection.Close(Boolean wasBroken, Boolean async)
   at Npgsql.NpgsqlConnection.CloseAsync()
   at Npgsql.NpgsqlConnection.DisposeAsync()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.DisposeAsync()
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.<>c__DisplayClass15_0.<<DisposeAsync>g__Await|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.<>c__DisplayClass15_0.<<DisposeAsync>g__Await|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Http.Features.RequestServicesFeature.<DisposeAsync>g__Awaited|9_0(RequestServicesFeature servicesFeature, ValueTask vt)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.FireOnCompletedAwaited(Task currentTask, Stack`1 onCompleted)

I am sure that I set up a connection to my db correctly. I verified that in the following way: I have another piece of code:
public async Task<List<GetVideoDto>> GetAll()
{
    var videoModels = await context
        .Videos
        .ToListAsync();
    return mapper.Map<List<GetVideoDto>>(videoModels);
}

And this piece of code works just fine. I manually inserted a value in my database and checked that it is returned by the await context.Videos.ToListAsync(); by debugging and by Postman.  Also I can apply migrations to a database successfully.
So, the error seems to tell me that my piece of code tries to open a connection before closing it. But I can not understand how this could be possible.
I am very well aware of the state machine behind the async/await, so the context.SaveChangesAsync(); in my case will definitely run only after the context.Videos.AddAsync(videoModel); has completed.
UPDATE
I was able to better pin down the issue. The error is thrown due to this line:
await context.SaveChangesAsync();

So, I am not getting an error if I use the SaveChanges instead of the SaveChangesAsync. Does that mean that if I want to preserve the performance benefit of the SaveChangesAsync I should make the context to be not a singleton (as it is by default), but scoped?
Here is how I am adding the context right now:
services.AddDbContext<DataContext>(opt => opt.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));

I mean here is my entire Startup.ConfigureServices:
public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<DataContext>(opt =>
            opt.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"))
        );

        services.AddCors();

        services.AddControllers();

        services.AddAutoMapper(typeof(Startup));

        services.AddScoped<IVideoService, VideoService>();
    }

And by the performance benefit of the SaveChangesAsync I mean that my thread won`t be idle waiting for the SaveChanges to complete, but will go back to the CLR thread pool.
I am strongly feeling that there should be a DDD principle which targets specifically the case of a correct SaveChangesAsync usage. But I can not find it (probably there is no one).

A: Add entities using plain old Add() rather than trying to add them async. Its not a long running operation just adding to an in memory collection so there is no benefit to trying to make the Add operation async.
When you are adding to your DbSet you are doing just that, it's the actual saving that benefits from being Async, as that's what you can await.
If you read the docs on AddAsync you will also see you should the following:-

This method is async only to allow special value generators, such as
the one used by
'Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo',
to access the database asynchronously. For all other cases the non
async method should be used

.
I typically do this, and await the call to save in my controllers or whatever.
        public void AddThing(Thing thingToAdd)
        {
            _context.Things.Add(thingToAdd);
        }

        public async Task<bool> SaveChangesAsync()
        {
            return (await _context.SaveChangesAsync() > 0);
        }


text:
Q: what is lift in these terms? I am unable to comprehend this  "Each vector $w(t)$ lifts to the vector $q(t)$"
is it trying to say that the smooth curve $y(t)$ in $\Bbb R^d $ and there is a tangent  $w(t)$ in $\Bbb R^d $   at $y(t)$ , then this vector lifts to the vector $q(t)$ in $\Sigma $ . am i correct or it means something different .
where $I$ is the identity matrix,$J$ is the jacobian,$\Sigma $ is an imbedding in $\Bbb R^d$ .
$\Sigma= \{y/F(y) :y \in \Bbb{R^d}\}$
A curve $y(t)$ in $\Bbb{R^d}$ lifts to a curve $x(t)=(y/F(y) )$ in $\Sigma $
and the tangent vector $v(t)=\dot {y}(t)$ in $\Bbb{R^d}$ lifts to the tangent vector $$u(t)=(I,J(y(t))^Tv(t)$$ to $\Sigma $ at $x(t)$
$J=\frac{\partial F()}{\partial y}$


text:
Q: Conditional outcome What am I doing wrong? Im trying to get a green text if conditions are met, or normal text when not.
This is my code:
if($result)
{
    echo ("

Totaal:

") ;

        if($formatted_one <= $formatted_two || $formatted_one <= $formatted_three || $formatted_one <= $formatted_four )
        {
        echo (" Opties Brons
 ") ;
        echo "Pakket Brons: &#8364 " . ($formatted_one) . "
" ;
        echo "Pakket Brons: &#8364 " . ($formatted_one_one) . " (inclusief all-in pakket)
" ;
        echo "Het verschil is: &#8364 " . ($formatted_one_two) . "
" ;
        echo ("
") ;
        }
        else
        {
        echo ("Opties Brons
 ") ;
        echo "Pakket Brons: &#8364 " . ($formatted_one) . "
" ;
        echo "Pakket Brons: &#8364 " . ($formatted_one_one) . " (inclusief all-in pakket)
" ;
        echo "Het verschil is: &#8364 " . ($formatted_one_two) . "
" ;
        echo ("
") ;
}
else
{
    echo("
U heeft niet alles goed ingevuld");
}

Thanks for the help!

A: your
} else {
    echo ("Opties Brons
 ") ;

never close...
so you actualy have
if() {
   ...
} else {
   ...
} else {
   ...
}

this wrong, add the missing }


text:
Q: How to use SQL Server data locks on SQL 2008 I would like some help with SQL Server locks, as I am having difficulty understanding how they work. The job is simple. I may have two orders coming in at the same time, or a split second difference, that try to allocate a certain amount of inventory on hand. The query takes already created order detail record and updates it with qty ordered in sufficient inventory is available. What I would like to be able to do  if the second order comes in with the same product request, it shouldn't over allocate, basically it should check IOH minus already allocated orders. So I'd like to prevent second order stepping on the first one and double allocating.
I've tried creating a two simple transactions running one with delay to see if the other one waits for the commit of the first. The second one timed out.
-- QOH IS ASSUMED TO BE 100
-- THIS IS THE 'SLOW' PROCESS

-- VARIABLES
DECLARE @QtyAvailable INT;
DECLARE @ID INT;
DECLARE @OrderQty INT;
DECLARE @ProcessID INT;
Declare @ProdID nchar(10);

SET @OrderQty = 20;
SET @ProcessID = 1;

-- LOCK HEADER RECORD AND CHECK ALLOCATION
begin transaction;
update alldetail set [exists]=0 where orderid=1;
select @QTYAVAILABLE = (select qty from locdet where locid='loc1' and prodid='prod1') - (select           isnull(sum(qtyall),0) from alldetail where locid='loc1' and prodid='prod1')

IF @QtyAvailable >= @OrderQty
BEGIN
    WAITFOR DELAY '00:00:10'
    PRINT 'Allocation passes, QTY Available before order = ' + CAST(@QTYAVAILABLE AS VARCHAR(20))
    PRINT 'Order QTY = ' + cast(@orderqty as varchar(20))
    update alldetail set [exists] = 1, qtyall=@OrderQty where orderid=1 and prodid='prod1' and locid='loc1';
END
ELSE
BEGIN
    PRINT 'Allocation FAILS, QTY Available = ' + CAST(@QTYAVAILABLE AS VARCHAR(20))
    update alldetail set [exists]=0, qtyall=0 where orderid=1 and locid='loc1' and prodid='prod1'       END
select @QTYAVAILABLE = (select qty from locdet where locid='loc1' and prodid='prod1') - (select   isnull(sum(qtyall),0) from alldetail where locid='loc1' and prodid='prod1');
PRINT 'QTY Available after order = ' + CAST(@QTYAVAILABLE AS VARCHAR(20)) + ' Time: ' +    cast(convert(time,GETDATE()) as char(50))
COMMIT transaction;

The second one is similar, but wihout timedelay, qty=15 and orderid=2

A: Two thing fixed the issue. Correct datatable design with an index on the primary key. Another one was using with(rowlock) on the initial update statement.


text:
Q: Simplify parsed regex I have to simplify custom regex expressions parsed to a certain data type. With "simplify" I mean the following (emphasis mine):

Given the rules:

*

*lowercase letters match themselves, eg.:
a matches a and nothing else

*parens enclosing only letters match their full sequence, eg.:
(abc) matches abc and nothing else

*square brackets enclosing only letters match every letters inside, eg.:
[abc] matches a and b and c and nothing else

The following are all valid:

*

*(a[bc]) matches ab and ac and nothing else

*[a(bc)] matches a and bc and nothing else

*(a(bc)) is the same as (abc) and matches abc and nothing else

*[a[bc]] is the same as [abc] and matches a and b and c and nothing else

Regexes can be simplified. For example [a[[bb]b[[b]]](c)(d)] is
really just the same as [abcd] which matches a, b, c and d.

I have implemented a simple parser combinator in Haskell using attoparsec and the following destination data type:
data Regex
  = Symbol Char
  | Concat [Regex] -- ()
  | Union [Regex] -- []
  deriving (Eq)

However, I'm really struggling with the simplification part. I try to reduce the Concats and Unions by a combination of unwrapping them, nubbing and concatMapping to no avail. I think that the data type I have defined might not be the best fit but I have run out of ideas (late at night here). Could you help me look to the right direction? Thanks!
simplify :: Regex -> Regex
simplify (Symbol s) = Symbol s
simplify (Concat [Symbol c]) = Symbol c
simplify (Concat rs) = Concat $ simplify <$> rs
simplify (Union [Symbol c]) = Symbol c
simplify (Union rs) = Union $ nub $ simplify <$> rs

A: You are missing a couple simple improvements, for starters. simplify (Concat [x]) = x and likewise for Union: there's no need for the wrapped regex to be specifically a symbol.
Then you need to start looking at Concats containing other Concats, and likewise for Union. Sure, you start by simplifying the elements of the wrapped list, but before jamming the result back into a wrapper, you lift up any elements using the same wrapper. Something like:
simplify (Concat xs) =
  case concatMap liftConcats (map simplify xs) of
    [x] -> x
    xs -> Concat xs
  where liftConcats :: Regex -> [Regex]
        liftConcats r = _exerciseForTheReader

Then you can do something similar for Union, with a nub thrown in as well.


text:
Q: Twitter profile image is tiny with Auth0 Universal login Im using Auth0's universal login with Facebook and Twitter. By default both of the social networks return tiny version of the user's profile image.
With Facebook you can set a rule in Auth0 which returns the larger one, however I cant any way to do the same with Twitter (default is 48px).

A: I don't know if this is best practice or not but if you replace the string "A_normal" with "A_400x400" then you get an image 400px square:
picture.replace('A_normal', 'A_400x400');


text:
Q: Any way to differentiate between those two functions? So far, I've seen functions, in numpy for example, where you just apply the function to a certain object/variable. And the result is automatically assigned to that object without you asking for it.
Example: np.random.shuffle(a). The answer will be stored in a even if you don't ask for that. How can you tell if a certain function does this in-place action or does it act like a normal function do.
Thanks.


text:
Q: Calculate $\int\int{\sqrt{1-x^2-y^2}}dxdy$ the domain is $x^2+y^2 \le x$ The question:
Calculate $\int\int{\sqrt{1-x^2-y^2}}dxdy$
the domain is $x^2+y^2 \le x$
my solution:

the correct answer offered by my teacher :

I can't figure out why I am wrong.
I wonder which step I make mistakes ...

A: Note that $\int_0^{\cos(\theta)}\sqrt{1-r^2}r dr=\frac13-\frac13(\sin^2x)^{\frac32}$ and not $\frac13-\frac13\sin^3x$.

A: In the first step of your teacher's solution splitting the integral from $\frac{-\pi}{2} - \frac{\pi}{2}$ to $0 - \frac{\pi}{2}$ and at the same time dr becomes $dr^2$, the 2 that is generated from the first transformation cancels out with division of two from the later transformation of the derivative. Yours and the teacher's setting up of the integral are the same. The initial integrand is even  and your teacher has split the limits and added 2. Due to symmetry, you can change the limits to 0 to $\frac{\pi}{2}$ and multiply by 2  or split the integral itself one with the limit $(\frac{-\pi}{2}) - 0$ and the other $0 - (\frac{\pi}{2})$


text:
Q: Panda Dataframe: Check if row satisfies multiple column filters Is there any way to check if certain rows in the dataframe satisfy multiple filters? I would like to find rows that satisfy filters and add extra values if they pass the filters.
For example,
a b c d e f
2000-01-01 1 1 2
2000-01-02 0 0 0
2000-01-03 1 -2 -1
2000-01-04 5 -5 -2
2000-01-05 0 -5 0
2000-01-06 0 0 0
2000-01-07 5 -2 6
2000-01-08 0 0 0

Consider the dataframe with columns a, b, c, d, e, f (d,e,f are empty). How can I do something like:
if (df['a'] == 0 AND df['b'] == 0 AND df['c'] == 0):
  df['d'] = 0
  df['e'] = 0
  df['f'] = 0

So row 2, 6, and 8 should have 0s in columns d, e, f, and the rest of the rows should have empty values in those columns
Thanks!

A: You can use vectorized and & to create a logical vector for indexing and assignment:
df.loc[(df.a == 0) & (df.b == 0) & (df.c == 0), list('def')] = 0

Update: if the values for d,e,f are different, you can do something like:
df.loc[(df.a == 0) & (df.b == 0) & (df.c == 0), list('def')] = 1,2,3


text:
Q: Element added to ObservableCollection in ViewModel not displayed Quite a newbie in the world of WPF. I've been hurting my eyes for several days now, looking for a solution, but didn't manage to make it right.
What I'm trying to achieve :

*

*Create an ObservableCollection in a view model class

*Bind the data inside the .xaml file

*Create a "Add" button from private void Button_Click in the MainWindow.xaml.cs (I'll create commands later - I just need to take it step by step and keep it simple to understand the process.)
Seems quite simple, uh ? I manage to do it all in the MainWindow.xaml.cs (only using ObservableCollection, no 'PropertyChanged' yet), but I can't make it work in the ViewModel.
Now my code :

Client.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataBindingTestInViewModel
{
    class Client
    {
        protected string _firstName;
        protected string _name;

        public string FirstName
        {
            get { return _firstName; }
            set { _firstName = value; }
        }

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
    }
}

MainWindow.xaml
<Window x:Class="DataBindingTestInViewModel.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DataBindingTestInViewModel"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <Window.DataContext>
        <local:ViewModel />
    </Window.DataContext>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <ItemsControl Grid.Row="0" ItemsSource="{Binding Clients}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Label Grid.Column="0" Content="{Binding FirstName}" />
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

        <Button Grid.Row="1" Click="Button_Click">Add a client</Button>
    </Grid>
</Window>

MainWindow.xaml.cs (create an instance of ViewModel + Button_Click event)
using System.Windows;

namespace DataBindingTestInViewModel
{
    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        ViewModel viewmodel = new ViewModel();

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            viewmodel.AddClient();
        }
    }
}

ViewModel.cs
using System.Collections.ObjectModel;
using System.Windows;

namespace DataBindingTestInViewModel
{
    class ViewModel
    {
        private ObservableCollection<Client> _clients = new ObservableCollection<Client>();

        public ViewModel()
        {
            _clients.Add(new Client() { FirstName = "John", Name = "Doe" });
            _clients.Add(new Client() { FirstName = "Jane", Name = "Doe" });
            //MessageBox.Show("Constructeur du View Model appelé.");
        }
        public ObservableCollection<Client> Clients
        {
            get { return _clients; }
        }

        public void AddClient()
        {
            _clients.Add( new Client() { FirstName = "Donald", Name = "Trump" } );
            MessageBox.Show("First element : " + _clients[0].FirstName + "\n" +
                            "Third element : " + _clients[2].FirstName );

        }
    }
}

Results :

*

*The "John Doe/Jane Doe" are displayed

*When I click the button it doesn't add the thing in the UI. (But the Messagebox works fine.)

What I think happens :
The MainWindow data context is binded to the ViewModel's Client instance. I create and add element in a new instance called in MainWindow - and that's not the one used in the datacontext.
Questions :

*

*Am I right ? If so, how to solve it (call the Viewmodel's instance's AddClient method in the MainWindow) ?

*Any other better (but simple, please !) methods ?

I guess that'll be a piece of cake for y'all. Thank you !!

A: you are correct about working with 2 instances (one created in xaml and another in code-behind). there 2 ways to fix the situation.
work with the instance created in xaml. to get reference to that instance cast DataContext to vm type:
public partial class MainWindow : Window
{
    ViewModel viewmodel;

    public MainWindow()
    {
        InitializeComponent();
        viewModel = (ViewModel)DataContext;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        viewmodel.AddClient();
    }
}

work with the instance created in code. set DataContext from code too:
public partial class MainWindow : Window
{
    ViewModel viewmodel = new ViewModel();

    public MainWindow()
    {
        InitializeComponent();
        DataContext = viewmodel;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        viewmodel.AddClient();
    }
}

and remove xaml part:
<Window.DataContext>
    <local:ViewModel />
</Window.DataContext>


text:
Q: is there a good way to combine stream manipulators? If I wanted to output a fixed width hex number with 4 digits on a stream, I would need to do something like this:
cout << "0x" << hex << setw(4) << setfill('0') << 0xABC;

which seems a bit long winded.  Using a macro helps:
#define HEX(n) "0x" << hex << setw(n) << setfill('0')

cout << HEX(4) << 0xABC;

Is there a better way to combine the manipulators?

A: Why a macro - can't you use a function instead?
void write4dhex(ostream& strm, int n)
{
    strm << "0x" << hex << setw(4) << setfill('0') << n;
}

A: Avoid the macros when you can! They hide code, making things hard to debug, don't respect scope, etc.
You can use a simple function as KenE provided. If you want to get all fancy and flexible, then you can write your own manipulator:
#include <iostream>
#include <iomanip>
using namespace std;

ostream& hex4(ostream& out)
{
    return out << "0x" << hex << setw(4) << setfill('0');
}

int main()
{
    cout << hex4 << 123 << endl;
}

This makes it a little more general. The reason the function above can be used is because operator<< is already overloaded like this: ostream& operator<<(ostream&, ostream& (*funtion_ptr)(ostream&)). endl and some other manipulators are also implemented like this.
If you want to allow the number of digits to be specified at runtime, we can use a class:
#include <iostream>
#include <iomanip>
using namespace std;

struct formatted_hex
{
    unsigned int n;
    explicit formatted_hex(unsigned int in): n(in) {}
};

ostream& operator<<(ostream& out, const formatted_hex& fh)
{
    return out << "0x" << hex << setw(fh.n) << setfill('0');
}

int main()
{
    cout << formatted_hex(4) << 123 << endl;
}

If the size can be determined at compile-time, however, might as well just use a function template [thanks to Jon Purdy for this suggestion]:
template <unsigned int N>
ostream& formatted_hex(ostream& out)
{
    return out << "0x" << hex << setw(N) << setfill('0');
}

int main()
{
    cout << formatted_hex<4> << 123 << endl;
}

A: In C++20 you'll be able to use std::format to make this much less verbose:
std::cout << std::format("0x{:04x}", 0xABC);

Output:
0x0abc

You can also easily reuse the format string by storing it in a constant.
In the meantime you can use the {fmt} library, std::format is based on. {fmt} also provides the print function that makes this even easier and more efficient (godbolt):
fmt::print("0x{:04x}", 0xABC);

Disclaimer: I'm the author of {fmt} and C++20 std::format.


text:
Q: Adding an etag/version to assets with brunch To compile my static web project I use Brunch. In order to serve it via a CDN without invalidating upon deploy I'd like to add an etag to my assets, e.g. my-app-12345.css instead of my-app.css.
Adding the etag to the file isn't the problem, but wiring it up in the index.html is a bit harder.
Is there a module that does this already? Or how could I achieve this otherwise?

A: I found digest-brunch, does exactly what I need!


text:
Q: Play QuickTime Video in WPF Is it possible to play a QuickTime Video in WPF? If yes, can anyone provide me the resources.

A: Quicktime is a tricky thing on Windows.  The APIs pretty much don't exist for any language except C++.  Here's some documentation from the Apple developer website; Quicktime Development For Windows.  But I doubt this will be useful for your WPF development.
Another option is to use the Quicktime ActiveX control/COM object.  Its essentially a built in player with minimal control.


text:
Q: Python refuses to import a module There are three modules in question, in two packages:
Tools
   BasicLogger.py
   CascadingDataSet.py

Sandbox
   test.py

BasicLogger.py contains a class ('BasicLogger'), with no parents other than 'object'.
CascadingDataSet.py contains a class ('CascadingDataSet'), which is a child of BasicLogger, above.
test.py imports CascadingDataSet as follows:
import Tools.CascadingDataSet.CascadingDataSet as CascadingDataSet

(As a side note, I'm convinced I'm doing that wrong, but not only does it usually work, I can't seem to find a way to do that without repetition somewhere. Also, it appears to be working here.)
CascadingDataSet.py imports BasicLogger as follows:
import Tools.BasicLogger.BasicLogger as BasicLogger

This where it fails, and this is the error that I get.
Traceback (most recent call last):
  File "D:\code\python\Engine\SandBox\test.py", line 7, in <module>
    import Tools.CascadingDataSet.CascadingDataSet as CascadingDataSheet
  File "D:\code\python\Engine\Tools\CascadingDataSet.py", line 7, in <module>
    import Tools.BasicLogger.BasicLogger as BasicLogger
ModuleNotFoundError: No module named 'Tools.BasicLogger.BasicLogger'; 'Tools.BasicLogger' is not a package

I have tried:

*

*renaming the class and filename for BasicLogger.  No success.

*renaming the package itself.  No success.

*moving BasicLogger.py to a different package.  No success.

*instantiating an object of the BasicLogger class inside BasicLogger.py.  This was successful, but only confuses me more, because obviously the code itself is fine.

*creating an entirely new file, with a different name, copying the contents of BasicLogger.py into it, and trying to import that.

*importing BasicLogger directly into test.py.  Nope.

*closing and reopening the IDE.  Had to try.

My IDE (pyDev for eclipse) completely recognizes the file as an appropriate import; I even erased the import line and redid it letting pyDev autocomplete each part.  As I mentioned, the code copies fine-- but its obviously something in the code.  Either that, or I fundamentally do not understand imports at all, but I've been playing with python for like, a year, and this has never come up.

A: I have got it working.  In two ways:
Two solutions:
This one was posted by deceze in the comments.
from Tools.BasicLogger import BasicLogger

This is doubly helpful because it not only solves this problem, but avoids the ridiculous threepeat, and is considerably more compact and elegant than:
import Tools.Logging as Logging

class CascadingDataSet(Logging.BasicLogger):

I'm still baffled about why it worked for CascadingDataSet but not BasicLogger, but I'm just going to let that go.

A: I think you will need another file outside of those two packages and also create an __init__.py file inside of those two packages.
main.py

Tools
   BasicLogger.py
   CascadingDataSet.py

Sandbox
   test.py

Then from test.py you could import it like what you write. But you couldn't run test.py file directly from Sandbox package because it can't find Tools packages. That's why you need runner.py to import and run the process from test.py.


text:
Q: How to add a number at the right of a matrix plot and an additional colored 1 line array below or above From this precedent question Drawing a large binary matrix as colored grid in TikZ I have the following matrix plot:
\documentclass{article}
\usepackage{filecontents}
\usepackage[table]{xcolor}
\usepackage{pgfplotstable}
\usetikzlibrary{calc}
\pgfplotsset{compat=1.8}

\begin{filecontents}{matrix.cvs}
0 1 1 0 1 1 0 1 0 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 1 1 0 1 1 1 1 0 0 0 1 0 1 1 0 0 1 0 1 0 1 0 0 0 1 1
0 0 1 1 0 1 0 0 0 1 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 1 0
0 1 0 1 0 0 0 0 0 1 1 0 1 0 0 1 0 1 0 0 1 0 0 1 0 0 0 0 0 0 1 0 0 1 1 1 0 0 1 0 0 0 1 0 1 1 0 1 1 0
0 0 1 0 0 0 1 1 0 1 0 1 1 0 0 0 1 1 0 0 1 1 0 0 1 0 1 1 0 0 0 0 0 1 1 0 1 0 1 0 0 0 1 0 0 0 0 1 1 0
1 0 1 1 0 0 1 1 0 1 0 1 0 0 1 0 0 1 1 0 0 0 1 0 0 0 0 0 1 0 1 1 1 1 0 0 0 0 0 0 1 0 0 0 1 1 1 0 0 0
0 0 0 1 0 0 0 1 0 1 0 0 0 1 0 0 1 0 0 0 0 0 1 0 1 1 1 0 1 0 0 1 0 1 0 1 0 0 0 0 1 0 0 0 0 1 0 1 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
1 0 1 0 0 0 1 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 0 1 1 1 1 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1
\end{filecontents}

\makeatletter
\tikzset{
    zero color/.initial=white,
    zero color/.get=\zerocol,
    zero color/.store in=\zerocol,
    one color/.initial=red,
    one color/.get=\onecol,
    one color/.store in=\onecol,
    cell wd/.initial=1ex,
    cell wd/.get=\cellwd,
    cell wd/.store in=\cellwd,
    cell ht/.initial=1ex,
    cell ht/.get=\cellht,
    cell ht/.store in=\cellht,
}

\newcommand{\drawgrid}[2][]{
\medskip
\begin{tikzpicture}[#1]
  \pgfplotstableforeachcolumn#2\as\col{
    \pgfplotstableforeachcolumnelement{\col}\of#2\as\colcnt{%
      \ifnum\colcnt=0
        \fill[\zerocol]($ -\pgfplotstablerow*(0,\cellht) + \col*(\cellwd,0) $) rectangle+(\cellwd,\cellht);
      \fi
      \ifnum\colcnt=1
        \fill[\onecol]($ -\pgfplotstablerow*(0,\cellht) + \col*(\cellwd,0) $) rectangle+(\cellwd,\cellht);
      \fi
    }
  }
\end{tikzpicture}
\medskip
}
\makeatother

\begin{document}
% read the file
\pgfplotstableread{matrix.cvs}{\matrixfile}

\begin{figure}[!t]
    \centering
        \drawgrid[zero color=orange,
          one color=violet,
          cell ht=0.75em,
          cell wd=0.75em]{\matrixfile}
    \caption{caption}
    \label{fig:label}
\end{figure}

\end{document}

which plots a 50 columns matrix:

I would like to add a number to each row of the matrix
0.0293
0.0211
0.0165
0.0163
0.0134
0.0382
0.0150
0.8501

and (aligned) add a matrix plot of one row at the bottom with white (0) to black (1) indicating these weights.
0.2833
0.0336
0.7766
0.0468
0.0228
0.0143
0.6877
0.0700
0.1287
0.6659
0.7123
0.0143
0.0143
0.6325
0.8049
0.7282
0.1624
0.6346
0.0564
0.0176
0.0143
0.0271
0.6463
0.7268
0.4798
0.1637
0.0297
0.3054
0.5039
0.0246
0.7140
0.3091
0.4256
0.3418
0.6493
0.0508
0.0143
0.2927
0.0291
0.6622
0.0143
0.0177
0.1610
0.1287
0.7471
0.0563
0.0143
0.3275
0.6773
0.5992

to get something like this:

(I have not completed the 1-row matrix of greys)
To distinguish better the rows and columns it would be a feature of the plot to control the white separation lines of the matrices.

A: \documentclass{article}
\usepackage{filecontents}
\usepackage[table]{xcolor}
\usepackage{pgfplotstable}
\usetikzlibrary{calc}
\pgfplotsset{compat=1.16}

\begin{filecontents}{matrix.cvs}
0 1 1 0 1 1 0 1 0 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 1 1 0 1 1 1 1 0 0 0 1 0 1 1 0 0 1 0 1 0 1 0 0 0 1 1
0 0 1 1 0 1 0 0 0 1 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 1 0
0 1 0 1 0 0 0 0 0 1 1 0 1 0 0 1 0 1 0 0 1 0 0 1 0 0 0 0 0 0 1 0 0 1 1 1 0 0 1 0 0 0 1 0 1 1 0 1 1 0
0 0 1 0 0 0 1 1 0 1 0 1 1 0 0 0 1 1 0 0 1 1 0 0 1 0 1 1 0 0 0 0 0 1 1 0 1 0 1 0 0 0 1 0 0 0 0 1 1 0
1 0 1 1 0 0 1 1 0 1 0 1 0 0 1 0 0 1 1 0 0 0 1 0 0 0 0 0 1 0 1 1 1 1 0 0 0 0 0 0 1 0 0 0 1 1 1 0 0 0
0 0 0 1 0 0 0 1 0 1 0 0 0 1 0 0 1 0 0 0 0 0 1 0 1 1 1 0 1 0 0 1 0 1 0 1 0 0 0 0 1 0 0 0 0 1 0 1 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
1 0 1 0 0 0 1 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 0 1 1 1 1 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1
\end{filecontents}

\makeatletter
\tikzset{
    zero color/.initial=white,
    zero color/.get=\zerocol,
    zero color/.store in=\zerocol,
    one color/.initial=red,
    one color/.get=\onecol,
    one color/.store in=\onecol,
    cell wd/.initial=1ex,
    cell wd/.get=\cellwd,
    cell wd/.store in=\cellwd,
    cell ht/.initial=1ex,
    cell ht/.get=\cellht,
    cell ht/.store in=\cellht,
    xlabels/.store in=\myxlabels,
    ylabels/.store in=\myylabels,
}
\newcommand{\drawgrid}[2][]{
\medskip
\begin{tikzpicture}[#1]
  \pgfplotstableforeachcolumn#2\as\col{
    \pgfplotstableforeachcolumnelement{\col}\of#2\as\colcnt{%
      \ifnum\colcnt=0
        \fill[\zerocol]($ (0,-\pgfplotstablerow*\cellht) + (\col*\cellwd,0) $) rectangle+(\cellwd,\cellht);
      \fi
      \ifnum\colcnt=1
        \fill[\onecol]($ (0,-\pgfplotstablerow*\cellht) + (\col*\cellwd,0) $) rectangle+(\cellwd,\cellht);
      \fi
    }
  }
  \pgfplotstablegetrowsof{#2}
  \pgfmathtruncatemacro{\numrows}{\pgfplotsretval}
  \pgfplotstablegetcolsof{#2}
  \pgfmathtruncatemacro{\numcols}{\pgfplotsretval}
  \draw[white] (0,\cellht) grid[xstep=\cellwd,ystep=\cellht]
     (\cellwd*\numcols,\cellht-\cellht*\numrows); %
  \foreach \Z [count=\Y] in \myylabels
   {\node[anchor=west,font=\sffamily,scale=0.7] at
    (\cellwd*\numcols,1.5*\cellht-\cellht*\Y) {\Z};}
  \foreach \Z [count=\X,evaluate=\Z as \CC using {int(\Z*100)}] in \myxlabels
   {\fill[black!\CC]
   (-\cellwd+\X*\cellwd,0.5*\cellht-\cellht*\numrows)
    rectangle ++ (\cellwd,-\cellht);
    \node[anchor=west,rotate=-90,font=\sffamily,scale=0.7] at
    (-0.5*\cellwd+\X*\cellwd,-0.5*\cellht-\cellht*\numrows) {\Z};
    }
\end{tikzpicture}
\medskip
}
\makeatother

\begin{document}
% read the file
\pgfplotstableread{matrix.cvs}{\matrixfile}

\begin{figure}[!t]
    \centering
        \drawgrid[zero color=orange,
          one color=violet,
          cell ht=0.75em,
          cell wd=0.75em,
          xlabels={0.2833,0.0336,0.7766,0.0468,0.0228,0.0143,0.6877,0.0700,0.1287,0.6659,0.7123,0.0143,0.0143,0.6325,0.8049,0.7282,0.1624,0.6346,0.0564,0.0176,0.0143,0.0271,0.6463,0.7268,0.4798,0.1637,0.0297,0.3054,0.5039,0.0246,0.7140,0.3091,0.4256,0.3418,0.6493,0.0508,0.0143,0.2927,0.0291,0.6622,0.0143,0.0177,0.1610,0.1287,0.7471,0.0563,0.0143,0.3275,0.6773,0.5992},
          ylabels={0.0293,0.0211,0.0165,0.0163,0.0134,0.0382,0.0150,0.8501}]{\matrixfile}
    \caption{caption}
    \label{fig:label}
\end{figure}

\end{document}

Please note that the figure is a bit too wide for the given page parameters, meaning that you may want to make the page wider, the figure smaller or to rotate the figure.


text:
Q: Need formula to count the number of true values for an aggregated attribute based on a larger dataset I've created an example spreadsheet here. The dataset I'm using is significantly larger, approx 2,000 rows.
The larger dataset has hundreds of rows per Market and dozens of rows per Partner along with TRUE/FALSE values for two parameters (Called & Registered).
What I want to do is create a smaller table that will track both Called and Registered progress on the market level. I'm fine with this simply being a COUNT function (although ultimately I'd like to turn that into a percent (TRUE / FALSE= %).
Because the real dataset is so large, I can't use a simple COUNTIF function - and I also need the formula to be replicable for similar datasets. I tried using a FILTER function: =COUNTIF(FILTER(B10:E,B10:B=B3),D10:D=TRUE) - to match the Market value but that hasn't worked.
I've included markdown text along with a screenshot below. Greatly appreciate the help!

Market
Called Progress
Registered Progress

New York

California

Texas

Florida

Market
Partner
Called
Registered

New York
John
FALSE
FALSE

New York
Mary
FALSE
FALSE

New York
Henry
FALSE
FALSE

California
Laura
FALSE
FALSE

California
Kevin
FALSE
FALSE

California
James
FALSE
FALSE

Texas
Michael
FALSE
FALSE

Texas
Sandra
FALSE
FALSE

Texas
Sarah
FALSE
FALSE

Florida
Jennifer
FALSE
FALSE

Florida
Harry
FALSE
FALSE

Florida
David
FALSE
FALSE

A: One way is to use query(), like this:
=arrayformula( query(
  if( islogical(B9:E), B9:E + 0, B9:E ),
  "select
     Col1,
     sum(Col3) / count(Col3),
     sum(Col4) / count(Col4)
   where Col1 is not null
   group by Col1
   label
     sum(Col3) / count(Col3) 'Called Progress',
     sum(Col4) / count(Col4) 'Registered Progress'
   format
     sum(Col3) / count(Col3) '0%',
     sum(Col4) / count(Col4) '0%' ",
  1
) )

This gives a table like this:

Market
Called Progress
Registered Progress

California
100%
67%

Florida
67%
33%

New York
33%
33%

Texas
33%
0%

A: use:
=BYROW(B3:B6, LAMBDA(x, SUMPRODUCT(B9:B=x, D9:D)))

and:
=BYROW(B3:B6, LAMBDA(x, SUMPRODUCT(B9:B=x, E9:E)))


text:
Q: Is it not possible to store BigDecimal values in a single-dimensional array My goal is store BigDecimal values as I input them through the Scanner class. I want to store BigDecimal numbers into an array so that I can sort them numerically. Can this be done using a single-dimensional array?
I can't find any BigInteger methods designed for this task. I want BigDecimal values because the decimal precision is important to me.

A: If you want to sort them easily, you could do the following:
    BigDecimal x1 = new BigDecimal("1235.2345");
    BigDecimal x2 = new BigDecimal("235.2345");
    BigDecimal[] nums = {x1,x2};
    List<BigDecimal> lnums = Arrays.asList(nums);
    Collections.sort(lnums);

Arrays.asList() merely passes the value of the reference of your array.  Collections.sort() uses merge sort.

A: I hope this help you,
BigDecimal x = new BigDecimal(5.94839);
BigDecimal y = new BigDecimal(9.03937);
BigDecimal[] myBDArr = {x,y};
System.out.println(myBDArr[0]);
System.out.println(myBDArr[1]);

Output:
5.948389999999999844249032321386039257049560546875
9.0393699999999999050714905024506151676177978515625


text:
Q: How to create a canvas element inside an iframe? I have an iframe in which there is DIV element "pageContainer1". I want to be able to add a canvas element in that DIV element and access it to draw something on it. I have tried this so far but doesn't seem to work.
var can=document.getElementById('frame').contentWindow.document.getElementById("pageContainer1");

var canvas=document.createElement("canvas");
canvas.id="testcanvas";

can.appendChild(canvas);
var can1=document.getElementById("frame").contentWindow.document.getElementById("testcanvas");
var ctx= can1.getContext('2d');

  ctx.beginPath();
  ctx.moveTo(20,20);
  ctx.lineTo(100,100);
  ctx.stroke();

please suggest some way to do it, even if by using jquery.

A: *

*Verify that the iframe is fully loaded and that you are getting a valid element back in variable "can"

*is there a reason why you need to get the canvas a second time when you already have access to it in the variable "canvas"?  try removing that and seeing if it works.

*try inspecting the page and making sure that the canvas has been added
EDITED
see if this helps:
function loaded() {
    var iframe = document.getElementById('thisistheiframe');

    var iframediv = iframe.contentWindow.document;

    iframediv.body.innerHTML += '<canvas id="thecanvas" style="background-color:red; width:100px; height:100px"></canvas>';

    var c = iframediv.getElementById('thecanvas');

    var ctx = c.getContext('2d');
    ctx.moveTo(20, 20);
    ctx.lineTo(100, 100);
    ctx.stroke();
}

http://jsfiddle.net/mW8kv/
EDIT 2
updated fiddle to use createElement instead of just setting html:
var can = iframediv.createElement('canvas')
can.id = 'thecanvas';
iframediv.body.appendChild(can);

var c = iframediv.getElementById('thecanvas');


text:
Q: OpenVPN route troubles i've setup openvpn on my raspbarry pi. This scheme below is my current network:

With the OpenVPN client i can ping the raspbarry (on the 10.8.0.1 interface) but im not able to ping my PC desktop (192.168.1.3).I tried to add this line into the server.conf:

push "route 192.168.1.0 255.255.255.0"

Server.conf:
dev tun
proto udp
port 1194
ca /etc/openvpn/easy-rsa/pki/ca.crt
cert /etc/openvpn/easy-rsa/pki/issued/raspberrypi_73c07827-d429-4cf4-8a0a-408772ae977f.crt
key /etc/openvpn/easy-rsa/pki/private/raspberrypi_73c07827-d429-4cf4-8a0a-408772ae977f.key
dh none
ecdh-curve prime256v1
topology subnet
server 10.8.0.0 255.255.255.0
# Set your primary domain name server address for clients
push "dhcp-option DNS 9.9.9.9"
push "dhcp-option DNS 149.112.112.112"
# Prevent DNS leaks on Windows
push "block-outside-dns"
# Override the Client default gateway by using 0.0.0.0/1 and
# 128.0.0.0/1 rather than 0.0.0.0/0. This has the benefit of
# overriding but not wiping out the original default gateway.
push "redirect-gateway def1"
client-to-client
client-config-dir /etc/openvpn/ccd
keepalive 15 120
remote-cert-tls client
tls-version-min 1.2
tls-crypt /etc/openvpn/easy-rsa/pki/ta.key
cipher AES-256-CBC
auth SHA256
user openvpn
group openvpn
persist-key
persist-tun
crl-verify /etc/openvpn/crl.pem
status /var/log/openvpn-status.log 20
status-version 3
syslog
verb 3

#Added
push "route 192.168.1.0 255.255.255.0"

#DuplicateCNs allow access control on a less-granular, per user basis.
#Remove # if you will manage access by user instead of device.
#duplicate-cn
# Generated for use by PiVPN.io

Client:
client
dev tun
proto udp
remote 188.153.71.125 1194
resolv-retry infinite
nobind
remote-cert-tls server
tls-version-min 1.2
verify-x509-name raspberrypi_73c07827-d429-4cf4-8a0a-408772ae977f name
cipher AES-256-CBC
auth SHA256
auth-nocache
verb 3

but it didnt work...
Any suggestions?

A: The problem that you are having is likely because you don't have masquerade setup on the raspberry pi.  Add an up script that will add an iptables postrouting masquerade, and that should allow the 10.8.0.2 pc to ping 192.168.1.3.
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE

You may have to change eth0 based on the configuration of your interfaces on the raspberry pi.
n.b., you will also have to make sure net.ipv4.ip_forward is set to 1 in sysctl


text:
Q: initramfs shell after upgrade to Ubuntu 22.04 - raid I upgraded from 20.04 to 22.04 and after reboot I get the following screen / errors (see screenshot) and it goes to the initramfs shell. It's a RAID system. It might be that boot partition was too full during upgrade, or that when freeing space pre-upgrade I deleted too much (and wrongly) from the boot folder. In the Grub menu there's two kernels to choose from (generic and low-latency variant) but none of them work, all revert to initramfs shell.
Problem sounds similar to: System boots to initramfs after upgrade from 21.10 to 22.04
"dmsetup ls" shows indeed the block devices (see screenshot) but partprobe is not found. EDIT: I managed to mount the partitions when booting into a Live USB. But still don't know how to make the system boot.
Can someone provide advice please? I'm pretty lost here... what other information do I have to provide to debug this properly?
Thanks in advance