text:
Q: Why does >= work but => not? When checking if a integer is the same or above a current number.. so I type
if (5 => 6) { //Bla }

but it shows this as a error. Why?  Isn't it exactly the same as
if (5 >= 6) { //Bla }

A: Because => is meant for lambda expressions:
Action<object> print = o => Console.WriteLine(o);
print(123);

Besides, you don't say "equal to or greater than", which is what => would have been pronounced as otherwise.

A: The confusion here is that you're assuming >= is two operators smooshed together.  In fact, it's only one operator with two characters, much the same as tons of other operators (+=, *=, -=, etc).

A: Why should it be? =! is not the same as != either. This is a part of the languages syntax.
In this specific case, => is also used for lambda expressions so it has another purpose.

A: Because it is called greater or equal to. Not equal or greater than. Simple uh?

A: The reason why it does not work is because => is not equivalent to >=.
=> is used in a lambda expression. Like :
(int x, string s) => s.Length > x

I do agree it is annoying. Before lambda expressions I used to get it wrong sometimes. Now I always know that one (=>) is a lambda expression and and other (>=) is the greater than equal to sign

A: Because the operator is >= not =>.
The writers of the language could have chosen either syntax, but had to choose one. Having two operators meaning the same thing would be confusing at best.
However, the operator is read "greater than or equal to" so it does make sense that the > symbol is first.
Also => is now used for Lambda expressions.

A: In C# the greater than or less than sign must come BEFORE the equal sign.  It is just part of the syntax of the language.

A: Because => stands for Lambda expressions in c#.
>= stands for greater than or equal to, as you already know.
The syntax is such that you have to use >= while comparing two entities. Also just additionally you can notice that even a space between them will give errors - > =

A: No, it is not this same. Correct operator in c# is >= for comparission and => for lambda expression.

A: @Barry's answer is probably the most insightful of the lot here. A single operator does not mean a single character; the fact that > and = combine to form >= does not mean that it's doing both > and =; it's doing a single operation. The fact that the defined operator for that operation includes the characters for two other similar operations is irrelevent.
I suppose if you really wanted to you could override it so that both >= and => worked the same way -- C# does allow operator overrides. But it would be a bad idea because as others have already said, => is actually in use for other purposes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rename worksheet to cell value keeping format The below code works.  It will rename my worksheet to a cell's value.  But in the case of a new project, the cell's value happens to be a date 8/4/2012 for example.  If i run the below code, the sheet gets renamed to "Sat Aug 04 2012 02:00:00 GMT-0500 (CDT)".
How can i adjust the below code so the sheet's name reflects only "8/4/2012"
  // The code below will rename the active sheet to last production week's date
var myValue = SpreadsheetApp.getActiveSheet( ).getRange("P1").getValue();
SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet(myValue);

A: You should use Utilities.formatDate() to get the format you want.
in your code it should be
SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet(Utilities.formatDate(myValue, "GMT", "MM/dd/yyyy"));

if you're not in GMT don't forget to change that since even if you don't use hours it will mess up your dates sometimes ;-)


text:
Q: Too many connections with PDO persistent connection? I've been struggling with this for quite a while, and it's to the point where I need to ask for help because even with all the research I've done I can't get a handle on why this is happening.

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [1040] Too many connections'

This happens upon loading a single page (index.php), and I am the only user (dev). As you can see here, the MySQL connection limit is set @ 50 but I am narrowly surpassing that. This is an improvement over the 100~ connections that were being created before I refactored the code.

Here are the stats after the page has loaded once.

I've narrowed the issue down to several causes:

*

*I don't fully understand how PDO/MySQL connections work.

*I am creating too many connections in my code even though I am trying to only create one that I can share.

*I need to increase the connection limit (seems unlikely).

Most of the SO questions I've found, tell the OP to increase the connection limit without truly knowing if that's the best solution so I'm trying to avoid that here if it's not needed. 50 connections for one page load seems like way too many.
These are the classes I am instantiating on the page in question.
$DataAccess = new \App\Utility\DataAccess();
$DataCopyController = new App\Controllers\DataCopyController($DataAccess);
$DriveController = new App\Controllers\DriveController($DataAccess);
$Helper = new App\Utility\Helper();
$View = new App\Views\View();

I am creating the DAL object then injecting it into the classes that need it. By doing it this way I was hoping to only create one object and one connection, however this is not what's happening obviously. Inside the DAL class I've also added $this->DbConnect->close() to each and every query method.
Here is the constructor for the DataAccess() class.
public function __construct() {

    $this->DbConnect = new \App\Services\DbConnect();
    $this->db = $this->DbConnect->connect("read");
    $this->dbmod = $this->DbConnect->connect("write");

    $this->Helper = new Helper();
}

Here is the DbConnect() class.
class DbConnect {
  private $db;
  private $dbmod;

  private function isConnected($connection) {
    return ($connection) ? TRUE : FALSE;
  }

  public function connect($access) {

    $options = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false
                ];

    if ($access == "read") {
        if ($this->isConnected($this->db)) {
            return $this->db;
        } else {
            if (strpos($_SERVER['SERVER_NAME'], DBNAME_DEV) === false) {
                $this->db = new PDO("mysql:host=127.0.0.1; dbname=".DBNAME,
                                                                    DBUSER,
                                                                    DBPASS,
                                                                    $options
                                                                       );
            } else {
                $this->db = new PDO("mysql:host=" . DBHOST_DEV ."; dbname=".DBNAME_DEV,
                                                                   DBUSER,
                                                                   DBPASS,
                                                                   $options
                                                                       );
            }
            return $this->db;
        }
    } elseif ($access == "write") {
        if ($this->isConnected($this->dbmod)) {
            return $this->dbmod;
        } else {
            if (strpos($_SERVER['SERVER_NAME'], DBNAME_DEV) === false) {
                $this->dbmod = new PDO("mysql:host=127.0.0.1; dbname=".DBNAME,
                                                                       DBUSER_MOD,
                                                                       DBPASS,
                                                                       $options
                                                                       );
            } else {
                $this->dbmod = new PDO("mysql:host=" . DBHOST_DEV . "; dbname=".DBNAME_DEV,
                                                                       DBUSER_MOD,
                                                                       DBPASS,
                                                                       $options
                                                                       );
            }
        }
        return $this->dbmod;
    }
  }

  public function close() {
    $this->db = null;
    $this->dbmod = null;
  }
}

I've also tried instantiating the DbConnect() class on index.php and injecting that rather than DataAccess() but the result was the same.
EDIT:
I also want to add that this MySQL server has two databases, prod and dev. I suppose the connection limit is shared between both. However, the prod database gets very little traffic and I am not seeing this error there. When I refreshed the stats, there were no connections to the prod database.

A: From the PHP manual ~ http://php.net/manual/en/pdo.connections.php

Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials.

So I would advise removing the DbConnection#close() method as you would not want to ever call this.
Also from the manual...

Note:
  If you wish to use persistent connections, you must set PDO::ATTR_PERSISTENT in the array of driver options passed to the PDO constructor. If setting this attribute with PDO::setAttribute() after instantiation of the object, the driver will not use persistent connections.

So you'll want (at least)
new \PDO("mysql:host=127.0.0.1;dbname=" . DBNAME, DBUSER, DBPASS, [
    PDO::ATTR_PERSISTENT => true
]);

You can also set your other connection attributes in the constructor.


text:
Q: Is it possible to have typescript output in different file extension I have file with the extension .jsv that a actually just javascript files but the application using the file requires them to be with the .jsv extension. The project is a c# library project with these files. I want to try and migrate to typescript. I want to add a file like file1.ts and have typescript generate file1.jsv as I make changes. Is this possible and if yes, how do I achieve this.

A: You can take advantage of the --out flag to achieve this if you are using the TypeScript compiler:
tsc --out app.jsv  app.ts

This results in the output going to app.jsv (but it will also combine your output into a single file where it detects dependencies).
Otherwise you could run a post-build event to rename all your *.js to *.jsv.


text:
Q: Choosing only specific classes of CIFAR-10 I'd like to use CIFAR-10 dataset but I want only the frog,dog,cat,horse and bird classes, I've used the following code so far :
  # Plot ad hoc CIFAR10 instances
  from keras.datasets import cifar10
  from matplotlib import pyplot
  from scipy.misc import toimage
  # load data
  (X_train, y_train), (X_test, y_test) = cifar10.load_data()
  # create a grid of 3x3 images
  for i in range(0, 9):
      pyplot.subplot(330 + 1 + i)
      pyplot.imshow(toimage(X_train[i]))
  # show the plot
  pyplot.show()

the cifar10.load_data() function loads the entire data, can I get only the desired classes?

A: (X_train, y_train), (X_test, y_test) = tf.keras.datasets.cifar10.load_data()

which contains all samples of 10 classes
choose index with respect to classes
index = np.where(y_train == 0)
X_train = X_train[indices]
y_train = y_train[indices]

which gives all 0th indices samples

A:
the cifar10.load_data() function loads the entire data, can I get only the desired classes?

By using load_data() provided by keras.datasets.cifar10 you can't do that. Also, checking other utilities on that source code seems that only the load_data() method is provided.
However, you can do it if you manually get and load the dataset. For this you can try emulating the way keras does it (as well as the previous source code) on the CIFAR10 dataset.
Based on this help page (from where you can also download the dataset) seems that the classes frog, dog, cat, horse, and bird correspond to indexes 6, 5, 3, 7, and 2, respectively. This means you could use those indexes when extracting the data elements, so you can select the ones you need.
Edit: another option that could work better for you is to discard the elements you don't wish from the load_data() call. According to the Keras datasets page, we see that method returns:

*

*2 tuples:

*

*x_train, x_test: uint8 array of RGB image data with shape (num_samples, 3, 32, 32).

*y_train, y_test: uint8 array of category labels (integers in range 0-9) with shape (num_samples,).

Knowing this you can discard any element that does not have the 6,5,3,7,2 tags which correspond to the classes you want.


text:
Q: Access 2013-Need to concatenate field 1 with unique value, with multiple other fields with duplicate values I have the following 4 records, and need the concatenation to read like the second example
Would someone please show me the formula for the query?  Most likely will involve 2 tables.
Field names are OE, Year, Make, Model.  Record 1 = OE - 000 353 13 73, Year - 2005, Make - Chevy, Model – Camaro.  Record 2 = OE - 000 353 13 73, Year - 2006, Make - Chevy, Model – Camaro.  Record 3 = OE - 000 353 13 73, Year - 2006, Make - Buick, Model – Regal.
I want the following results.  Record 1 = 2005, 2006, Chevy, Buick, Camaro, Regal
Thank you.


text:
Q: white screen after exitApp I am developing mobile app with ionic having splash & launch screen.
As of now, I am using below code to do my configurations & initiations and then hiding my splash screen.
angular.element(document).ready(function () {
        // config & initiations
                ionic.Platform.ready( function() {
                if(navigator && navigator.splashscreen){
                    navigator.splashscreen.hide();
                }
        });
    });

Also, I am using double tap exit at first launch page with below snippet.
.factory('backcallFactory', ['$state','$ionicPlatform','$ionicHistory','$timeout',function($state,$ionicPlatform,$ionicHistory,$timeout){
        var obj={}
        obj.backcallfun=function(){
        var backbutton=0;
            $ionicPlatform.registerBackButtonAction(function () {
                if ($state.current.name == "register") {
                     if(backbutton==0){
                        backbutton++;
                        window.plugins.toast.showShortCenter('Press again to exit');
                        $timeout(function(){backbutton=0;},5000);
                    }else{
                        navigator.app.exitApp();
                    }
                }
                else{
                        $ionicHistory.goBack();
                    }
            }, 100);
        }
        return obj;
    }])

So in launch page, if i click back button twice in 5 seconds and it gets closed.
I could see app is still open in open apps list. (first or last button in android phones).
The problem is, if I relaunch the app after double tap to exit , then it is showing white screen for a while and showing launch screen (but no splash screen). I checked in other popular apps having double tap to exit function are showing splash screen again and launch screen without white screen.
How can I achieve the same in my app.

A: I had the same issue. It works fine by downgrading to version 2.0.0 of cordova-plugin-splashscreen.
You can refer to https://issues.apache.org/jira/browse/CB-9374.


text:
Q: Product rule for limits of scalar products How do we prove:
\begin{equation*}
\lim_{t\rightarrow t_{0}}[r_1(t) \cdot r_2(t)]=\lim_{t\rightarrow t_{0}}[r_1(t)] \cdot \lim_{t\rightarrow t_{0}}[r_2(t)]
\end{equation*}
where $r_1(t)$ and $r_2(t)$ are vector functions in $\mathbb{R}^3$ defined in a deleted neighborhood of $t_0,$ assuming they both have limits at $t_0.$

A: The scalar product is a sum of products, namely $r_{1,x}\cdot r_{2,x} + r_{1,y}\cdot r_{2,y}+ r_{1,z}\cdot r_{2,z}$. Now, sums and products can be moved out of the limit as long as the individual limits exist:
$$
\begin{split}
\lim_{t\rightarrow t_0} [r_1(t) \cdot r_2(t)]
&= \lim_{t\rightarrow t_0} [r_{1,x}(t)\cdot r_{2,x}(t) + r_{1,y}(t)\cdot r_{2,y}(t)+ r_{1,z}(t)\cdot r_{2,z}(t)] \\
&= \lim_{t\rightarrow t_0} r_{1,x}(t) \cdot \lim_{t\rightarrow t_0} r_{2,x}(t) + \lim_{t\rightarrow t_0} r_{1,y}(t) \cdot \lim_{t\rightarrow t_0} r_{2,y}(t)
+ \lim_{t\rightarrow t_0} r_{1,z}(t) \cdot \lim_{t\rightarrow t_0} r_{2,z}(t) \\
&= \lim_{t\rightarrow t_0} r_1(t) \cdot  \lim_{t\rightarrow t_0} r_2(t).
\end{split}
$$


text:
Q: bootstrap grid need 10 columns to fill the width I have a bootstrap grid with 2-8-2
In the left hand 2 I have a menu which I want to collapse below 979px
All this is working.
However I would like the remaining 8-2 columns to fill up the width and to position the menu out of the way somewhere.
I suppose i could alter the width of the 8-2 with the media queries - but is there a better way
Any ideas?

A: Use the .hidden classes to hide the menu after the breakpoint?

A: Along with @PeteTNT's answer, you can change the widths of the remaining 8-2 cols, to 10 and 2 after the breakpoint..

left

main

right

Demo: http://bootply.com/Iuq0OH7Jxq


text:
Q: ggplot fitted distributions aren't quite level with the x axis I am trying to model output data from the "mixtools" package in a similar manner to how jhoward did here with minor changes.  The examples provided work as expected and his solution works with my data, however the fitted distributions seem...tilted.

Notice how both distributions are angled above the x axis slightly.
Using an artificial dataset doesn't show the problem anymore.
`sample.ratio`=c(rnorm(120000,0.386,0.0842),rnorm(200000,0.653,0.1153))
`mixmdl_k2.sample`=normalmixEM(`sample.ratio`, k=2)

ggplot_mixEM <- function(EM) {
  require(ggplot2)
  x       <- with(EM,seq(min(x),max(x),len=1000))
  pars    <- with(EM,data.frame(comp=colnames(posterior), mu, sigma,lambda))
  em.df   <- data.frame(x=rep(x,each=nrow(pars)),pars)
  em.df$y <- with(em.df,lambda*dnorm(x,mean=mu,sd=sigma))
  ggplot(data.frame(x=EM$x),aes(x,y=..density..)) +
    geom_histogram(fill=NA,color="black")+
    geom_polygon(data=em.df,aes(x,y,fill=comp),color="grey50", alpha=0.5)+
    scale_fill_discrete("Component\nModes",labels=format(em.df$mu,digits=3))+
    geom_density(color="red",linetype="dotted")
}
ggplot_mixEM(`mixmdl_k2.sample`)

.  The distribution fills are now level, though they are also no longer constrained to the (0,1) interval.
About my data: it ranges explicitly from 0-1, and the bimodal distribution modeled by mixtools is expected.  Increasing the x scale with scale_x_continuous(limits=c(-0.1,1.1)) didn't solve the issue.  The first solution from the link above, provided by Spacedman, also worked on my data, but gave the same "tilted plot" results.
Does anyone know why this is happening and how to fix this tilt? Is there a way to force extend the shading to the x axis?
Thank you.
Edit: added in sample code.

A: Changing the line
x       <- with(EM,seq(min(x),max(x),len=1000))
to
x       <- with(EM,seq(min(x),max(1.1),len=1000))

Seems to have fixed it.


text:
Q: Integrate a Java stand alone application to the Web I develop Java applications with Eclipse that process data. So far I only developed stand alone applications that take data from file or database, process the data, and output the results to the console/file/database.
I would like put my application online. I never did any web development, but from my understanding, the only difference is that my code needs to be on a web server that can get http requests from users, and return http response based on my application's result.
I would like to get advice on the easiest way I can do this. What technology do I need to learn and what tools I can use for making the transition easier. I would also like to separate my code from the code related to the web stuff.
Thanks a lot!

A: The simplest approach to developing Java web applications is via the Servlet specification. This lets you load your application into a Servlet container (such as Jetty or Tomcat), which handles the HTTP-side invocation issue. Your servlet is then a front-end for your front end agnostic processing application.
Since all applications require a user interface, take a look at the myraid of possible templating languages available. Velocity is always a safe pick. This will help you seperate the user interface from the adapter code.

A: While you investigate alternatives, Java Web Start may be the fastest way to get your existing application online. Here's a trivial example.

A: The easiest is most likely to learn how to write a simple servlet, how the HTML looks that you want to generate and then adapt your existing application to run inside the servlet code, and print html instead of just plain text.
This is described in the Servlet part of the Java EE tutorial (which is not great, but a start)
http://java.sun.com/javaee/5/docs/tutorial/doc/bnafe.html
If you want a more accessible book, I can recommend the Head First series.  http://oreilly.com/catalog/9780596005405
For a web container, Apache Tomcat is fine.  http://tomcat.apache.org/


text:
Q: Enviar valores de variables a un servidor externo Hola que tal tengo la siguiente duda, obtengo los datos capturados por metodo POST
$classCode = $_POST["classCode"];
$estimate    = $_POST["estimate"];
$pdateTime    = $_POST["pdateTime"];
$pdateTime2    = $_POST["pdateTime2"];
$pickup_loc    = $_POST["pickup_loc"];
$pickup_time = $_POST["pickup_time"];
$rate_id    = $_POST["rate_id"];
$rdateTime    = $_POST["rdateTime"];
$rdateTime2    = $_POST["rdateTime2"];
$return_loc    = $_POST["return_loc"];
$return_time = $_POST["return_time"];
$tarifabase    = $_POST["tarifabase"];

Como hago para que ya que la variable esta inicializada con el dato capturado, ya sea juntarlo o uno por uno enviar los datos ingresados a un servidor externo.
Dispongo de un VPS donde se estarian recibiendo estos datos para procesarlos

A: Puedes usar la variable $_POST y enviarla al servidor externo mediante una petición HTTP con cURL:
// Inicializa cURL
ch = curl_init();

// Establece la URL
curl_setopt($ch, CURLOPT_URL, 'http://servidor-externo/');

// Establece los campos a enviar
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));

// Ejecuta la petición
$server_output = curl_exec($ch);

// Cierra cURL
curl_close ($ch);

En el servidor remoto te tocará leer las variables almacenadas en $_POST
También puedes establecer los campos uno a uno, de esta manera:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
    'clasCode'  => $classCode,
    'estimate'  => $estimate,
    'pdateTime' => $pdateTime
)));


text:
Q: Spring WS client add SoapHeader I'm trying to send SOAP request with soap header looks like this:
<SOAP-ENV:Header>
<Security xmlns="http://www.xxx.org/xxx/2003/05">
<UsernameToken><Username>yyyy</Username><Password>xxx</Password>
</UsernameToken></Security></SOAP-ENV:Header>

In order to do it I'm adding header element using SoapActionCallback
SoapActionCallback actionCallBack = new SoapActionCallback("https://aaa.com/bbb.asmx") {
            public void doWithMessage(WebServiceMessage msg) {
                SoapMessage smsg = (SoapMessage) msg;
                smsg.setSoapAction("http://www.xxx.org/yyy/2003/05/SessionCreate");
                SoapHeaderElement security = smsg.getSoapHeader().addHeaderElement(new QName("http://www.xxx.org/yyy", "Security"));
                security.setText("<UsernameToken><Username>yyyy</Username><Password>xxx</Password></UsernameToken>");
            }
        };

My problem is that soap header looks like this
<SOAP-ENV:Header><Security xmlns="http://www.xxx.org/yyy/2003/05"><UsernameToken><Username>yyyyy</Username><Password>xxxx</Password></UsernameToken></Security></SOAP-ENV:Header>

And as result my request fails:
How can I add this message correct?

A: I want the same thing as well. However, as it appears in my own searching, Spring doesn't have full functions like the SOAPMessage in java. What you probably needed was an addChildElement() to the header.
I ended up ditching the SoapMessage building and went with this:
SOAPMessage message = MessageFactory.newInstance();
private void buildHeader(String userName, String password) throws SOAPException{
    SOAPHeader header = message.getSOAPHeader();
    QName authHeader = new QName(SCHEMA, "AuthenticationHeader", SCHEMA_PREFIX);
    SOAPHeaderElement authElement = header.addHeaderElement(authHeader);

    QName userNameHeader = new QName(SCHEMA, "UserName", SCHEMA_PREFIX);
    SOAPElement userElement = authElement.addChildElement((userNameHeader));
    userElement.setTextContent(userName);

    QName passwordHeader = new QName(SCHEMA, "Password", SCHEMA_PREFIX);
    SOAPElement passwdElement = authElement.addChildElement(passwordHeader);
    passwdElement.setTextContent(password);

}

Do note that with the approach above passing a SOAPMessage using sendSourceAndReceiveToResult wraps the SOAPMessage in another envelope and this is not what we want. :(
Update (10/25/2013): I found this solution in another discussion. It's a little vague but worth looking into. I'll try to test this out on my end. One of my colleagues tried out spring-integration-ws and looking in google for the topic and soap headers yielded some promising resources.
Update (10/25/2013): After fooling around with the library I discovered there is a quicker way to wrap the SOAPMessage into Spring's SoapMessage using this:
// message is a SOAPMessage object with custom headers
SoapMessage soapMessage = new SaajSoapMessage(message);
soapMessage.writeTo(System.out);

Perhaps after you build your soapmessage you can route it to spring-ws and so on.


text:
Q: C# adding string to image, using the max font size I want to add 2 string to an image as follows:
This is Text
------------
------------
------------
--Other-----

How do I use the largest font size possible without have the String go off the side of the image?
example: if text is too big then it goes off the image::
This is Text That is too big
------------
------------
------------
--Other-----

A: I wrote this script on my previous projects to fit some text into the image by calculating its  dimensions for each font-size. when the font size is bigger than the image's width, it lowers the font size by 0.1em and tries again until the text fits in the image. Here's the code :
public static string drawTextOnMarker(string markerfile, string text, string newfilename,Color textColor)
    {
        //Uri uri = new Uri(markerfile, UriKind.Relative);
        //markerfile = uri.AbsolutePath;
        //uri = new Uri(newfilename, UriKind.Relative);
        //newfilename = uri.AbsolutePath;
        if (!System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(newfilename)))
        {
            try
            {

                Bitmap bmp = new Bitmap(System.Web.HttpContext.Current.Server.MapPath(markerfile));
                Graphics g = Graphics.FromImage(bmp);
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
                StringFormat strFormat = new StringFormat();
                strFormat.Alignment = StringAlignment.Center;
                SolidBrush myBrush = new SolidBrush(textColor);
                float fontsize = 10;
                bool sizeSetupCompleted = false;
                while (!sizeSetupCompleted)
                {
                    SizeF mySize = g.MeasureString(text, new Font("Verdana", fontsize, FontStyle.Bold));
                    if (mySize.Width > 24 || mySize.Height > 13)
                    {
                        fontsize-= float.Parse("0.1");
                    }
                    else
                    {
                        sizeSetupCompleted = true;
                    }
                }

                g.DrawString(text, new Font("Verdana", fontsize, FontStyle.Bold), myBrush, new RectangleF(4, 3, 24, 8), strFormat);
                bmp.Save(System.Web.HttpContext.Current.Server.MapPath(newfilename));
                return newfilename.Substring(2);
            }
            catch (Exception)
            {
                return markerfile.Substring(2);
            }
        }
        return newfilename.Substring(2);
    }

A: Here is a quick solution:
using (Graphics g = Graphics.FromImage(bmp))
{
    float width = g.MeasureString(text, font).Width;
    float scale = bmp.Width / width;
    g.ScaleTransform(scale, scale); //Simple trick not to use other Font instance
    g.DrawString(text, font, Brushes.Black, PointF.Empty);
    g.ResetTransform();
    ...
}

Your text won't be always 100% width if you use TextRenderingHint.AntiAliasGridFit or similar, but I think that's not a problem as you just want to make sure the text alawys fits in the image.


text:
Q: Ruby: Understanding _why's cloaker method I'm trying to understand _why's cloaker method which he wrote about in "A Block Costume":
class HTML
  def cloaker &blk
    (class << self; self; end).class_eval do
      # ... rest of method
    end
  end
end

I realise that class << self; self; end opens up the Eigenclass of self, but I've never seen anyone do this inside an instance method before. What is self at the point where we do this? I was under the impression self should be the receiver that the method was called on, but cloaker is called from inside method_missing:
def method_missing tag, text = nil, &blk
  # ...
  if blk
    cloaker(&blk).bind(self).call
  end
  # ...
end

So what is self inside the method_missing call? And what is self when we call:
((class << self; self; end).class_eval)

inside the cloaker method?
Basically, I want to know whether we are we opening the Eignenclass of the HTML class, or if we are doing it to a specific instance of the HTML class?

A: Inside the cloaker method, self will be an instance of HTML since you'll call that on a object, so you're effectively creating a Singleton Method on HTML class instances. For instance:
class HTML
  def cloaker &blk
    (class << self; self; end).class_eval do
      def new_method
      end
    end
  end
end

obj = HTML.new
obj.cloaker
p HTML.methods.grep /new_method/  # []
p obj.singleton_methods # [:new_method]

Edit
Or as  Jörg W Mittag commented , just a pre-1.9 way of the calling "Object#define_singleton_method"


text:
Q: Cómo agrupar un array de objetos por valor y concatenar demás valores en uno solo? Tengo una duda, cómo puedo hacer para mapear y reducir un array como este:

[
    {
      "Table": [
        {
          "id": 1,
          "cycle": {
            "id": 1,
            "Start": "2020-10-10"
          },
          "col": {
            "id": 1,
            "Name": "TableA"
          }
        },
        {
          "id": 2,
          "cycle": {
            "id": 1,
            "Start": "2020-10-10"
          },
          "col": {
            "id": 2,
            "Name": "TableB"
          }
        },
        {
          "id": 3,
          "cycle": {
            "id": 1,
            "Start": "2020-11-10"
          },
          "col": {
            "id": 2,
            "Name": "TableC"
          }
        }
      ]
    }
]

y quisiera poder hacer esto con el array:
[
    {
        Start: "2020-10-10",
        Name: [TableA, TableB]
    },
    {
        Start: "2020-11-10",
        Name: [TableC]
    }
]

Alguna sugerencia para llegar a lo que necesito?
Estoy escribiendo una app en React y quiero mostrar esos valores agrupados en una tabla.
Tendría que quedar algo así:

Intenté con esto:

    <TableHead>
        <TableRow class="table-secondary">
            <TableCell>Date</TableCell>
            <TableCell>Name</TableCell>
        </TableRow>
    </TableHead>
    {array.map(row => {
        return (
            <TableBody>
                <TableCell rowSpan={AQUÍ HAY QUE CONTAR CUANTOS DE CADA NAME PARA CADA CYCLE}>
                    <TableRow>
                        {row.cycle.Start}
                    </TableRow>
                </TableCell>
                <TableCell>
                    <TableRow>
                        {row.col.Name}
                    </TableRow>
                </TableCell>
            </TableBody>
        );
    })}

Lo anterior solo lista todos los elementos, pero no me los agrupa por cycle.Start.
Y hay que tener en cuanta el rowSpan para que fusione las filas para un un mismo cycle.Start.
La idea es agrupar los valores en un nuevo array, mostrarlos y ver el tamaño de Name: [TableA, TableB] por ejemplo para ver el tamaño y colocarlo en rowSpan.

A: Creo que esta es la forma mas sencilla que tienes de hacerlo se crea un hashmap para usar como llave la fecha y poder agrupar la tablas por otro lado debes recorrer el objeto para sacar la información

var objeto ='[{"Table":[{"id":1,"cycle":{"id":1,"Date":"2020-10-10"},"col":{"id":1,"Name":"TableA"}},{"id":2,"per":{"id":1,"Date":"2020-10-10"},"col":{"id":2,"Name":"TableB"}},{"id":3,"cycle":{"id":1,"Date":"2020-11-10"},"col":{"id":2,"Name":"TableC"}},{"id":3,"cycle":{"id":1,"Date":"2020-11-10"},"col":{"id":2,"Name":"Tablej"}}]}]'
// el array es distinto para ver como se agrupan por fechas
var myHash = {};
JSON.parse(objeto)[0].Table.forEach(x => {
debugger;
    if(!myHash[x?.cycle?.Date]){
        myHash[x?.cycle?.Date]= [x.col.Name]}
    else{
        myHash[x?.cycle?.Date].push(x.col.Name)
    }})

Object.entries(myHash).forEach(x=>console.log(x[0]+" "+x[1]))

El método Object.entries() devuelve una matriz de pares propios de una propiedad enumerable [key, value] de un objeto dado, en el mismo orden que es proporcionado por for...in (La diferencia es que un bucle for-in enumera las propiedades en la cadena de prototipos).
link

A: Siguiendo lo sugerido por Enrique:

Creo que esta es la forma mas sencilla que tienes de hacerlo se crea un hashmap para usar como llave la fecha y poder agrupar la tablas por otro lado debes recorrer el objeto para sacar la información.

Hice
var objeto ='[{"Table":[{"id":1,"cycle":{"id":1,"Start": "2020-10-10"},"col":{"id":1,"Name": "TableA"}},{"id":1,"cycle":{"id":1,"Start": "2020-10-10"},"col":{"id":1,"Name": "TableB"}},{"id":1,"cycle":{"id":1,"Start": "2020-11-10"},"col":{"id":1,"Name": "TableC"}}]}]'

var myHash = {};

JSON.parse(objeto)[0].Table.forEach(x => {
//debugger;
    if(!myHash[x?.cycle?.Start]){
        myHash[x?.cycle?.Start]= [x.col.Name]}
    else{
        myHash[x?.cycle?.Start].push(x.col.Name)
    }})
console.log(myHash)

Como resultado, en la consola del navegador:
{2020-10-10: Array(2), 2020-11-10: Array(1)}
2020-10-10: Array(2)
0: "TableA"
1: "TableB"
length: 2
__proto__: Array(0)
2020-11-10: Array(1)
0: "TableC"
length: 1
__proto__: Array(0)
__proto__: Object

Ahora necesito recorrer ese array para mostrar los valores como lo indica la tabla que está arriba.
Siguiendo la idea
[{Start:"2020-10-10",Name:[TableA,TableB]},{Start:"2020-11-10",Name:[TableC]}]

Intenté esto

    <TableHead>
        <TableRow class="table-secondary">
            <TableCell>Date</TableCell>
            <TableCell>Name</TableCell>
        </TableRow>
    </TableHead>
    {myHash.map(row => {
        return (
            <TableBody>
                <TableCell rowSpan={row.Name.length}>
                    <TableRow>
                        {row.Start}
                    </TableRow>
                </TableCell>
                <TableCell>
                    <TableRow>
                        {row.Name}
                    </TableRow>
                </TableCell>
            </TableBody>
        );
    })}

Que da el error:
TypeError: myHash.map is not a function

Cómo debo hacer para que la tabla quede como la imagen que publiqué en el post? Gracias!


text:
Q: In bash how to transform multimap to a map of  I am processing output from a file in bash and need to group values by their keys.
For example, I have the
13,47099
13,54024
13,1
13,39956
13,0
17,126223
17,52782
17,4
17,62617
17,0
23,1022724
23,79958
23,80590
23,230
23,1
23,118224
23,0
23,1049
42,72470
42,80185
42,2
42,89199
42,0
54,70344
54,72824
54,1
54,62969
54,1

in a file and group all values from a particular key into a single line as in
13,47099,54024,1,39956,0
17,126223,52782,4,62617,0
23,1022724,79958,80590,230,1,118224,0,1049
42,72470,80185,2,89199,0
54,70344,72824,1,62969,1

There are about 10000 entries in my input file. How do I transform this data in shell ?

A: awk to the rescue!
assuming keys are contiguous...
$ awk -F, 'p!=$1 {if(a) print a; a=p=$1}
                 {a=a FS $2}
           END   {print a}' file

13,47099,54024,1,39956,0
17,126223,52782,4,62617,0
23,1022724,79958,80590,230,1,118224,0,1049
42,72470,80185,2,89199,0
54,70344,72824,1,62969,1

A: Here is a breakdown of what @karakfa's code is doing, for us awk beginners. I've written this based on a toy dataset file:
1,X
1,Y
3,Z

*

*p!=$1: check if the pattern p!=$1 is true

*

*checks if variable p is equal to the first field of the current (first) line of file (1 in this case)

*since p is undefined at this point it cannot be equal to 1, so p!=$1 is true and we continue with this line of code

*if(a) print a: check if variable a exists and print a if it does exists

*

*since a is undefined at this point the print a command is not executed

*a=p=$1: set variables a and p equal to the value of the first field of the current (first) line (1 in this case)

*a=a FS $2: set variable a equal to a combined with the value of the second field of the current (first) line separated by the field separator (1,X in this case)

*END: since we haven't reached the end of file yet, we skip the the rest of this line of code

*move to the next (second) line of file and restart the awk code on that line

*p!=$1: check if the pattern p!=$1 is true

*

*since p is 1 and the first field of the current (second) line is 1, p!=$1 is false and we skip the the rest of this line of code

*a=a FS $2: set a equal to the value of a and the value of the second field of the current (second) line separated by the filed separator (1,X,Y in this case)

*END: since we haven't reached the end of file yet, we skip the the rest of this line of code

*move to the next (third) line of file and restart the awk code

*p!=$1: check if the pattern p!=$1 is true

*

*since p is 1 and $1 of the third line is 3, p!=$1 is true and we continue with this line of code

*if(a) print a: check if variable a exists and print a if it does exists

*

*since a is 1,X,Y at this point, 1,X,Y is printed to the output

*a=p=$1: set variables a and p equal to the value of the first field of the current (third) line (3 in this case)

*a=a FS $2: set variable a equal to a combined with the value of the second field of the current (third) line separated by the field separator (3,Z in this case)

*END {print a}: since we have reached the end of file, execute this code

*

*print a: print the last group a (3,Z in this case)

The resulting output is
1,X,Y
3,Z

Please let me know if there are any errors in this description.

A: Slight tweak to @karakfa's answer. If you want the separator between the key and the values to be different than the separator between the values, you can use this code:
awk -F, 'p==$1 {a=a "; " $2} p!=$1 {if(a) print a; a=$0; p=$1} END {print a}'


text:
Q: Dataset From Bigquery To Datastudio I connect my Firebase project to BigQuery. Then, I connected the BigQuery to DataStudio to create a dynamic dashboard.
The default DataStudio collector does not work. It gives me back an error. Going to analyze the BigQuery logs I get this:
QUERY:
SELECT t0.device.browser, t0.device.browser_version,
t0.device.web_info.browser, t0.device.web_info.browser_version
FROM  my_dataset.my_table AS t0 LIMIT 100;

RETURN:
 jobStatus: {
  additionalErrors: [
   0: {
    code:  11
    message:  "Duplicate column names in the result are not supported. Found duplicate(s): browser, browser_version"
   }
  ]
  error: {
   code:  11
   message:  "Duplicate column names in the result are not supported. Found duplicate(s): browser, browser_version"
  }
  state:  "DONE"
 }
}

Not being able to change the scheme I have no way to fix this?
Is there any way to report this to google?

A: The duplicated columns are shown here:
For browser version:
t0.device.web_info.browser_version
t0.device.browser_version
For browser:
t0.device.browser
t0.device.web_info.browser
They might look different and / or are from different sources or elements but the column names are the same, which is causing issues here.
If you can't change the schema, I recommend you to use aliases for each column like:
SELECT
  t0.device.browser AS device_browser,
  t0.device.browser_version AS device_browser_version,
  t0.device.web_info.browser AS web_browser,
  t0.device.web_info.browser_version AS web_browser_version
FROM  my_dataset.my_table AS t0 LIMIT 100;

I hope this is helpful!


text:
Q: How to access a nested string? grid = [ ['x'] * w ] * h
grid[0[2]] = 'a'

This was a test to make a grid-like structure. The thing is, I can't access a nested list because integers can't be subscripted. I've seen problems like this but they aren't a recalling problem. Any suggestions?

A: I think you may have meant:
grid[0][2] = 'a'

That would take the first element in 'grid' (a list), and set its 3rd element (at position 2) to 'a'


text:
Q: ReactJS component doesn't seem to have isolated scope I'm new to ReactJS, coming from AngularJS. I want to have a component that has a button and when you click that button it shows a textarea. Given this custom component in React:
Toggle = React.createClass({
    UI: {
        showNotes: false
    },
    toggleShowNotes: function () {
        this.UI.showNotes = !this.UI.showNotes;
        console.log(this.UI.showNotes);
        this.setState({UI: this.UI});
    },
    render: function () {
        return (

                    <button className="btn btn-default" onClick={this.toggleShowNotes}>+ Add Notes</button>

                {this.UI.showNotes ? <textarea className="form-control" placeholder="Notes"></textarea> : null }

        )
    }
});

Notice I'm logging the state of the component's UI.showNotes to the console whenever the button is clicked. If I put several of these components inside my main app, like this:
var App = React.createClass({
  render: function () {
    return (

        <Toggle></Toggle>
        <Toggle></Toggle>
        <Toggle></Toggle>
        <Toggle></Toggle>
        <Toggle></Toggle>

    );
   }
});

ReactDOM.render(
        <App/>,
        document.getElementById('container')
    );

When I click the button, what's logged to the console is always the opposite value of what was previously logged to the console. The problem is that this is true no matter which <Toggle> button I click. In other words, it seems as though there is only ONE instance of this.UI instead of one instance per component. That really confuses me, given ReactJS' documentation on the matter:

React takes care of creating an instance for every class component, so you can write components in an object-oriented way with methods and local state, but other than that, instances are not very important in the React's programming model and are managed by React itself.

I would expect this.UI to be unique to each component, not be a "global" object that's shared between all instances of the component.

*

*Why is this not the case?

*Since it's not the case, what is the best way for me to restructure my component in order to achieve the desired effect?

A: By using
UI: {
    showNotes: false
},

you're essentially creating an object that is shared across all instances because it's defined on the prototype, therefore if you change showNotes, all instances see the change
It has nothing to do with React, but with JavaScript.
Instead use something like this:
Toggle = React.createClass({
    getInitialState: function() {
        return {showNotes: true};
    },
    toggleShowNotes: function () {
        this.setState({showNotes: !this.state.showNotes});
    },
    render: function () {
        return (

                    <button className="btn btn-default" onClick={this.toggleShowNotes}>+ Add Notes</button>

                {this.state.showNotes ? <textarea className="form-control" placeholder="Notes"></textarea> : null }

        )
    }
});


text:
Q: Taking picture using OpenCV without led light on python I was able to capture an image using openCV.
What I couldn't figure out is how to capture a picture without the little LED light on. Does anyone know how to do this?
This is my function:
def cheese():
    vc = cv2.VideoCapture(0)

if vc.isOpened():  # try to get the first frame
    rval, frame = vc.read()
    frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
    img = Image.fromarray(frame)
    return img
else:
    rval = False

A: The properties of videocapture have get / set methods as  id/value pair and the led mode is the id 412. And led selector 411 !  Technically you should do :
vc.set(412,your_value ) but that one (412) is a constant.


text:
Q: How to pass params to rails form correctly I'm new to learning rails.  I want to try and create a simple app where a user can write a post and then others can leave a comment on their post.
I have 3 models.  User, Post, and Comments. I'm having trouble bringing along the post_id and user_id in the parameters when I create a new comment.
This is my new method in my comments controller
  def new
    @comment = Comment.new(user_id: params[:user_id], post_id: params[:post_id])
  end

In my server it looks like I'm passing the params key(not sure if thats the correct term) and I'm looking for the value.
Started GET "/comments/new?post_id=post_id&user_id=user_id" for ::1 at 2021-04-16 22:40:14 -0700
   (0.1ms)  SELECT sqlite_version(*)
Processing by CommentsController#new as HTML
  Parameters: {"post_id"=>"post_id", "user_id"=>"user_id"}
  Rendering comments/new.html.erb within layouts/application
  Rendered comments/_form.html.erb (Duration: 1.5ms | Allocations: 715)
  Rendered comments/new.html.erb within layouts/application (Duration: 1.8ms | Allocations: 814)
[Webpacker] Everything's up-to-date. Nothing to do
Completed 200 OK in 18ms (Views: 9.9ms | ActiveRecord: 0.6ms | Allocations: 10798)

The parameters I'm passing is "post_id" and it should be an integer corresponding to the correct post.
I'm not sure what to google to figure out how to get the params.  I thought maybe it was nested under the comments controller so I've tried
  def new
    @comment = Comment.new(user_id: params[:comments][:user_id], post_id: params[:comments][:post_id])
  end

That broke my code.  I'm at a loss.  I'm not sure what to even google to try and resolve this.  Any help would be much appreciated.  Thank you.

A: You need to pass through strong params:
https://api.rubyonrails.org/v6.1.3/classes/ActionController/StrongParameters.html
def create
  @comment = Comment.new(comment_params)
end

private

def comment_params
  params.require(:comment).permit(:user_id, :post_id)
end

And addition to that, I think you should use a post method for your http request.

A: My suggestion is don't pass lot of parameters in 'GET' method. Use post method and for strong parameters as mentioned by @thibault, you need to pass the parameters in the following format
{"comments" => {"post_id"=>"post_id", "user_id"=>"user_id"} }

In the new action, you just need to render the form, and after entering the values in the form, use 'POST' method to create the comment. There are many form helpers in rails, you can have a look on them here https://guides.rubyonrails.org/form_helpers.html
I recommend you to use rails form helper 'form_with' - https://apidock.com/rails/ActionView/Helpers/FormHelper/form_with
If you are new to the rails, use 'scaffold' and understand the things by observing the code and logs of each action.
   rails generate scaffold Comment


text:
Q: Solution of differential equation with complex coefficients Given  $$\dfrac{d^2y}{dx^2}-(3-2i)y=0,\quad y(0)=1,\quad y(x\rightarrow \infty)\rightarrow 0$$ then what is $y(\pi)$ ?
The answer given is $-e^{-\pi}$.
But I cannot understand how its solution can be pure real.

A: The general solution of
$$\frac{d^2y}{dx^2}-a^2 y=0$$
is
$$y=Ae^{ax}+Be^{-ax},$$
where $A$ and $B$ are constants. In this case, $a$ can be set as
$$a=\sqrt{\frac{\sqrt{13}+3}{2}}+i\sqrt{\frac{\sqrt{13}-3}{2}}$$
If $y(0)=1$, then $A+B=1$, and If $y(x\to\infty)\to 0$, then $e^{ax}$ must vanish, so $A=0$ and $B=1$. Then is it possible that $y(\pi)=-e^{-\pi}$? If the coefficient is $-3+4i$, as Yiorgos S. Smyrlis said, and $y(0)=-1$, then $-e^{-\pi}$ may be a possible solution.

A: Mainly, the answer is, why not?  Notice that the answer is not that $y$ is real for all values of $x$ (though maybe it is), just that $y$ is real for the specific value $x=\pi$.  You can have a very complicated looking complex function which will be pure real for certain values of the variable, for example,
$$ix^3-(3+5i)\sqrt2e^{i\pi/x^2}$$
when $x=2$.


text:
Q: Why no security prompt when I run my .exe? I'm developing a document management solution that generates self-extracting .exe's with 7zip, then signs them with signtool... Looking at the generated .exe, I can inspect the signature by looking at the signatures tab of the properties dialog, but I want the "Are you sure you want to run..." prompt, with the signature details presented in the Publisher field. Why is windows letting me run this .exe without confirmation? What do I have to do to see "Are you sure you want to run"?

A: That's because it does not require administrator privileges. Add a   .exe.manifest (MSDN) file that has  requireAdministrator set.
See also difference between highestAvailable and requireAdministrator


text:
Q: Setting content-md5 on azure blob with nodejs? I have uploaded a file with nodejs
 sharedBlobSvc.createBlockBlobFromLocalFile(containerName, blobName, path, function (error, result, response) {
                    grunt.log.writeln("uploading '"+ path +"' -> '" + blobName+"'");

I dont seem to be able to find proper documentation and is googling these meethods as i find them. Anyone got a link? I am looking to find out if the content-md5 field is being set when using nodejs to upload the file. If not what is the corrent way with nodejs to set it ( i know how to calculate it).

A: Please check the code here: https://github.com/Azure/azure-storage-node/blob/ce2faa9ec63d9f3d9b27e90c3b5fd56330aa2cc2/lib/services/blob/blobservice.js#L2971. As you can see, there's an additional parameter called options that you can pass to the method and there you can manually specify contentMD5. Also take a look at storeBlobContentMD5 in options. By default it is set to true in case of block blobs.

@param {bool} [options.storeBlobContentMD5] Specifies whether the
  blob's ContentMD5 header should be set on uploads. The default value
  is true for block blobs.

Have you seen the code here: https://github.com/Azure/azure-sdk-for-node/blob/master/lib/services/legacyStorage/lib/blob/blobservice.js (especially putBlockBlobFromFile). Basically along with the parameters you have specified, there's an additional options parameter where you can define additional parameters which includes content-md5. I have not used it myself, but looking at the options it seems that you can ask the SDK to compute MD5 for you - options.setBlobContentMD5:


text:
Q: Flow upgrade to 0.64 results in bunch of new errors I recently upgraded flow-bin and .flowconfig from 0.53 to 0.64 and now flow is resulting in bunch of new errors inside react-native framework files.
What can I do about this situation?
Error: node_modules/react-native/Libraries/Components/ScrollResponder.js:480
480:       var { animated, ...rect } = rect;
                           ^^^^^^^ rect. This type is incompatible with
472:     rect: { x: number, y: number, width: number, height: number, animated?: boolean },
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ object type
  Property `animated` is incompatible:
    472:     rect: { x: number, y: number, width: number, height: number, animated?: boolean },
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ property `animated`. Property not found in
    480:       var { animated, ...rect } = rect;
                               ^^^^^^^ rect

Error: node_modules/react-native/Libraries/Inspector/Inspector.js:104
104:       clearTimeout(_hideWait);
                        ^^^^^^^^^ null. This type is incompatible with the expected param type of
733: declare function clearTimeout(timeoutId?: TimeoutID): void;
                                               ^^^^^^^^^ TimeoutID. See lib: /tmp/flow/flowlib_213409a3/core.js:733

Error: node_modules/react-native/Libraries/Interaction/InteractionManager.js:171
171:       _nextUpdateHandle = setTimeout(_processUpdate, 0 + DEBUG_DELAY);
                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TimeoutID. This type is incompatible with
182:   _nextUpdateHandle = 0;
                           ^ number

Error: node_modules/react-native/Libraries/Lists/FlatList.js:465
           v--------------------------------
465:       this._virtualizedListPairs.push({
466:         viewabilityConfig: this.props.viewabilityConfig,
467:         onViewableItemsChanged: this._createOnViewableItemsChanged(
...:
470:       });
           -^ rest parameter array of call of method `push`. Has some incompatible type argument with
249:     push(...items: Array<T>): number;
                        ^^^^^^^^ array type. See lib: /tmp/flow/flowlib_213409a3/core.js:249
  Type argument `T` is incompatible:
                                               v
    465:       this._virtualizedListPairs.push({
    466:         viewabilityConfig: this.props.viewabilityConfig,
    467:         onViewableItemsChanged: this._createOnViewableItemsChanged(
    ...:
    470:       });
               ^ object literal. This type is incompatible with
    476:   _virtualizedListPairs: Array<ViewabilityConfigCallbackPair> = [];
                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ViewabilityConfigCallbackPair
      Property `viewabilityConfig` is incompatible:
        466:         viewabilityConfig: this.props.viewabilityConfig,
                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ undefined. Inexact type is incompatible with exact type
         26:   viewabilityConfig: ViewabilityConfig,
                                  ^^^^^^^^^^^^^^^^^ ViewabilityConfig. See: node_modules/react-native/Libraries/Lists/ViewabilityHelper.js:26

Error: node_modules/react-native/Libraries/Lists/FlatList.js:558
558:       return keyExtractor(items, index);
                               ^^^^^ array type. This type is incompatible with the expected param type of
151:   keyExtractor: (item: ItemT, index: number) => string,
                            ^^^^^ ItemT

Error: node_modules/react-native/Libraries/Lists/ViewabilityHelper.js:91
 91:     this._timers.forEach(clearTimeout);
                              ^^^^^^^^^^^^ function type. This type is incompatible with the expected param type of
572:     forEach(callbackfn: (value: T, index: T, set: Set<T>) => mixed, thisArg?: any): void;
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function type. See lib: /tmp/flow/flowlib_213409a3/core.js:572
  The first parameter is incompatible:
     77:   _timers: Set<number> = new Set();
                        ^^^^^^ number. This type is incompatible with
    733: declare function clearTimeout(timeoutId?: TimeoutID): void;
                                                   ^^^^^^^^^ TimeoutID. See lib: /tmp/flow/flowlib_213409a3/core.js:733

Error: node_modules/react-native/Libraries/Lists/ViewabilityHelper.js:200
200:         this._timers.delete(handle);
                                 ^^^^^^ TimeoutID. This type is incompatible with the expected param type of
 77:   _timers: Set<number> = new Set();
                    ^^^^^^ number

Error: node_modules/react-native/Libraries/Lists/ViewabilityHelper.js:207
207:       this._timers.add(handle);
                            ^^^^^^ TimeoutID. This type is incompatible with the expected param type of
 77:   _timers: Set<number> = new Set();
                    ^^^^^^ number

Error: node_modules/react-native/Libraries/Lists/VirtualizedList.js:484
                                  v
484:           this.scrollToIndex({
485:             animated: false,
486:             index: this.props.initialScrollIndex,
487:           }),
               ^ object literal. This type is incompatible with the expected param type of
                             v
266:   scrollToIndex(params: {
267:     animated?: ?boolean,
268:     index: number,
...:
271:   }) {
       ^ object type
  Property `index` is incompatible:
    486:             index: this.props.initialScrollIndex,
                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ null or undefined. This type is incompatible with
    268:     index: number,
                    ^^^^^^ number

Error: node_modules/react-native/Libraries/Lists/VirtualizedList.js:484
                                  v
484:           this.scrollToIndex({
485:             animated: false,
486:             index: this.props.initialScrollIndex,
487:           }),
               ^ object literal. This type is incompatible with the expected param type of
                             v
266:   scrollToIndex(params: {
267:     animated?: ?boolean,
268:     index: number,
...:
271:   }) {
       ^ object type
  Property `index` is incompatible:
    486:             index: this.props.initialScrollIndex,
                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ undefined. This type is incompatible with
    268:     index: number,
                    ^^^^^^ number

Error: node_modules/react-native/Libraries/Lists/VirtualizedList.js:500
500:     clearTimeout(this._initialScrollIndexTimeout);
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ number. This type is incompatible with the expected param type of
733: declare function clearTimeout(timeoutId?: TimeoutID): void;
                                               ^^^^^^^^^ TimeoutID. See lib: /tmp/flow/flowlib_213409a3/core.js:733

Error: node_modules/react-native/Libraries/Lists/VirtualizedList.js:1016
1016:       distanceFromEnd < onEndReachedThreshold * visibleLength &&
                              ^^^^^^^^^^^^^^^^^^^^^ null or undefined. The operand of an arithmetic operation must be a number.

Error: node_modules/react-native/Libraries/Lists/VirtualizedList.js:1016
1016:       distanceFromEnd < onEndReachedThreshold * visibleLength &&
                              ^^^^^^^^^^^^^^^^^^^^^ undefined. The operand of an arithmetic operation must be a number.

Error: node_modules/react-native/Libraries/Lists/VirtualizedList.js:1094
1094:         this.props.onEndReachedThreshold * visibleLength / 2;
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ null or undefined. The operand of an arithmetic operation must be a number.

Error: node_modules/react-native/Libraries/Lists/VirtualizedList.js:1094
1094:         this.props.onEndReachedThreshold * visibleLength / 2;
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ undefined. The operand of an arithmetic operation must be a number.

Error: node_modules/react-native/Libraries/Lists/VirtualizedList.js:1170
1170:           distanceFromEnd < onEndReachedThreshold * visibleLength
                                  ^^^^^^^^^^^^^^^^^^^^^ null or undefined. The operand of an arithmetic operation must be a number.

Error: node_modules/react-native/Libraries/Lists/VirtualizedList.js:1170
1170:           distanceFromEnd < onEndReachedThreshold * visibleLength
                                  ^^^^^^^^^^^^^^^^^^^^^ undefined. The operand of an arithmetic operation must be a number.

Error: node_modules/react-native/Libraries/Lists/VirtualizedList.js:1247
1247:     return frame;
                 ^^^^^ object type. This type is incompatible with the expected return type of
            v
1210:   ): ?{
1211:     length: number,
1212:     offset: number,
...:
1215:   } => {
        ^ object type
  Property `inLayout` is incompatible:
                v
    1210:   ): ?{
    1211:     length: number,
    1212:     offset: number,
    ...:
    1215:   } => {
            ^ property `inLayout`. Property not found in
    1247:     return frame;
                     ^^^^^ object type

Error: node_modules/react-native/Libraries/Lists/VirtualizedSectionList.js:236
236:       key: keyExtractor(viewable.item, info.index),
                                            ^^^^^^^^^^ null or undefined. This type is incompatible with the expected param type of
101:   keyExtractor: (item: Item, index: number) => string,
                                         ^^^^^^ number

Error: node_modules/react-native/Libraries/StyleSheet/flattenStyle.js:36
 36:     return getStyle(style);
                ^^^^^^^^^^^^^^^ number. This type is incompatible with the expected return type of
 29: function flattenStyle(style: ?StyleObj): ?Object {
                                               ^^^^^^ object type

Found 30 errors
error Command failed with exit code 2.


text:
Q: Higher order residues using series For example if we have any $f(z)$ with a singularity at $z=0$ but it is of order 12
Instead of using the limit definition, suppose $f(z)$ is in the form of:
$$f(z) = a_0z + a_1z^2 + a_2z^3 + ... + a_{-1}\frac{1}{z}$$
Is $a_{-1}$ still the residue of $f(z) $ at $z=0$? Even though this is of order 12?
What about then
$$\frac{f(z)}{(z+1)}$$
Will the residue at $z=0$ change?


text:
Q: Server connection timed out when using mysql pooling So I have been getting this error a lot recently.
Error: Connection lost: The server closed the connection.
at Protocol.end (/home/node_modules/mysql/lib/protocol/Protocol.js:$
at Socket.<anonymous> (/home/node_modules/mysql/lib/Connection.js:1$
at emitNone (events.js:111:20)
at Socket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)

I have been searching a lot for a solution. I read a lot that mysql pooling would solve this, which I have been using for weeks now. The error still pops up though. Does anyone know why this could be?
I'm using this base function which I found in an answer on Stackoverflow. It handles all my queries
var mysql   = require("mysql");
var config = require('./db');
var db = config.database;

var pool = mysql.createPool({
    connectionLimit : 20,
    host: db.host,
    user: db.user,
    password: db.password,
    database: db.database
});

var DB = (function () {

    function _query(query, params, callback) {
        pool.getConnection(function (err, connection) {
            if (err) {
                connection.release();
                callback(null, err);
                throw err;
            }

            connection.query(query, params, function (err, rows) {
                connection.release();
                if (!err) {
                    callback(rows);
                }
                else {
                    callback(null, err);
                }

            });

            connection.on('error', function (err) {
                connection.release();
                callback(null, err);
                throw err;
            });
        });
    };

    return {
        query: _query
    };
})();

module.exports = DB;

I'm executing queries like this:
    DB.query("SELECT * FROM lists WHERE list_id = ?", [listId], function (result, err) {
console.log(result);

}

A: The MySQL Server has a variable called interactive_timeout, this means, if your connection is idle for X seconds, the server will close the connection.
You can increase this value slightly, but the prefered way is to acknowledge the timeout and simply use a new connection from the pool if you need to query something.
See https://github.com/mysqljs/mysql#error-handling
The connection pool does not prevent any timouts, but the pool assures that you always have a connection, or have several connections if your application is under heavy load. If you only of very little traffic, you won't even need multiple connections, hence, you would not even need a connection pool.
Each connection in the pool will time out, because using release() does not close the connection but give it back to the pool.
So your disconnects are pretty normal and you should handle the error appropriately.
The connections are recreated automatically, see https://github.com/mysqljs/mysql#poolcluster-options
canRetry (Default: true)
If true, PoolCluster will attempt to reconnect when connection fails.

How do you correctly handle the error?
Prepare a general error handler for all the MySQL errors:
// Above:
mySqlErrorHandler = function(error) {
    if (error.code == '') { // <---- Insert in '' the error code, you need to find out
        // Connection timeout, no further action (no throw)
    } else {
        // Oh, a different error, abort then
        throw error;
    }
}

// In the function:
connection.on('error', mySqlErrorHandler);

You need to find out error.code for your timeout. This can be done with console.log(error.code);.


text:
Q: Exception while instantiating MockRunner- [NoSuchMethodError] [Kotlin] I have created a library for distribution the network requests amongst different clients. I am using OkHttp3 in one of the clients. For testing my library, I am trying to mock the response using the okhttp3.mockwebserver. The way I am trying to set up my mock web server is as follows:
val server = MockWebServer()
server.start()
val baseUrl = server.url("https://api.stage.zeta.in/zeta.in")

server.enqueue(MockResponse().setBody("{userID: 345923}"))

I am getting the following exception on line val server = MockWebServer():
    java.lang.NoSuchMethodError:
 okhttp3.internal.Util.immutableListOf([Ljava/lang/Object;)Ljava/util/List;

    at okhttp3.mockwebserver.MockWebServer.<init>(MockWebServer.kt:176)
    at in.zeta.android.networkrouter.MyTestClass.setup(MyTestClass.kt:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:250)
    at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:176)
    at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:49)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:142)

Not sure where I am making a mistake. Can you please help me with this?

A: Make sure the version numbers of MockWebServer and OkHttp are the same.


text:
Q: How to set separate behaviours for different sets of tabs? I am developing a functionality where I have different sets of tabs.
And I want every set of tabs to behave by itself. I mean: any of the other set of tabs have to interfere with the behaviour of the other sets.
The only error I have in the code so far is that when you click on any of the tabs of the first set, the content of the select tabs of the other sets disappear.
And I need the first tab of every set to be always selected by default.
Here is a JSFiddle I have created.

$(document).ready(function() {

  $('.tabs a:not(:first)').addClass('inactive');
  $('.container').hide();
  $('.tabs').next('.container').show();

  $('.tabs a').click(function() {
    var t = $(this).attr('id');
    if ($(this).hasClass('inactive')) { //this is the start of our condition
      $(this).siblings('a').addClass('inactive');
      $(this).removeClass('inactive');

      $(this).parent().nextAll('.container').hide();
      $('#' + t + 'C').fadeIn('slow');
    }
  });

});
.tabs {
  width: 100%;
  height: 30px;
  border-bottom: solid 1px #CCC;
  padding-right: 2px;
  margin-top: 30px;
}

a {
  cursor: pointer;
}

.tabs a {
  float: left;
  list-style: none;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  margin-right: 5px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  outline: none;
  font-family: Arial, Helvetica, sans-serif;
  font-size: small;
  font-weight: bold;
  color: #5685bc;
  ;
  padding-top: 5px;
  padding-left: 7px;
  padding-right: 7px;
  padding-bottom: 8px;
  display: block;
  background: #FFF;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  text-decoration: none;
  outline: none;
}

.tabs a.inactive {
  padding-top: 5px;
  padding-bottom: 8px;
  padding-left: 8px;
  padding-right: 8px;
  color: #666666;
  background: #EEE;
  outline: none;
  border-bottom: solid 1px #CCC;
}

.tabs a:hover,
.tabs a.inactive:hover {
  color: #5685bc;
  outline: none;
}

.container {
  clear: both;
  width: 100%;
  border-left: solid 1px #CCC;
  border-right: solid 1px #CCC;
  border-bottom: solid 1px #CCC;
  text-align: left;
  padding-top: 20px;
}

.container h2 {
  margin-left: 15px;
  margin-right: 15px;
  margin-bottom: 10px;
  color: #5685bc;
}

.container p {
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.3;
  font-size: small;
}

.container ul {
  margin-left: 25px;
  font-size: small;
  line-height: 1.4;
  list-style-type: disc;
}

.container li {
  padding-bottom: 5px;
  margin-left: 5px;
}

  test1
  test2
  test3
  test4

1Some content

2Some content

3Some content

4Some content

  test1
  test2
  test3
  test4

5Some content

6Some content

7Some content

8Some content

  test1
  test2
  test3
  test4

5Some content

6Some content

7Some content

8Some content

A: The idea is simple:
Wrap your content with a div just like how you wrap your tabs (otherwise they are all siblings).
Now add inactive to all children of tabs except the 1st child of each tabs
 $(".tabs a:not(:first-child)").addClass('inactive');

Target each div content by .tabs + div (which will find next sibling div) then hide all child that are not 1st child of each div
$(".tabs + div > div:not(:first-child)").hide();

When click on tabs, go to parent then go next div find all child (.container) and hide them, then show the id that clicked.
 $(this).parent().next('div').find('.container').hide();

Also fixed html you have, there are duplicated ids (make sure id are unique)

$(document).ready(function() {
  $(".tabs a:not(:first-child)").addClass('inactive');
  $(".tabs + div > div:not(:first-child)").hide();

  $('.tabs a').click(function() {
    var t = $(this).attr('id');
    if ($(this).hasClass('inactive')) { //this is the start of our condition
      $(this).siblings('a').addClass('inactive');
      $(this).removeClass('inactive');

      $(this).parent().next('div').find('.container').hide();
      $('#' + t + 'C').fadeIn('slow');
    }
  });

});
.tabs {
  width: 100%;
  height: 30px;
  border-bottom: solid 1px #CCC;
  padding-right: 2px;
  margin-top: 30px;
}

a {
  cursor: pointer;
}

.tabs a {
  float: left;
  list-style: none;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  margin-right: 5px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  outline: none;
  font-family: Arial, Helvetica, sans-serif;
  font-size: small;
  font-weight: bold;
  color: #5685bc;
  ;
  padding-top: 5px;
  padding-left: 7px;
  padding-right: 7px;
  padding-bottom: 8px;
  display: block;
  background: #FFF;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  text-decoration: none;
  outline: none;
}

.tabs a.inactive {
  padding-top: 5px;
  padding-bottom: 8px;
  padding-left: 8px;
  padding-right: 8px;
  color: #666666;
  background: #EEE;
  outline: none;
  border-bottom: solid 1px #CCC;
}

.tabs a:hover,
.tabs a.inactive:hover {
  color: #5685bc;
  outline: none;
}

.container {
  clear: both;
  width: 100%;
  border-left: solid 1px #CCC;
  border-right: solid 1px #CCC;
  border-bottom: solid 1px #CCC;
  text-align: left;
  padding-top: 20px;
}

.container h2 {
  margin-left: 15px;
  margin-right: 15px;
  margin-bottom: 10px;
  color: #5685bc;
}

.container p {
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.3;
  font-size: small;
}

.container ul {
  margin-left: 25px;
  font-size: small;
  line-height: 1.4;
  list-style-type: disc;
}

.container li {
  padding-bottom: 5px;
  margin-left: 5px;
}

  test1
  test2
  test3
  test4

1Some content

2Some content

3Some content

4Some content

  test1
  test2
  test3
  test4

5Some content

6Some content

7Some content

8Some content

  test1
  test2
  test3
  test4

9Some content

10Some content

11Some content

12Some content

A: I've removed the ids and replaced them by data-tab, because id should be unique and I wrapped all tabs to get only the clicked scope.

$(document).ready(function() {

  $('.tabs a').addClass('inactive');
  $('.tabs a:first-child').removeClass('inactive');
  $('.tab-container .container').hide();
  $('.tabs').next('.container').show();

  $('.tabs a').on('click', function() {
    var $tabContainer = $(this).parents('.tab-container');
    var tabId = $(this).data('tab');

    $tabContainer.find('.tabs a').addClass('inactive');
    $(this).removeClass('inactive');

    $tabContainer.find('.container').hide();
    $tabContainer.find('.container[data-tab="'+tabId+'"]').fadeIn('slow');
  });
});
.tabs {
  width: 100%;
  height: 30px;
  border-bottom: solid 1px #CCC;
  padding-right: 2px;
  margin-top: 30px;
}

a {
  cursor: pointer;
}

.tabs a {
  float: left;
  list-style: none;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  margin-right: 5px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  outline: none;
  font-family: Arial, Helvetica, sans-serif;
  font-size: small;
  font-weight: bold;
  color: #5685bc;
  ;
  padding-top: 5px;
  padding-left: 7px;
  padding-right: 7px;
  padding-bottom: 8px;
  display: block;
  background: #FFF;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  text-decoration: none;
  outline: none;
}

.tabs a.inactive {
  padding-top: 5px;
  padding-bottom: 8px;
  padding-left: 8px;
  padding-right: 8px;
  color: #666666;
  background: #EEE;
  outline: none;
  border-bottom: solid 1px #CCC;
}

.tabs a:hover,
.tabs a.inactive:hover {
  color: #5685bc;
  outline: none;
}

.container {
  clear: both;
  width: 100%;
  border-left: solid 1px #CCC;
  border-right: solid 1px #CCC;
  border-bottom: solid 1px #CCC;
  text-align: left;
  padding-top: 20px;
}

.container h2 {
  margin-left: 15px;
  margin-right: 15px;
  margin-bottom: 10px;
  color: #5685bc;
}

.container p {
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.3;
  font-size: small;
}

.container ul {
  margin-left: 25px;
  font-size: small;
  line-height: 1.4;
  list-style-type: disc;
}

.container li {
  padding-bottom: 5px;
  margin-left: 5px;
}

    test1
    test2
    test3
    test4

5Some content

6Some content

7Some content

8Some content

    test1
    test2
    test3
    test4

5Some content

6Some content

7Some content

8Some content

    test1
    test2
    test3
    test4

5Some content

6Some content

7Some content

8Some content


text:
Q: Eigen + MKL slower than Matlab for matrix multiplication I am doing a lot of matrix multiplications in a C++ program and I use Eigen (3.3.5) linked with Intel's MKL (2018.3.222). I use the sequential version of the MKL and OpenMP is disabled. The problem is that it is slower than Matlab.
Some example code:
#define NDEBUG
#define EIGEN_USE_MKL_ALL

#include <iostream>
#include <chrono>
#include <Core>

using namespace Eigen;
using namespace std;

int main(){
    MatrixXd jac = 100*MatrixXd::Random(10*1228, 2850);
    MatrixXd res = MatrixXd::Zero(2850, 2850);

    for (int i=0; i<10; i++){
        auto begin = chrono::high_resolution_clock::now();
        res.noalias() = jac.transpose()*jac;
        auto end = chrono::high_resolution_clock::now();

        cout<<"time: "<<chrono::duration_cast<chrono::milliseconds>(end-begin).count() <<endl;
    }

    return 0;
}

It reports about 8 seconds on average. Compiled with -O3 and no debug symbols on Ubuntu 16.04 with g++ 6.4.
The Matlab code:
m=100*(-1+2*rand(10*1228, 2850));
res = zeros(2850, 2850);
tic; res=m'*m; toc

It reports ~4 seconds, which is two times faster. I used Matlab R2017a on the same system with maxNumCompThreads(1). Matlab uses MKL 11.3.
Without MKL and using only Eigen, it takes about 18s. What can I do to bring the C++ running time down to the same value as Matlab's?
Thank you.
Later Edit:
As @Qubit suggested, Matlab recognises that I am trying to multiply a matrix with its transpose and does some 'hidden' optimization. When I multiplied two different matrices in Matlab, the time went up to those 8 seconds.
So, now the problem becomes: how can I tell Eigen that this matrix product is 'special' and could be optimized further?
Later Edit 2:
I tried doing it like this:
MatrixXd jac = 100*MatrixXd::Random(10*1228, 2850);
MatrixXd res = MatrixXd::Zero(2850, 2850);

auto begin = chrono::high_resolution_clock::now();
res.selfadjointView<Lower>().rankUpdate(jac.transpose(), 1);
res.triangularView<Upper>() = res.transpose();
auto end = chrono::high_resolution_clock::now();

MatrixXd oldSchool = jac.transpose()*jac;
if (oldSchool.isApprox(res)){
    cout<<"same result!"<<endl;
}
cout<<"time: "<<chrono::duration_cast<chrono::milliseconds>(end-begin).count() <<endl;

but now it takes 9.4 seconds (which is half of the time Eigen with no MKL requires for the classic product). Disabling the MKL has no time effect on this timing, therefore I believe the 'rankUpdate' method does not use MKL ?!?
Last EDIT:
I have found a bug in eigen header file:
Core/products/GeneralMatrixMatrixTriangular_BLAS.h

at line 55. There was a misplaced parenthesis. I changed this:
if ( lhs==rhs && ((UpLo&(Lower|Upper)==UpLo)) ) { \

to this:
if ( lhs==rhs && ((UpLo&(Lower|Upper))==UpLo) ) { \

Now, my C++ version and Matlab have the same execution speed (of ~4 seconds on my system).

A: To really an answer since you already figured out the issues, but some comments:

*

*The issue Core/products/GeneralMatrixMatrixTriangular_BLAS.h was already fixed in the devel branch, but it turns out it has never been brackported to the 3.3 branch.

*The issue is now fixed in the 3.3 branch. The fix will be part of 3.3.6.

*A speedup factor x2 between built-in Eigen and MKL in single thread mode does not make sense. Make sure to enable all features your CPU support by compiling with -march=native in addition to -O3 -DNDEBUG. On my Haswell 2.6GHz I get 3.4s vs 3s.


text:
Q: how to get an IHTMLElementCollection obj which composed of several IHTMLElements? guys: I got a problem about "how to get an IHTMLElementCollection obj which composed of several IHTMLElements" in object-pascal programming ,  my codes below:
function TExDomUtils.GetElementsByClassName(vDoc:IHTMLDocument3; strClassName:string):IHTMLElementCollection;
var
  vElementsAll : IHTMLElementCollection;
  vElementsRet : IHTMLElementCollection;
  vElement : IHTMLElement;
  docTmp : IHTMLDocument2;
  I ,J: Integer;
begin
  J := 0;
  vElementsAll := vDoc.getElementsByTagName('*');
  for I:=0 to vElementsAll.length - 1 do
  begin
    vElement := vElementsAll.item(I,0) as IHTMLElement;
    if vElement.getAttribute('class',0) = strClassName then
    begin
      // how to get an IHTMLElementCollection obj which composed of several IHTMLElements?
      J := J + 1;
    end;

  end;

  Result := vElementsRet;
end;

A: You could simply create your own container class, such as TList<IHTMLElement> or an array of IHTMLElements:
type
  THTMLElements = array of IHTMLElement;

function GetElementsByClassName(ADoc: IDispatch; const strClassName: string): THTMLElements;
var
  vDocument: IHTMLDocument2;
  vElementsAll: IHTMLElementCollection;
  vElement: IHTMLElement;
  I, ElementCount: Integer;
begin
  Result := nil;
  ElementCount := 0;
  if not Supports(ADoc, IHTMLDocument2, vDocument) then
    raise Exception.Create('Invalid HTML document');
  vElementsAll := vDocument.all;
  SetLength(Result, vElementsAll.length); // set length to max elements
  for I := 0 to vElementsAll.length - 1 do
    if Supports(vElementsAll.item(I, EmptyParam), IHTMLElement, vElement) then
      if SameText(vElement.className, strClassName) then
      begin
        Result[ElementCount] := vElement;
        Inc(ElementCount);
      end;
  SetLength(Result, ElementCount); // adjust Result length
end;

Usage:
procedure TForm1.FormCreate(Sender: TObject);
begin
  WebBrowser1.Navigate('http://stackoverflow.com/questions/14535755/how-to-get-an-ihtmlelementcollection-obj-which-composed-of-several-ihtmlelements');
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Elements: THTMLElements;
  I: Integer;
begin
  // show Tags information for SO page:
  Elements := GetElementsByClassName(WebBrowser1.Document, 'post-tag');
  ShowMessage(IntToStr(Length(Elements)));
  for I := 0 to Length(Elements) - 1 do
    Memo1.Lines.Add(Elements[I].innerHTML + ':' + Elements[I].getAttribute('href', 0));
end;

The main problem with returning the result as IHTMLElementCollection, is that IHTMLElementCollection is created internally by IHTMLDocument, and I could not find any way of creating a new instance of IHTMLElementCollection and adding references of the elements to it e.g.:
vElementsRet := CoHTMLElementCollection.Create as IHTMLElementCollection

will result Class not registered exception.


text:
Q: How to decode color mapping in matplotlib's Colormap? I know how to map a number to a color from this post: Map values to colors in matplotlib
But I don't know how to decode the mapping to get my original color, assuming this is a one-to-one mapping, which it must be I figure.
I am encoding an image for visualization purposes, but I need to be able to decode it and read the original data values.
For reference, here are the Colormap docs: http://matplotlib.org/api/cm_api.html
Here's my try to the main answer below, which still isn't working right.
from PIL import Image
import numpy as np
import matplotlib
import matplotlib.cm as cm
values = [670, 894, 582, 103, 786, 348, 972, 718, 356, 692]
minima = 103
maxima = 972
norm = matplotlib.colors.Normalize(vmin=minima, vmax=maxima, clip=True)
mapper = cm.ScalarMappable(norm=norm, cmap=cm.gist_rainbow_r)
c = []
for i in range(10):
    c.append(mapper.to_rgba(values[i], bytes=True))
print(c) # [(75, 255, 0, 255), (255, 77, 0, 255), (0, 255, 64, 255), (255, 0, 191, 255), (255, 250, 0, 255), (0, 72, 255, 255), (255, 0, 40, 255), (151, 255, 0, 255), (0, 83, 255, 255), (108, 255, 0, 255)]

def get_value_from_cm(color, cmap, colrange):
    # color = matplotlib.colors.to_rgba(color)
    r = np.linspace(colrange[0], colrange[1], 10) # there are 10 values
    norm = matplotlib.colors.Normalize(colrange[0], colrange[1])
    mapvals = cmap(norm(r))[:, :4] # there are 4 channels: r,g,b,a
    distance = np.sum((mapvals - color) ** 2, axis=1)
    return r[np.argmin(distance)]

decoded_colors = []
for i in range(10):
    decoded_colors.append(get_value_from_cm(c[i], cm.gist_rainbow_r, colrange=[minima, maxima]))
print(decoded_colors) # [778.88888888888891, 778.88888888888891, 489.22222222222223, 103.0, 778.88888888888891, 392.66666666666669, 103.0, 778.88888888888891, 392.66666666666669, 778.88888888888891]

A: Inverting the colormapping is possible, if
(a) you know the data range it is mapping and
(b) if you know the colormap that has been used, and
(c) if the colormap is unambiguous.
The following function would return the value given a color, a colormap and the range over which the colormap has been used.
import numpy as np
import matplotlib.colors
import matplotlib.pyplot as plt

def get_value_from_cm(color, cmap, colrange=[0.,1.]):
    color=matplotlib.colors.to_rgb(color)
    r = np.linspace(colrange[0],colrange[1], 256)
    norm = matplotlib.colors.Normalize(colrange[0],colrange[1])
    mapvals = cmap(norm(r))[:,:3]
    distance = np.sum((mapvals - color)**2, axis=1)
    return r[np.argmin(distance)]

b = get_value_from_cm(plt.cm.coolwarm(0.5), plt.cm.coolwarm, [0.,1.])
c = get_value_from_cm(np.array([1,0,0]), plt.cm.coolwarm)

print b                   # 0.501960784314
print plt.cm.coolwarm(b)
# (0.86742763508627452, 0.86437659977254899, 0.86260246201960789, 1.0)
print plt.cm.coolwarm(0.5)
#(0.86742763508627452, 0.86437659977254899, 0.86260246201960789, 1.0)

Note that this method involves an error, so you only get the closest value from the colormap and not the value that has initially been used to create the color from the map.
In the updated code from the question, you have the color defined as integers between 0 and 255 for each channel. You therefore need to first map those to the range 0 to 1.
from PIL import Image
import numpy as np
import matplotlib
import matplotlib.cm as cm
values = [670, 894, 582, 103, 786, 348, 972, 718, 356, 692]
minima = 103
maxima = 972
norm = matplotlib.colors.Normalize(vmin=minima, vmax=maxima, clip=True)
mapper = cm.ScalarMappable(norm=norm, cmap=cm.gist_rainbow_r)
c = []
for i in range(10):
    c.append(mapper.to_rgba(values[i], bytes=True))
print(c) # [(75, 255, 0, 255), (255, 77, 0, 255), (0, 255, 64, 255), (255, 0, 191, 255), (255, 250, 0, 255), (0, 72, 255, 255), (255, 0, 40, 255), (151, 255, 0, 255), (0, 83, 255, 255), (108, 255, 0, 255)]

def get_value_from_cm(color, cmap, colrange):
    color = np.array(color)/255.
    r = np.linspace(colrange[0], colrange[1], 256)
    norm = matplotlib.colors.Normalize(colrange[0], colrange[1])
    mapvals = cmap(norm(r))[:, :4] # there are 4 channels: r,g,b,a
    distance = np.sum((mapvals - color) ** 2, axis=1)
    return r[np.argmin(distance)]

decoded_colors = []
for i in range(10):
    decoded_colors.append(get_value_from_cm(c[i], cm.gist_rainbow_r, colrange=[minima, maxima]))
print(decoded_colors)


text:
Q: Initializing memory allocator in C I'm trying to implement an init_allocator() function that initializes the memory allocator and makes a portion of _length bytes available. The allocator uses a _basic_block_size as its minimal unit of allocation. The function returns the amount of memory made available to the allocator. If an error occurred, it returns 0.
This is what I have so far:
int memAvail;  // amount of memory to be made available to allocator

unsigned int init_allocator(unsigned int _basic_block_size, unsigned int _length){
    if (_basic_block_size < _ length){
        memAvail = _length/_basic_block_size;
        return memAvail;
    }
    else{
        return 0;
    }
}

I don't know if this is the right implementation but It seems right to me. Is there something I'm doing wrong? Am I supposed to make use of pointers? Any advice would be appreciated.

A: This is an example memory allocator from Chapter 5.4 in Kernighan and Ritchie
#include<stdio.h>

#define ALLOCSIZE 10000

static char allocbuf[ALLOCSIZE];
static char *allocp=allocbuf;

/* Return pointer to n characters */
char *alloc(int n)
{
   if(allocbuf+ALLOCSIZE-allocp>=n){
       // It fits
       allocp+=n;
       return allocp-n;
   }else
       // Not enough room
       return 0;
}

allocbuf is the memory buffer where you store your chars, since this is a char allocator. *alloccp is a pointer to the next free position, initially the first (i.e. 0th) element of allocbuf. *alloc returns a pointer to the first spot in allocbuf where the program will be storing the n characters.
This can be readily converted to other datatypes, it demonstrates a principle of possible simple allocator design. Clarify your requirements and I can add content.


text:
Q: Labels on X-Axis bar graph Grafana
Is there a way to add labels to the X-Axis on a bar graph in Grafana or am I simply doing it wrong?
EDIT To clarify, the labels should be values from the lob field of my table.

A: You need to put ${__cell_0} in "Display name":


text:
Q: Combing two IIS6 server together I have two IIS6 Servers.
Server A has a few websites running on it
Server B has more website running on it.
Server B is being taken off-line and wish to run all the sites on it as it a higher spec machine and we are trying to save costs.
I need to migrate:

*

*IIS 6 meta data

*SQL Databases

*DLLs of custom web apps

*User accounts

*Website files

What would you suggest being the best way to do this. I began moving each site by hand manually but this could take some time.
After the sites are moved and I have tested they are working I know I need to update the dns to point to new server.

A: Some of your migration points are fairly easy, others are not. I fear that, depending on just how "custom" your "DLLs of custom web apps" are, you may be in for a lot of manual migration.
Metabase import/export is fairly straightforward. You could parse the Metabase (since it's just XML) and locate any referenced ISAPI DLLs and migrate them over, as well. Likewise, you should be able to parse the Metabase to locate any content files that need to be migrated and ROBOCOPY / XCOPY them over. (Migrating ACLs between non-domain members is a non-trivial operation, though.)
Copying user accounts and groups between non-domain member servers can be done via script.
Moving SQL Server databases is pretty easy. Detach / move / Attach... lather, rinse, repeat. If you have a lot of them you could write some TSQL to help automate the process.
When you get into custom software, though, all bets are off. If you even know where that software is storing its configuration data you're probably stuck writing one-off scripts to migrate and alter the configuration. Be wary of ugly things like hard-coded database locations, IP addresses, etc.
Moving forward, this kind of thing is a good reason to have fairly rigorous documentation / change control procedures. The next time you have to do this you'll be happy to have those kind of docs.
There's the other argument that says "You should just be running all this on virtual machines." You could always try to do a P2V of your "Server B" machine, however you need to be aware of the potential operating system and/or application licensing concerns that could arise.


text:
Q: Twitter Bootstrap - Div content floating over top of div below I have my page laid out like this:
[ ROW 1 Col 1  Col 2 ]
[ ROW 2 Col 1  ]
When I shrink the browser window (i.e. to test responsive behaviour) I want Row 1 to push Row 2 down to make room for its content, like this:
[ ROW 1 Col 1 ]
[ ROW 1 Col 2 ]
[ ROW 2 Col   ]
The problem is that when I shrink the browser Row 2 stays fixed in place and the text in Col 2 of Row 1 floats down over the top of Row 2.
Does any one have an idea why this might be?  As far as I can tell, it's standard for twitter bootstrap divs to fold vertically at breakpoints. Mine don't do that.  I've spent a few hours reading and trying-out several things (clearfix, re-arranging the divs etc) , but can't figure it out.
Here is the code:
In the  section I have:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

And the body:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis

 Another section

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti

It's probably staring me in the face, but I can't see it.
Many thanks.
I was asked for my CSS classes. I am using the latest version of Bootstrap plus the following:
.row {
  margin-right: 0;
  margin-left: 0;
 background-color: #FFFFFF;
}

.container{
  border:1px solid #000000;
}

A: Can you post the CSS classes?
I think what you're wanting can be achieved using the float attribute.
Try adding something like this to CSS and see if it's what you need
div.col-md-8 {
    width:50%;
}
div.col-md-4 {
    float:right;
}

and then put a
 tag before your Div 2.

A: Is your .row clearing? If not try this.
.row {
  clear:both;
  margin-right: 0;
  margin-left: 0;
  background-color: #FFFFFF;
}

Would have thought that it's already in bootStrap but you never know...
Yes this should be a comment but I haven't reached 50 rep yet.

A: ====================================
Update
(I tried to add this to my own question above but wasn't logged in hence the anonymous post. Sorry about that).
Thanks for the replies above, they helped.
I copied and pasted the example code from the Bootstrap CSS page and put my content in, but still had the same problem. This narrowed down the problem to the page header. In the header I had a background image set for the header div in my CSS file like this:
.banner{
   background-image: url('../img/banner1.jpg');
   height: 250px;
}

I changed that CSS to:
.banner{
   background-image: url('../img/banner1.jpg');
   background-size: cover;
}

This worked on a cell phone but not a tablet, so I changed col-xs-* to col-sm-* and now everything is fine.
Thanks to all.


text:
Q: How to take input from .in file and provide output in another .txt file using Netbeans for java programs? I am looking from Google CodeJam point of view.
I have written my code which takes the input like
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();

Now, the contest provides the input in form of .in files and asks to upload the output file.
How exactly do we take the input from the .in file and output the solution to another .txt file?
I'm a newbie. Please help and pardon for any mistakes in the question.

A: If you have 2 files,
One -the input File: in.txt
Another -the ouput File: out.txt
Then while executing your code, Simply execute from command prompt as
java test < in.txt > out.txt
(Replace your desired input and output file names in place of in.txt and out.txt respectively)
This will take input from the content you have placed in in.txt,
and Place the output in out.txt.
Also you are generally asked to upload the code file, not the output file.
(Just check instructions once again. I amy be wrong too.)


text:
Q: Soft question: How to pronounce "Clairaut" I'm preparing for a presentation tomorrow and I will refer to clairaut's theorem in multivariable calculus (mixed partials are equal)
Can French speakers chime in as to how to correctly pronounce clairaut (for an english speaker). Is it pronounced "clear-roo" or..
Thanks!


text:
Q: Google Pay Direct Integration Rotation of keys I am trying to implement the Google Pay using direct integration and in the google docs it is mentioned that merchants have to manually rotate the keys. During rotation it is mentioned that
Caution: You must support the old private key for decryption of payment methods for eight days after you remove the old public key.
Does this mean I need to support old private key even after deleting the old public key?
I found out that Google uses Elliptic Curve Digital Signature which is asymmetric. As far as I know in case of asymmetric algorithms only one key pair will be involved (public and private). Why does Google recommend to support old private key up to 8 days?

A: The workflow is the following:

*

*define/upload a new key pair (recommended annually)

*support both new and old keys during decryption
 String decryptedMessage =
  new PaymentMethodTokenRecipient.Builder()
     .addRecipientPrivateKey(newPrivateKey)
     .addRecipientPrivateKey(oldPrivateKey);

*remove old key
This is a common approach as the platform might require some time to propagate the new keys and make sure the old ones are no longer used. You need to support the old key deploying the code above (supporting both signatures) for some time (at least 8 days according to Google's note) and ideally

confirm that the old public key is no longer used to encrypt any
transactions.


text:
Q: Concatenate 3d and 2d array I have 2 arrays
The first one has this shape
(4133,10000,12)

and the second one has this shape:
(4133,2)

I want to combine those two arrays so I get this shape
(4133,10000,12,2)

A: Shape of an array along a dimension is NOT the total number of elements. It is the number of elements PER corresponding dimension. Thus, you cannot concatenate arrays of shapes (4133,10000,12) and (4133,2) to have an array of shape (4133,10000,12,2). An easier example to think of is two matrices of shapes (m,n) and (m,k). You cannot concatenate them to have an array of shape (m,n,k).

A: I don't know what you mean by combine but you can reshape the arrays then let broadcasting kick in.  For example:
x = np.empty((10,8,4))
y = np.empty((10,2))
combined = x.reshape((10,8,4,1))*y.reshape((10,1,1,2))
print(combined.shape)
# (10,8,4,2)