text:
Q: Youtube Api with listener for state change I'm testing the Youtube API but the state listeners don't work in the demo and I don't understand why?
this is the simple code for the demo:
    <script src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" type="text/javascript"></script>
<script type="text/javascript">
    var params = { allowScriptAccess: "always" };
    var atts = { id: "myytplayer" };
    swfobject.embedSWF("http://www.youtube.com/v/u1zgFlCw8Aw?enablejsapi=1&playerapiid=ytplayer&version=3",
                       "ytapiplayer", "425", "356", "8", null, null, params, atts);
    function onYouTubePlayerReady(playerId) {
      ytplayer = document.getElementById("myytplayer");
      ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
    }
    function onytplayerStateChange(newState) {
       alert("Player's new state: " + newState);
    }
</script><div id="ytapiplayer">
You need Flash player 8+ and JavaScript enabled to view this video.  </div>

A: Are you testing it on local computer?
Try to test on website and access it with prefix http://
Edit:
You already solved it. Sorry, I realize that after posted.


text:
Q: PHP script failing to get post data from javascript/sql update query fails So I have a php script running on our server to put data into our database. I want it to handle two different scenarios: Add a new entry, or update an existing entry. I have:
$update = $_POST['Update'];

if('$update' == '0'){
$squareN = $_POST['SquareN'];
printf("N: %f\n", $squareN);
$squareE = $_POST['SquareE'];
printf("E: %f\n", $squareE);
$squareS = $_POST['SquareS'];
printf("S: %f\n", $squareS);
$squareW = $_POST['SquareW'];
printf("W: %f\n", $squareW);
$siteName = $_POST['SiteName'];
printf("Name: %s\n", $siteName);
$siteType = $_POST['SiteType'];
printf("Type: %d\n", $siteType);
$estFlags = $_POST['EstFlags'];
printf("Flags: %d\n", $estFlags);

$sql = "INSERT INTO `dec1620_db`.`Sites` (`SiteID`, `SiteName`, `CircleLat`, `CircleLon`, `CircleRad`, `SquareN`, `SquareE`, `SquareS`, `SquareW`, `Active`, `SiteType`, `EstFlags`) VALUES (NULL, '$siteName', NULL, NULL, NULL, '$squareN', '$squareE', '$squareS', '$squareW', 1, '$siteType', '$estFlags')";

mysqli_query($con, $sql) or die(mysqli_error($con));
}
if('$update' == '1'){
$squareN = $_POST['SquareN'];
printf("N: %f\n", $squareN);
$squareE = $_POST['SquareE'];
printf("E: %f\n", $squareE);
$squareS = $_POST['SquareS'];
printf("S: %f\n", $squareS);
$squareW = $_POST['SquareW'];
printf("W: %f\n", $squareW);
$siteName = $_POST['SiteName'];
printf("Name: %s\n", $siteName);

$sql = "UPDATE `Sites` SET `SquareN`='$squareN', `SquareE`='$squareE', `SquareS`='$squareS', `SquareW`='$squareW' WHERE `SiteName`='$siteName';

mysqli_query($con, $sql) or die(mysqli_error($con));
}

But $update = $_POST['Update'] kills the script with a 500 error. I have error reporting turned on, and an alert set up in my post to print data/errors, but I get nothing when the error happens... I am not sure why the $update = $_POST['Update'] fails, but all other ones succeed in grabbing correct data. Where update == 0, if I take out update and if statements and update == 1 part, that works perfectly fine when I add a new google map rectangle. When I take out update and if statement and update == 0 part and try to edit bounds of a rectangle the script errors out, again with no report of the actual error.
my posts are:
$.post("send_jobsite.php", {
       'Update': 1,
       'SquareN': rectangle.getBounds().getNorthEast().lat,
       'SquareE': rectangle.getBounds().getNorthEast().lng,
       'SquareS': rectangle.getBounds().getSouthWest().lat,
       'SquareW': rectangle.getBounds().getSouthWest().lng,
       'SiteName': rectangle.id
    }).done(function(data) {
        alert("Server Response: " + data);
    });

$.post("send_jobsite.php", {
    'Update': 0,
    'SquareN': rectangle.getBounds().getNorthEast().lat,
    'SquareE': rectangle.getBounds().getNorthEast().lng,
    'SquareS': rectangle.getBounds().getSouthWest().lat,
    'SquareW': rectangle.getBounds().getSouthWest().lng,
    'SiteName': $("#jobname").val(),
    'SiteType': 3,
    'EstFlags': $("#numberFlags").val()
    }).done(function(data) {
    alert("Server Response: " + data);
    });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Throw unformatted 401 in MVC Currently I've got the following piece of code:
            if (!checkAuthCode(LoginAuthenticatieCode))
            {
                throw new HttpException(401, "Auth Failed");
            }

This code checks if the user is authenticated, and if not throws a 401 exception. The only problem being, somewhere along the way this 401 gets packaged into a nice-looking 500 error, saying

"Message": "An error has occurred.",
  "ExceptionMessage": "Auth Failed",
  "ExceptionType": "System.Web.HttpException",
  "StackTrace": "   bij
  WebApplication1.Controllers.loginController.checkAuthCodeOrThrow(String
  LoginAuthenticatieCode) in blablabla

Is there a way to prevent ASP.NET (or MVC, I don't know which of the two is responsible) from wrapping my error in this "nice" human-readable form?

A: It looks like this is a WebAPI controller, and you're throwing an MVC exception. This difference will be unified with MVC 6 / vNext.
For now, MVC and WebAPI use different assemblies and namespaces. The System.Web.HttpException you throw is not recognized as an HTTP exception by WebAPI, so it thinks your application has thrown a random exception and formats that as a JSON-formatted 500 Internal Server Error.
So for WebAPI, throw a new HttpResponseException(HttpStatusCode.Unauthorized). This will generate an HTTP 401.

A: For ASP.NET MVC use HttpException(401, "Some message...").
For ASP.NET WebAPI use HttpResponseException(HttpStatusCode.Unauthorized).


text:
Q: Use Cauchy Inequalities to find an upper bound for $|f^4(i)|$ and $|f^4(0)|$ Let's suppose that $f$ is differentiable on a disk $B_{10}(r)$, and $|f(z)| \leq 54$ for $z$ on the circle $|z-i| = 3$. My goal is to use Cauchy Inequalities to find an upper bound for $|f^4(i)|$ and $|f^4(0)|$.
The first of these is simply a direct application of the Cauchy Inequality formula. However, the hint I was given for $|f^4(0)|$ is this statement:

A strict maximum of the absolute value of an analytic function can't be attained at the interior point of a set.

Using this information, my guess was that because $0$ is in the interior of the circle $|z-i| = 3$, we cannot find an upper bound for it. Hence, finding an upper bound for $|f^4(0)|$ is not possible.
This sounds fine at first, but I run into a question: isn't $i$ also an interior point of $|z-i| = 3$? If that's true, why does a contradiction not arise with this point as was the case for $z_0 = 0$?

A: Looking for $\boldsymbol{f^{(4)}(z)}$
If $\left|w-i\right|=3$, then
$$
\begin{align}
\left|f^{(4)}(i)\right|
&=\frac{4!}{2\pi}\left|\oint\frac{f(w)\,\mathrm{d}w}{(w-i)^5}\right|\\
&\le\frac{4!}{2\pi}\oint\frac{\left|f(w)\right|\,\left|\mathrm{d}w\right|}{\left|w-i\right|^5}\\
&\le\frac{24}{2\pi}\frac{54\cdot6\pi}{3^5}\\[6pt]
&=16
\end{align}
$$
If $\left|w-i\right|=3$, then $\left|w-0\right|\ge2$
$$
\begin{align}
\left|f^{(4)}(0)\right|
&=\frac{4!}{2\pi}\left|\oint\frac{f(w)\,\mathrm{d}w}{(w-0)^5}\right|\\
&\le\frac{4!}{2\pi}\oint\frac{\left|f(w)\right|\,\left|\mathrm{d}w\right|}{\left|w-0\right|^5}\\
&\le\frac{24}{2\pi}\frac{54\cdot6\pi}{2^5}\\[6pt]
&=\frac{243}2
\end{align}
$$

Looking for $\boldsymbol{f^4(z)}$
If $\left|w-i\right|=3$, then
$$
\begin{align}
\left|f(i)\right|
&=\frac1{2\pi}\left|\oint\frac{f(w)\,\mathrm{d}w}{w-i}\right|\\
&\le\frac1{2\pi}\oint\frac{\left|f(w)\right|\,\left|\mathrm{d}w\right|}{\left|w-i\right|}\\
&\le\frac1{2\pi}\frac{54\cdot6\pi}{3}\\[6pt]
&=54
\end{align}
$$
Therefore,
$$
\left|f^4(i)\right|\le54^4
$$
If $\left|w-i\right|=3$, then $\left|w-0\right|\ge2$
$$
\begin{align}
\left|f(0)\right|
&=\frac1{2\pi}\left|\oint\frac{f(w)\,\mathrm{d}w}{w-0}\right|\\
&\le\frac1{2\pi}\oint\frac{\left|f(w)\right|\,\left|\mathrm{d}w\right|}{\left|w-0\right|}\\
&\le\frac1{2\pi}\frac{54\cdot6\pi}{2}\\[6pt]
&=81
\end{align}
$$
But the maximum of $\left|f(z)\right|$ on $\left|z-i\right|\le3$ is attained on the boundary $\left|z-i\right|=3$, where $\left|f(z)\right|\le54$. Therefore,
$$
\left|f^4(0)\right|\le54^4
$$


text:
Q: Cannot create a mysql view from other views I have the following views
M_VWPROC_sub1,M_VWPROC_sub2,M_VWPROC_sub3,M_VWPROC_sub4,M_VWPROC_sub5,
M_VWPROC_sub6,M_VWPROC_sub7,M_VWPROC_sub8,M_VWPROC_sub9
I tried to create a view using the following sql.but I get the following error

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
  near 'M_VWPROC_sub2 union all M_VWPROC_sub3 union all M_VWPROC_sub4
  union all M_VWPROC' at line 2

Query:
CREATE OR REPLACE  VIEW M_VWPROC (UNIT, PS_DATE, LOCALIN, STOCKIN, STOCKOUT) AS
select inner_sub_table.UNIT,
       inner_sub_table.PS_DATE,
       sum(inner_sub_table.LOCALIN)LOCALIN,
       sum(inner_sub_table.pur) STOCKIN,
       sum(inner_sub_table.sale) STOCKOUT
  from M_VWPROC_sub1
 union all M_VWPROC_sub2
 union all M_VWPROC_sub3
 union all M_VWPROC_sub4
 union all M_VWPROC_sub5
 union all M_VWPROC_sub6
 union all M_VWPROC_sub7
 union all M_VWPROC_sub8
 union all M_VWPROC_sub9)
       inner_sub_table
 group by inner_sub_table.UNIT, inner_sub_table.PS_DATE;

Any help. Thanks in advance.

A: The correct syntax for union all requires a subquery . . . that is a select clause.  But, you cannot do what you want.  You need another layer of subqueries.  Something like:
create view v_YetAnotherView as
 select * from M_VWPROC_sub1
 union all select * from M_VWPROC_sub2
 union all select * from M_VWPROC_sub3
 union all select * from M_VWPROC_sub4
 union all select * from M_VWPROC_sub5
 union all select * from M_VWPROC_sub6
 union all select * from M_VWPROC_sub7
 union all select * from M_VWPROC_sub8
 union all select * from M_VWPROC_sub9;

And then:
CREATE OR REPLACE  VIEW M_VWPROC (UNIT, PS_DATE, LOCALIN, STOCKIN, STOCKOUT) AS
select inner_sub_table.UNIT,
       inner_sub_table.PS_DATE,
       sum(yav.LOCALIN)LOCALIN,
       sum(yav.pur) STOCKIN,
       sum(yav.sale) STOCKOUT
  from YetAnotherView yav
  group by yav.UNIT, yav.PS_DATE;

Do note that this ridiculous limitation on views (that the from clause cannot contain subqueries) is limited to MySQL.


text:
Q: Как создать подпись при работе с Etxt API? Пытаюсь реализовать работу с API сайта etxt.ru.
При этом, столкнулся с проблемой генерации подписи к запросам, всё остальное реализовал без проблем.
Подпись запроса
Чтобы удостовериться, что запрос отправлен действительно вами, а не злоумышленниками от лица вашего приложения, все запросы к API должны быть подписаны. Результат расчета подписи вы должны передать в параметре sign. Биржа проверит подпись и выполнит запрос только если подпись правильная.
Алгоритм использует отдельный ключ api_pass, который мы настоятельно рекомендуем вам хранить только на ваших серверах и использовать только при запросах с них к серверу Биржи. Данный ключ задается в разделе "Мой профиль/Настройки интерфейса".
sign = md5(params.md5(api_pass.'api-pass'))
Значение params — это конкатенация пар «имя=значение» отсортированных в алфавитом порядке по «имя», где «имя» — это название параметра, передаваемого в функцию API, «значение» — значение параметра. Разделитель в конкатенации не используется. Параметр sign при расчете подписи не учитывается, все остальные параметры запроса должны учитываться при расчете.
Безопасность схемы основывается на том, что api_pass знаете только вы и Биржа. Поэтому никогда не раскрывайте его третьим лицам. Если у вас возникли сомнения в безопасности api_pass, измените его в настройках профиля.

Нужно как-то реализовать это на python 3.


text:
Q: Best O(n) algorithm to find often appearing numbers? This is a example. Each number is a value
in the range between [0..k]. A number x is said to appear often in A if at least 1/3 of the numbers
in the array are equal to x.
What would be an O(n) algorithm finding the often appearing numbers for the
case when k is orders of magnitude larger than n?

A: Why not use a hash map, i.e. a hash-based mapping (dictionary) from integers to integers? Then just iterate over your input array and compute the counters. In imperative pseudo-code:
const int often = ceiling(n/3);
hashmap m;

for int i = 1 to n do {
    if m.contains(A[i])
       m[A[i]] += 1;
    else
       m[A[i]] = 1;

    if m[A[i]] >= often
        // A[i] is appearing often
        // print it or store it in the result set, etc.
}

This is O(n) in terms of time (expected) and space.


text:
Q: Does the order of "unbounded" quantifiers matter? Is $(\exists x)(\forall y)P(x,y) \Leftrightarrow (\forall y)(\exists x)P(x,y)$ ?
Please understand that I am neither asking about $(\exists x)(\forall y)P(x,y) \Leftrightarrow (\forall x)(\exists y)P(x,y)$ nor $(\exists x)(\forall y)P(x,y) \Leftrightarrow (\exists y)(\forall x)P(x,y)$ nor about "bounded" quantifications like $\forall x \in X, \exists y \in Y$.

A: No. For example, let $P(x,y)$ mean $x\ne y$, and assume there are at least two things in the universe we quantify over.
Then $\exists x \forall y (x\ne y)$ is false, but $\forall y \exists x (x \ne y)$ is true.

A: Inspired by Henning's answer...
Let a and b be two distinct objects in the domain of quantification $U$ (the "universe" set). We have:
$$a\in U$$
$$b\in U$$
$$a\neq b$$
Yes, I know the OP said "unbounded quantifiers," but I think you really need to make the "universe" set explicit to understand the principle at work here.

Part 1
Required to prove: $\neg \exists x\in U: \forall y\in U:x\neq y$
Suppose to the contrary. Let $c$ be such that $c\in U$ and $\forall y\in U: c\neq y$. This leads to the obvious contradiction $c\neq c$.

Part 2
Required to prove: $\forall y\in U: \exists x\in U: x\neq y$
Let $c$ be such that $c\in U$. Consider two cases.
Case 1: Suppose $a=c$.
Then $b\neq c$ by substitution and symmetry. Since $b\in U$, we then have $\exists x\in U: x\neq c$.
Case 2: Suppose $a\neq c$.
Since $a\in U$, we also have $\exists x\in U: x\neq c$.
In both cases, we have $\exists x\in U: x\neq c$. Generalizing on $c$, we have, as required:
$\forall y\in U: \exists x\in U: x\neq y$

A: Take for example the following two propositions paraphrased from Smith (2013) $\S$12.1.7 pp.271-2*:
$Lxy:x$ sends an arrow to $y$

*

*$\forall x \exists y(Lxy)$

*

*This claims that all things send an arrow to another thing.
A visual representation in Smith (2013) Figure 12.1 $\forall x \exists y(Lxy)$

*$\exists y \forall x (Lxy)$

*

*This claims that there is at least one thing to which every other thing sends an arrow.
A visual representation in Smith (2013) Figure 12.2 $\exists y \forall x (Lxy)$
They are not equivalent: proposition (1) could be true without (2) being necessarily true. If each thing sends an arrow somewhere, it does not follow that there is some particular thing to which everything must send an arrow.
However if (2) is true then necessarily (1) is true. If everything sends an arrow to one particular thing then a fortiori everything sends an arrow somewhere.

*Smith, N. (2013). Logic : the laws of truth . Princeton University Press.


text:
Q: Configuring Rails application in Kubernates I am configuring rails application in kubernates.I am using redis,sidekiq and Postgres DB.Below the yaml I am using.
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  namespace: dev-app
  name: test-deployment
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: Dev-app
    spec:
      nodeSelector:
       cloud.io/sec-zone-green: "true"
      containers:
        - name: dev-application
          image: hub.docker.net/appautomation/dev.app.1.0:latest
            command: ["/bin/sh"]
            args: ["-c", "while true; do echo test; sleep 20;done"]
          resources:
            limits:
              memory: 8Gi
              cpu: 5
            requests:
              memory: 8Gi
              cpu: 5
          ports:
            - containerPort: 3000
        - name: dev-app-nginx
          image: hub.docker.net/appautomation/dev.nginx.1.0:latest
          resources:
            limits:
              memory: 4Gi
              cpu: 4
            requests:
              memory: 4Gi
              cpu: 4
          ports:
            - containerPort: 80

        - name: dev-app-redis
          image: hub.docker.net/appautomation/dev.redis.1.0:latest

          resources:
            limits:
              memory: 4Gi
              cpu: 4
            requests:
              memory: 4Gi
              cpu: 4
          ports:
            - containerPort: 6379

In kubectl I am not seeing any error.But when I try to execute logs in pods I am getting below.I could see three containers build internally.I have  executed my dev-application and tried rails s to check server is running or not.But I am getting "/usr/local/bundle/gems/redis-3.3.5/lib/redis/connection/ruby.rb:229:in `getaddrinfo': getaddrinfo: Name or service not known (SocketError." How to check my application linked with redis and nginx? My yaml configuration is correct? or I need to use depends on in my yaml file.
kubectl get pods
NAME                               READY   STATUS    RESTARTS   AGE
dev-database-57b6ff5997-mgdhm   1/1     Running   0          11d
test-deployment-5f59864c8b-4t5b7   3/3     Running   0          8m44s

kubectl logs test-deployment-5f59864c8b-4t5b7
error: a container name must be specified for pod test-deployment-5f59864c8b-4t5b7, choose one of: [dev-application dev-app-nginx dev-app-redis]

Service yams file
apiVersion: v1
kind: Service
metadata:
  namespace: Dev-app
  name: test-deployment
spec:
  selector:
    app: Dev-app
  ports:
  - name: Dev-application
    protocol: TCP
    port: 3001
    targetPort: 3000
  - name: redis
    port: 6379
    targetPort: 6379

A: you are not running right way container. ideally POD running must be single application if require multiple container then and then use the multiple container inside the single POD or deployment.
you should be deploying single container in single POD or deployment instead of 3 in single.
for logs issue you check specific container logs using
kubectl logs test-deployment-5f59864c8b-4t5b7
error: a container name must be specified for pod test-deployment-5f59864c8b-4t5b7, choose one of: [dev-application dev-app-nginx dev-app-redis]

-c is used to check the specific container logs
kubectl logs test-deployment-5f59864c8b-4t5b7 -c <any one name dev-application dev-app-nginx dev-app-redis>

ideally distributed system structure goes like you run the standalone POD or deployment of the REDIS so all the services can use it here you are running your application redis if Redis crash your application will auto-restart (Kubernetes behavior).
If application crash Redis will auto-restart as Kubernetes auto-restart whole if any of container fails inside the POD.
I am getting "/usr/local/bundle/gems/redis-3.3.5/lib/redis/connection/ruby.rb:229:in `getaddrinfo': getaddrinfo: Name or service not known (SocketError.

if you are getting this error check you have set the proper host path into the application code. If all the Redis, Nginx and application running in single container you connect with any or service over the localhost. So Redis will be running at localhost 6379 for application
if you want to further debug you try using the exec command to go inside the pod and check the
kubectl exec -it test-deployment-5f59864c8b-4t5b7 -c dev-application -- /bin/bash

by this way, you will be inside the container and test out the connections to Redis using CLI.
Update :
Redis deployment.yaml
apiVersion: v1
kind: Service
metadata:
  name: redis
spec:
  type: ClusterIP
  ports:
  - port: 6379
    name: redis
  selector:
    app: redis
---
apiVersion: apps/v1beta2
kind: StatefulSet
metadata:
  name: redis
spec:
  selector:
    matchLabels:
      app: redis
  serviceName: redis
  replicas: 1
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
        - name: redis
          image: redislabs/rejson
          args: ["--appendonly", "no", "--loadmodule"]
          ports:
            - containerPort: 6379
              name: redis
          volumeMounts:
            - name: redis-volume
              mountPath: /data
  volumeClaimTemplates:
  - metadata:
      name: redis-volume
    spec:
      accessModes: [ "ReadWriteOnce" ]
      resources:
        requests:
          storage: 1Gi


text:
Q: What is the meaning of `echo ${#str}` in linux can someone explain this command to me
str=hello
echo ${#str}

this code counts the number of characters in the variable str. I want to know how it works what does the symbols $,# and {} means there
thanks.

A: '$' introduces parameter expansion, so here it "replaces" the variable with the actual value:
str=hello
echo $str
> hello

With the braces: {} you can define the boundaries of the parameter name. So: " parameter is followed by a character which is not to be interpreted as part of its name". For example this shows that "asdfg" is not part of the parameter name:
str=hello
echo ${str}asdfg
> helloasdfg

'#' just tells that you need the length of the value of that parameter.
str=hello
echo ${#str}asdfg
> 5asdfg

But as @John1024 said it's all in Parameter Expansion part of man bash


text:
Q: Cross-platform solution to do geography calculations I'm working on migrating a .Net framework application to .Net Core and I need to support running on Linux.
The application needs to calculate the intersection of polygons and very long lines on the Earths surface, and so it uses Geography objects as apposed to Geometry to take into account    the Earth's elliptical shape.
For this we use Microsoft.SqlServer.Types, which lets us do the following:
    // Line from New York to Paris
    SqlGeography line = SqlGeography.STGeomFromText(new System.Data.SqlTypes.SqlChars("LINESTRING(40.730610 -73.935242, 48.864716 2.349014)"), 4326);

    // Polygon in the Atlantic
    SqlGeography polygon = SqlGeography.STGeomFromText(new System.Data.SqlTypes.SqlChars("POLYGON((60 -40, 60 -20, 30 -20, 30 -40, 60 -40))"), 4326);

    // Contains the two locations where the line intersects with the polygon
    SqlGeography intersection = line.STIntersection(polygon);

The problem is that Microsoft.SqlServer.Types only works on Windows. How can I get the same result in a way that will also compile and run on Linux?
I've looked into NetTopologySuite but it seems to only support geometry calculations

A: Not sure if you are using EFCore or the NetTopology Suite for handling geography data in your project - but all these are already supported in that package.
Microsoft
Nuget
As you are using the WellKnownText format you can use the Docs from here:
Github Docs
I can't post the source code of my solution but an example of how to use it would be:
public class GeographyHelper
{
    private static GeometryFactory _geometryFactory
    {
        get
        {
            return NetTopologySuite.NtsGeometryServices.Instance.CreateGeometryFactory(4326);
        }
    }

    public bool TestIntersectsAPolygon(double latitude, double longitude)
    {
        var wellKnownText = "YOUR POLYGON WKT";

        var point = _geometryFactory.CreatePoint(new Coordinate(longitude, latitude));
        var rdr = new NetTopologySuite.IO.WKTReader();
        var geometry = rdr.Read(wellKnownText);

        var polygon =  _geometryFactory.CreatePolygon(geometry.Coordinates);

        var intersects = polygon.Intersects(point);

        return intersects ;
    }
}


text:
Q: Redirect from index page in Spring and Tomcat I have a Spring application, which is running on Tomcat say at: http://example.com/foo/
DisplatcherServlet is mapped to app/*, for example, index page is:
http://example.com/foo/app/index.html

This is so because I have other servlets (for HttpRequestHandlers), e.g. mapped to service/*. This scheme is convenient to use because this way app/ and service/ can have different security settings.
What I want is http://example.com/foo to redirect to http://example.com/foo/app/index.html.
How do I achieve this?

A: In your web.xml, you can define a welcome file, seen when navigating to the root of the app:
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

You can then make a tiny index.jsp that redirects to where you want:
<% response.sendRedirect("app/index.html"); %>

A: You can add the (tuckey) Url Rewrite Filter to your application.
It provides you the functionality to define URL rewrite rules in you Application (ingoing and outgoing).
So you can define a rewrite rule for \ that it rewrites to myApplication.startpage - or something else.
@see: http://mattgivney.blogspot.com/2010/07/how-to-url-rewrite-in-spring-mvc.html - for a short example


text:
Q: Appending text to a video using ffmpeg I would like to add a blank screen at the end of my video with some white text in the middle (in bold). I've seen this post and I would like to do something alike, but the text should be added at the end of my existing video. All the parameters of the video (resolution, bit rate...) should be kept.
Any idea how I can do this? Thanks

A: So here is what I ended up doing. It's probably not the best solution but it does work :

*

*I created a 10 second video with the text on it. This post was particularly useful to split the text in multiple lines.

*Then I merged the two videos. I've had a few issues with the containers and this post helped a lot.
I hope this will help someone.


text:
Q: Stats window located at the bottom of the container I put a WebGL plot into a div container. Everything works except the Stats window which is displaying below the WebGL window.
Here what I get :

my code :
<html>
<head>
        <style>
#container{
        display: block;
        margin: 0 auto;
        width: 700px;
        height: 700px;
           }
        </style>
</head>

<body>

...

<div id="container">
</div>

<script>

if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

var container, stats;
var camera, controls, scene, renderer;
var cross;
var width = 700, height = 700;

init();
animate();

function init() {

        // Define container
        container = document.getElementById( 'container' );

// Add renderer to container
  container.appendChild( renderer.domElement );

  // Add stats
  stats = new Stats();
  stats.domElement.style.position = 'relative';
  stats.domElement.style.zIndex = 100;
  container.appendChild( stats.domElement );
}
</script>

</body>
</html>

For having a Stats window at the left top of the container, I have to add :
stats.domElement.style.bottom = '700px';

How to put naturally the Stats window at the left top of the container ? i.e without this trick.
Thanks

A: Ok, you can use basically two ways to get it.
the first: prepend the stats to the #container element, inserting it as child of body element and use some css in order to set it as a block relative to the body.
the second: keep statistics as they are and add this css
.yourStatsClass {
    left: 0;
    top: 0;
}


text:
Q: Renaming columns using column data from another dataframe I have two dataframes - an original file that looks like this:
Gene Symbol, 10555, 10529, 10519
Map7, .184, .026, .207
nan, .348, .041, .187
Cpm, .45, .278, .453

and a reference file that looks like this:
Experiment_Num, Microarray, Experiment_Name, Chip_Name
10555, Genechip, Famotidine-5d, RG230-2
10529, Genechip, Famotidine-3d, RG230-2
10519, MMchip, Dicyclomine-3d, R01

I am trying to merge them in a way that the header of the original file display the Experiment_Name rather than just the Experiment_Num as follows:
Gene symbol, Famotidine-5d, Famotidine-3d, Dicyclomine-3d
Map7, .184, .026, .207
nan, .348, .041, .187
Cpm, .45, .278, .453

My code is completely written using pandas and looks as follows:
 import pandas as pd

df = ('ftp://anonftp.niehs.nih.gov/drugmatrix/Differentially_expressed_gene_lists_directly_from_DrugMatrix/Affymetrix/Affymetrix_annotation.txt', sep='\t', dtype=str)
# Reference file

df2.columns = df2.columns.to_series().replace(df.set_index('Experiment').Compound_Name)
#Original File

df2

I tried to convert the columns of the original DF to it's series representation and then replace the old value which were the Experiment_Num. with the new Experiment_name retrieved from the reference DF, but keep getting
KeyError: 'Experiment'
I tried figuring out what could be causing a KeyError, but found that there are so many possibilities, none of which seems to fix my particular issue.
Thanks for the help if possible!
Troy


text:
Q: Set created by modified by dynamically with mixin Coming from the rails world, I was pleased to find out about mixins. I set up a
Basic mixin
core/mixins.py
from django.db import models
from django.contrib.auth.models import User

class Timestamps(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

And then my Event model in core/my_app/models.py
from core import mixins as core_mixins

class Event(core_mixins.Timestamps):
    # ...

all jolly good, but what if I wanted to extend this a bit and create a more dynamic mixin?
Advanced mixin
core/mixins.py
from django.db import models
from django.contrib.auth.models import User

from django.dispatch import receiver
from django.db.models.signals import pre_save
from cw_core.requestprovider.signals import get_request

class Trackable(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    created_by = models.ForeignKey(User, related_name='created_XXX') # <-- ???
    updated_by = models.ForeignKey(User, related_name='updated_XXX') # <-- ???

    class Meta:
        abstract = True

@receiver(pre_save, sender=Event) # <-- ???
def security_attributes(sender, instance, **kwargs):
    request = get_request()

    instance.updated_by = request.user

    if instance.id is None:
        instance.created_by = request.user

core/my_app/models.py
from core import mixins as core_mixins

class Event(core_mixins.Trackable):
    # ...

*

*How would I dynamically set the related_name? I found this question but I have not found the variables I could use in strings, are there any docs?

*Also how would I dynamically set the sender in the @receiver call?
My attempt would be to set:
@receiver(pre_save, sender=self.__class__)

But I am unsure if this will work? What is the suggested approach?

A: Just use existing functionality https://docs.djangoproject.com/en/1.11/topics/db/models/#abstract-related-name
class Trackable(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    created_by = models.ForeignKey(User, related_name='created_%(class)s')
    updated_by = models.ForeignKey(User, related_name='updated_%(class)s')
    class Meta:
        abstract = True

And for second part there is also solution https://stackoverflow.com/a/17173716/3627387
@receiver(pre_save)
def security_attributes(sender, instance, **kwargs):
    if not issubclass(sender, core_mixins.Trackable):
        return
    request = get_request()

    instance.updated_by = request.user

    if instance.id is None:
        instance.created_by = request.user

Basically you could filter senders inside signal processor.
Also there is django-model-utilshttps://django-model-utils.readthedocs.io/en/latest/models.html#timestampedmodel


text:
Q: Mysql2::Error: All parts of a PRIMARY KEY must be NOT NULL I am using a legacy version of rails 3.2.22 and while trying to execute my migration file, I encountered this error:
rake db:migrate
==  CreateBooks: migrating ====================================================
-- create_table(:books)
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

Mysql2::Error: All parts of a PRIMARY KEY must be NOT NULL; if you need NULL in a key, use UNIQUE instead: CREATE TABLE `books` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `Book Title` varchar(255), `Author` varchar(255), `Date Published` date, `Book ID` int(11), `Checked Out?` tinyint(1), `Return Time` datetime, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL) ENGINE=InnoDB
/usr/share/rvm/gems/ruby-2.1.10/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `_query'
/usr/share/rvm/gems/ruby-2.1.10/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in `block in query'
/usr/share/rvm/gems/ruby-2.1.10/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `handle_interrupt'
/usr/share/rvm/gems/ruby-2.1.10/gems/mysql2-0.3.21/lib/mysql2/client.rb:79:in `query'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:245:in `block in execute'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract_adapter.rb:280:in `block in log'
/usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract_adapter.rb:275:in `log'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:245:in `execute'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/mysql2_adapter.rb:213:in `execute'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/schema_statements.rb:170:in `create_table'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:434:in `create_table'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:466:in `block in method_missing'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:438:in `block in say_with_time'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:438:in `say_with_time'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:458:in `method_missing'
/home/elliot/Desktop/SAIT WORK/Library/db/migrate/20220609183208_create_books.rb:3:in `up'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:410:in `block (2 levels) in migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:410:in `block in migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_pool.rb:129:in `with_connection'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:389:in `migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:528:in `migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:720:in `block (2 levels) in migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:777:in `call'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:777:in `ddl_transaction'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:719:in `block in migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:700:in `each'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:700:in `migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:570:in `up'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/migration.rb:551:in `migrate'
/usr/share/rvm/gems/ruby-2.1.10/gems/activerecord-3.2.22/lib/active_record/railties/databases.rake:193:in `block (2 levels) in <top (required)>'
/usr/share/rvm/gems/ruby-2.1.10/gems/rake-12.3.3/exe/rake:27:in `<top (required)>'
/usr/share/rvm/gems/ruby-2.1.10/bin/ruby_executable_hooks:24:in `eval'
/usr/share/rvm/gems/ruby-2.1.10/bin/ruby_executable_hooks:24:in `<main>'

I am well aware of the fact that people have posted this problem in the past and there have been solutions posted that helped solve this problem but when I attempt to utilize those solutions, I encounter errors. In particular, I am referencing this guide:
Link to solution 1
However, when I implement the suggested changes, I can run the rake db:migrate, however, when I try to run any other rails command (i.e. rails s or rails console), I get this error:
rails s
=> Booting WEBrick
=> Rails 3.2.22 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
Exiting
/usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:251:in `require': cannot load such file -- /home/elliot/Desktop/SAIT WORK/Library/lib/patches/abstract_mysql_adapter (LoadError)
    from /usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:251:in `block in require'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:236:in `load_dependency'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:251:in `require'
    from /home/elliot/Desktop/SAIT WORK/Library/config/environment.rb:3:in `<top (required)>'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:251:in `require'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:251:in `block in require'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:236:in `load_dependency'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:251:in `require'
    from /home/elliot/Desktop/SAIT WORK/Library/config.ru:3:in `block in <main>'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/rack-1.4.7/lib/rack/builder.rb:51:in `instance_eval'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/rack-1.4.7/lib/rack/builder.rb:51:in `initialize'
    from /home/elliot/Desktop/SAIT WORK/Library/config.ru:in `new'
    from /home/elliot/Desktop/SAIT WORK/Library/config.ru:in `<main>'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/rack-1.4.7/lib/rack/builder.rb:40:in `eval'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/rack-1.4.7/lib/rack/builder.rb:40:in `parse_file'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/rack-1.4.7/lib/rack/server.rb:200:in `app'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/railties-3.2.22/lib/rails/commands/server.rb:46:in `app'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/rack-1.4.7/lib/rack/server.rb:304:in `wrapped_app'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/rack-1.4.7/lib/rack/server.rb:254:in `start'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/railties-3.2.22/lib/rails/commands/server.rb:70:in `start'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/railties-3.2.22/lib/rails/commands.rb:55:in `block in <top (required)>'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/railties-3.2.22/lib/rails/commands.rb:50:in `tap'
    from /usr/share/rvm/gems/ruby-2.1.10/gems/railties-3.2.22/lib/rails/commands.rb:50:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

I have also tried the implementing the solution suggested here:
Link to Solution 2 but I would run into the same error. Could this problem relate to the naming convention of my models and tables? I am very stuck so any help would be greatly appreciated.
app/models/book.rb
class Book < ActiveRecord::Base
  # attr_accessible :title, :body
end

config/database.yml !!!Note that I omitted the password and username for privacy, but they are implemented correctly I believe!!!
# MySQL.  Versions 4.1 and 5.0 are recommended.
#
# Install the MYSQL driver
#   gem install mysql2
#
# Ensure the MySQL gem is defined in your Gemfile
#   gem 'mysql2'
#
# And be sure to use new-style password hashing:
#   http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: Library_development
  pool: 5
  username: **
  password: **
  socket: /var/run/mysqld/mysqld.sock

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: Library_test
  pool: 5
  username: **
  password: **
  socket: /var/run/mysqld/mysqld.sock

production:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: Library_production
  pool: 5
  username: **
  password: **
  socket: /var/run/mysqld/mysqld.sock

db/migrate/20220609183208_create_books.rb
class CreateBooks < ActiveRecord::Migration
  def up
    create_table :books do |t|
      t.string 'Book Title'
      t.string 'Author'
      t.date "Date Published"
      t.integer "Book ID"
      t.boolean "Checked Out?"
      t.datetime "Return Time"
      t.timestamps
    end
  end

  def down
    drop_table :books
  end

end

Gemfile
source 'https://rubygems.org'

gem 'rails', '3.2.22'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

# gem 'mysql2'

gem 'mysql'
gem 'mysql2', "~> 0.3.10"

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'

  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  # gem 'therubyracer', :platforms => :ruby

  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'

# To use Jbuilder templates for JSON
# gem 'jbuilder'

# Use unicorn as the app server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

# To use debugger
# gem 'debugger'

gem 'devise'

gem 'cancancan'

gem 'mail_interceptor', group: [:development, :staging]

#gem 'sidekiq', '~>6.0.0'

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '~> 2.13'
  gem 'selenium-webdriver'
  gem 'rspec-rails', '~> 3.5'
  gem 'factory_bot_rails'
  gem 'database_cleaner'
end

gem "bootstrap-sass", "~> 3.1.1.0"


text:
Q: PHP multiline, concatenated strings Any difference between the two, int terms of speed/performance?
$sql = "SELECT * "
     . "FROM `myTable` "
     . "WHERE `id` = 4";

$sql = "SELECT *
        FROM `myTable`
        WHERE `id` = 4";

A: Maybe a very very very small difference, the first one probably being a bit slower (because of concatenations)...
... But the time taken to execute your single simple SQL query will be thousands (maybe hundreds, with a simple query -- just a wild guess, but you'll see the point) of times more important than that very small difference !
So, you really shouldn't bother about that kind of "optimizations", and consider/choose what is the most easy to both write/read/understand and maintain.

EDIT : just for fun, here are the opcodes that are generated for the first portion of code :
$ php -dextension=vld.so -dvld.active=1 temp-2.php
Branch analysis from position: 0
Return found
filename:       /home/squale/developpement/tests/temp/temp-2.php
function name:  (null)
number of ops:  6
compiled vars:  !0 = $sql
line     #  op                           fetch          ext  return  operands
-------------------------------------------------------------------------------
   5     0  EXT_STMT
         1  CONCAT                                           ~0      'SELECT+%2A+', 'FROM+%60myTable%60+'
         2  CONCAT                                           ~1      ~0, 'WHERE+%60id%60+%3D+4'
         3  ASSIGN                                                   !0, ~1
   8     4  RETURN                                                   1
         5* ZEND_HANDLE_EXCEPTION

And, for the second one :
$ php -dextension=vld.so -dvld.active=1 temp-2.php
Branch analysis from position: 0
Return found
filename:       /home/squale/developpement/tests/temp/temp-2.php
function name:  (null)
number of ops:  4
compiled vars:  !0 = $sql
line     #  op                           fetch          ext  return  operands
-------------------------------------------------------------------------------
   7     0  EXT_STMT
         1  ASSIGN                                                   !0, 'SELECT+%2A%0A++++++++FROM+%60myTable%60%0A++++++++WHERE+%60id%60+%3D+4'
   9     2  RETURN                                                   1
         3* ZEND_HANDLE_EXCEPTION

So, yes, there is a difference... But, still, what I said before is still true : you shouldn't care about that kind of optimization : you'll do so many "not-optimized" stuff in the other parts of your application (or even if the configuration of your server) that a small difference like this one means absolutly nothing

Well, except if you are google and have thousands of servers, I guess ^^

A: To test this kind of stuff, you use a big while loop and run the code over-and-over to compare. Do this twice (or more) to compare operations. Run it a few dozen times and track the results.
ob_start();
$t = microtime(true);
while($i < 1000) {
    // CODE YOU WANT TO TEST

    ++$i;
}
$tmp = microtime(true) - $t;
ob_end_clean();

echo $tmp

A: i think the latter is faster. because you have used the concatenation operator in the former which parsing it may take some time.

A: I think that the first one might take a little longer because of concatenation, but, it is not  going to be much of a difference. If you are worried about optimization you can start by using stored procedures in your database instead of writing the SQLs in your php code. This will not only increase speed but also security.


text:
Q: function or way to convert euler rotation to fixed axis rotation ( world rotation )? I need function or way to convert Euler rotation to fixed axis rotation or converting fixed axis rotation to Euler rotation .
Here is an example .
I have Euler rotation "XYZ" ( red arrow ) of the sphere and I want to know "XYZ" rotation of Fixed rotation world ( blue arrow ) or conversely .
Thank you .


text:
Q: Saving .xml on client javascript im looking for a solution to write a file on the clientside that has .xml as file extention.
im using p5.js, so i get the save() function, makes it quite easy for me to save files, but it will add .txt to the file.
Whats the best way to export data in xml on the client?
Thats my code on the client.
function exportFixture(){

    let data = [];

    let standartHeader = '<?xml version="1.0" encoding="utf-8"?>';
    let maHeader = '<MA xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.malighting.de/grandma2/xml/MA" xsi:schemaLocation="http://schemas.malighting.de/grandma2/xml/MA http://schemas.malighting.de/grandma2/xml/3.3.4/MA.xsd" major_vers="3" minor_vers="3" stream_vers="4">';

    data.push(standartHeader);
    data.push(maHeader);

    save(data, "text.xml");
    // alert("Exported fixture");
  }

A: You can use the saveStrings(list,filename,[extension]) method and rewrite your save call like:
saveStrings(data, "text", "xml");

Alternatively, you can just rewrite the call to the save method like so:
save(data, "text", "xml");

Both ways worked for me.

A: In my application,I'm using downloadjs something like this:
download(data, "mydata.xml", "text/plain");

and this is a Demo for HTML file


text:
Q: FxCop installation I am trying to get latest version of FxCop. I am using Visual Studio 2010 Professional edition which does not include code analysis, so I am trying to set it up using FxCop.
At http://www.microsoft.com/en-us/download/details.aspx?id=6544 there is readme file whic says to install Windows SDK which includes latest FxCop. I've installed Windows SDK from here http://www.microsoft.com/en-us/download/details.aspx?id=8442 and it does not include FxCop at all, I have checked both x86 and x64 versions.
Any idea where can I find it? Is FxCop supported by Microsoft any more?
EDIT:
I did full installation of Windows SDK. I am installing x86 version on Windows 7 x86. I have searched in x64 Windows SDK ISO for FxCop only by extracting it into folder.
The only place I found FxCop 10 is in answer https://stackoverflow.com/a/7151981/84852

A: I have the folder C:\Program Files\Microsoft SDKs\Windows\v7.0A\FXCop in my SDK install, however it is for the older version of FxCop. I also have the setup for the latest version of FxCop, but I can't remember where I found it, and its just as easy for you to download it from that other question.
However these days I follow the instructions detailed on this blog post because the FxCop command line runner produces different results than the IDE Code Analysis runner (namely because FxCop doesn't support the new phoenix engine), and I wanted my build server to enforce the same rules as were run in the IDE.
This procedure also gave me the ability to relax the rules for my unit test projects (there is an issue in VS2010 whereby the ruleset configured for the first project built became the ruleset for all projects, regardless of what was configured).
UPDATE
If required, this Code Analysis Team blog post says that the FxCop 10.0 setup is included in Microsoft Windows SDK for Windows 7 and .NET Framework 4 Version 7.1 and can be found in the folder %ProgramFiles%\Microsoft SDKs\Windows\v7.1\Bin\FXCop.

A:
FxCop Installation Instructions

*

*Download the Microsoft Windows SDK for Windows 7 and .NET Framework 4 version 7.1.

*Run %ProgramFiles%\Microsoft SDKs\Windows\v7.1\Bin\FXCop\FxCopSetup.exe to install FxCop.

but I found it in

C:\Program Files\Microsoft SDKs\Windows\v6.0A\FXCop

A: Since FxCop 10.0 is distributed as part of Windows 7 SDK, you have to do some download and extractions to install it on servers which are not running Windows 7.

Any idea where can I find it? Is FxCop supported by Microsoft any more?

You can download the file directly from here:
https://fxcopinstaller.codeplex.com/
This project is not created by Microsoft. I made it just for saving you and other people a few steps of extracting the binary from the original package. I did not change anything in the original MSI file provided by Microsoft. I also don't accept any contributor's upload to keep the file genuine.
[UPDATE]
Codeplex is shutting down. New location is www.fxcopinstaller.com.


text:
Q: How to set all data in a slice, got from mongodb using mgo? I am trying to fetch data from MongoDB that has dynamic keys and set it in a slice.
Here is my data sample:
_id ObjectIdHex("5911786dc28f25578150501d")
2017-05-01 [800 1000 1200 1400 1600]
_id ObjectIdHex("59117897c28f25578150501e")
2017-05-02 [800 1000 1200 1400 1600]
_id ObjectIdHex("5911789ec28f25578150501f")
2017-05-03 [800 1000 1200 1400 1600]
2017-05-04 [800 1000 1200 1400 1600]
_id ObjectIdHex("591178a6c28f255781505020")
_id ObjectIdHex("591178abc28f255781505021")
2017-05-05 [800 1000 1200 1400 1600]
_id ObjectIdHex("591178b0c28f255781505022")
2017-05-06 [800 1000 1200 1400 1600]
_id ObjectIdHex("591178b5c28f255781505023")
2017-05-07 [800 1000 1200 1400 1600]
_id ObjectIdHex("591178bac28f255781505024")
2017-05-08 [800 1000 1200 1400 1600]
_id ObjectIdHex("591178c8c28f255781505025")
2017-05-09 [800 1000 1200 1400 1600]
2017-05-10 [800 1000 1200 1400 1600]

I need to set it into an array like {2017-05-09 : [800 1000 1200 1400 1600]} and same for other entries.
I have tried
package main

import(
    "fmt"
    "gopkg.in/mgo.v2/bson"
    //"encoding/json"
)

type Spot struct{
    Id      bson.ObjectId   `json:"_id,omitempty" bson:"_id,omitempty"`
    Spots   map[string]interface{} `json:"spots"`
}

//type Values []Value

//var result []struct{ Value int }
type Spots []Spot

func getAllSpots() (Spots) {
    mongoSession := getDbSession()

    sessionCopy := mongoSession.Copy()
    defer sessionCopy.Close()
    var spots []Spot
    c := mongoSession.DB("test").C("spots")
    var data []bson.M
    err := c.Find(bson.M{}).All(&data)
    if err != nil {
        panic(err)
        // TODO: Do something about the error
    }

    test := make(map[string]int)
    for _, doc := range data {
      for key, value := range doc {
        if(key == "_id"){
            test[key] = value
            fmt.Println(key, value)
        }
      }
    }

    return spots
}

I am able to get the spots in data and able to write the output to the console using fmt.Println() but when I assign it to a slice it gives me the following error:

cannot use value (type interface {}) as type int in assignment: need type assertion

I searched all over the web but couldn't find a valid solution. Can anyone please guide me what am I doing wrong?

A: If you look at the documentation for bson.M, you'll see that it's just an alias for map[string]interface{}. That means when you range over it, your key is a string, and your value is an interface{}. Your target is a map[string]int. So when you test[key] = value, you're trying to assign value (an interface{}) to something expecting an int, which you can't do without an explicit cast (aka type assertion). This is exactly what the error message says: cannot use value (type interface {}) as type int in assignment: need type assertion. You could instead do:
test[key] = value.(int)

But as a putu noted, it looks like those values are actually arrays of ints, which doesn't fit the test type at all, as it is a map of strings to single int values. So you'd need to either change the type of test to map[string][]int or pick a value from the source array to store in the map, e.g.
test[key] = (value.([]int))[0]


text:
Q: ios NSURLSession JSON parsing to nil in swift (ok in obj-c) my obj-c code is fine.
can someone help me figure out what's wrong with my swift code?
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:url]
        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            // handle response
            if (error) {
                TGLog(@"FAILED");
            } else {
                NSError* jsonerror;
                NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonerror];
                if (jsonerror != nil) {
                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                    TGLog(@"response status code: %ld", (long)[httpResponse statusCode]);
                    TGLog(@"%@", jsonerror);
                    return;
                }
                TGLog(@"%@", json);
                TGLog(@"status %@ reason %@", [json objectForKey:@"status"], [json objectForKey:@"reason"]);
            }
        }] resume];

and outputs
2016-11-19 ...._block_invoke:39 status success reason updated

but when I implement it in swift status and reason are nil
var request = URLRequest(url: url)
request.httpMethod = "POST"

URLSession.shared.dataTask(with: request) {data, response, err in
    print("Entered user update completionHandler")

    DispatchQueue.main.async() {
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
    }
    if let error = err as? NSError {
        print(error.localizedDescription)
    } else if let httpResponse = response as? HTTPURLResponse {
        if httpResponse.statusCode == 200 {
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any]
                print(json)
                let status = json["status"] as? [String:Any]
                let reason = json["reason"] as? [String:Any]
                // TODO: this is always printing out nil values - haven't figure out the swift problem yet
                print("status \(status) reason \(reason)")
            } catch let error as NSError {
                    print(error)
            }
        }
    }

}.resume()

my webpage outputs
{"status":"success","reason":"updated","uuid":"blahblahblahbahaldsh"}

A: Read the JSON, status and reason are String rather than a dictionary
 let status = json["status"] as? String
 let reason = json["reason"] as? String

According to the given JSON you could even cast json to [String:String]
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:String]

then you get rid of the other type casts
 let status = json["status"]
 let reason = json["reason"]

The result of both lines is optional String. As you seem to be responsible for the web service you can unwrap the optionals if your service sends always the keys status and reason
 let status = json["status"]!
 let reason = json["reason"]!


text:
Q: Sticky columns horizontal scrolling of window not table I have used the Sticky Table headers from codrops:
http://tympanus.net/codrops/2014/01/09/sticky-table-headers-columns/
and have made a few changes. Working sample uploaded here:
http://codepen.io/dbn14/pen/yyQjjQ

$(function() {
  $('table').each(function() {
    if ($(this).find('thead').length > 0 && $(this).find('th').length > 0) {
      // Clone

      var $w = $(window),
        $t = $(this),
        $thead = $t.find('thead').clone(),
        $col = $t.find('thead, tbody').clone();

      // Add class, remove margins, reset width and wrap table
      $t
        .addClass('sticky-enabled')
        .css({
          margin: 0,
          width: '100%'
        }).wrap('
');

      if ($t.hasClass('overflow-y')) $t.removeClass('overflow-y').parent().addClass('overflow-y');

      // Create new sticky table head (basic)
      $t.after('
');

      // If
 contains , then we create sticky column and intersect (advanced)
      if ($t.find('tbody th').length > 0) {
        $t.after('

');
      }

      // Create shorthand for things
      var $stickyHead = $(this).siblings('.sticky-thead'),
        $stickyCol = $(this).siblings('.sticky-col'),
        $stickyInsct = $(this).siblings('.sticky-intersect'),
        $stickyWrap = $(this).parent('.sticky-wrap');

      $stickyHead.append($thead);

      $stickyCol
        .append($col)
        .find('thead th:gt(0)').remove()
        .end()
        .find('tbody td').remove();

      $stickyInsct.html('

' + $t.find('thead th:first-child').html() + '

');

      // Set widths
      var setWidths = function() {
          $t
            .find('thead th').each(function(i) {
              $stickyHead.find('th').eq(i).width($(this).width());
            })
            .end()
            .find('tr').each(function(i) {
              $stickyCol.find('tr').eq(i).height($(this).height());
            });

          // Set width of sticky table head
          $stickyHead.width($t.width());

          // Set width of sticky table col
          $stickyCol.find('th').add($stickyInsct.find('th')).width($t.find('thead th').width())
        },
        repositionStickyHead = function() {
          // Return value of calculated allowance
          var allowance = calcAllowance();

          // Check if wrapper parent is overflowing along the y-axis
          if ($t.height() > $stickyWrap.height()) {
            // If it is overflowing (advanced layout)
            // Position sticky header based on wrapper scrollTop()
            if ($stickyWrap.scrollTop() > 0) {
              // When top of wrapping parent is out of view
              $stickyHead.add($stickyInsct).css({
                opacity: 1,
                top: $stickyWrap.scrollTop()
              });
            } else {
              // When top of wrapping parent is in view
              $stickyHead.add($stickyInsct).css({
                opacity: 0,
                top: 0
              });
            }
          } else {
            // If it is not overflowing (basic layout)
            // Position sticky header based on viewport scrollTop
            if ($w.scrollTop() > $t.offset().top && $w.scrollTop() < $t.offset().top + $t.outerHeight() - allowance) {
              // When top of viewport is in the table itself
              $stickyHead.add($stickyInsct).css({
                opacity: 1,
                top: $w.scrollTop() - $t.offset().top
              });
            } else {
              // When top of viewport is above or below table
              $stickyHead.add($stickyInsct).css({
                opacity: 0,
                top: 0
              });
            }
          }
        },
        repositionStickyCol = function() {
          if ($stickyWrap.scrollLeft() > 0) {
            // When left of wrapping parent is out of view
            $stickyCol.add($stickyInsct).css({
              opacity: 1,
              left: $stickyWrap.scrollLeft()
            });
          } else {
            // When left of wrapping parent is in view
            $stickyCol
              .css({
                opacity: 0
              })
              .add($stickyInsct).css({
                left: 0
              });
          }
        },
        calcAllowance = function() {
          var a = 0;
          // Calculate allowance
          $t.find('tbody tr:lt(3)').each(function() {
            a += $(this).height();
          });

          // Set fail safe limit (last three row might be too tall)
          // Set arbitrary limit at 0.25 of viewport height, or you can use an arbitrary pixel value
          if (a > $w.height() * 0.25) {
            a = $w.height() * 0.25;
          }

          // Add the height of sticky header
          a += $stickyHead.height();
          return a;
        };

      setWidths();

      $t.parent('.sticky-wrap').scroll($.throttle(250, function() {
        repositionStickyHead();
        repositionStickyCol();
      }));

      $w
        .load(setWidths)
        .resize($.debounce(250, function() {
          setWidths();
          repositionStickyHead();
          repositionStickyCol();
        }))
        .scroll($.throttle(250, repositionStickyHead));
    }
  });
});
body {
  background-color: #FFF;
}
/* Component styles */

.component {
  line-height: 1.5em;
  padding: 0em;
  width: 100%;
  overflow: hidden;
  margin-top: 0;
  margin-bottom: 0;
}
.component .filler {
  font-family: "Blokk", Arial, sans-serif;
  color: #d3d3d3;
}
table {
  border-collapse: collapse;
  width: 100%;
  background: #fff;
}
td,
th {
  padding: 0;
  text-align: left;
}
th {
  background-color: rgba(255, 255, 255, .5);
  font-weight: bold;
  color: #333;
  white-space: nowrap;
}
tbody th {} tbody tr:nth-child(2n-1) {
  transition: all .125s ease-in-out;
}
tbody tr {}
/* For appearance */

.sticky-wrap {
  overflow-x: auto;
  overflow-y: hidden;
  position: relative;
  margin: 0;
  width: 100%;
}
.sticky-wrap .sticky-thead,
.sticky-wrap .sticky-col,
.sticky-wrap .sticky-intersect {
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;
  transition: all .125s ease-in-out;
  z-index: 50;
  width: auto;
  /* Prevent table from stretching to full size */
}
.sticky-wrap .sticky-thead {
  box-shadow: 0 0.25em 0.1em -0.1em rgba(0, 0, 0, .125);
  z-index: 100;
  width: 100%;
  /* Force stretch */
}
.sticky-wrap .sticky-intersect {
  opacity: 1;
  z-index: 150;
}
.sticky-wrap .sticky-intersect th {} .sticky-wrap td,
.sticky-wrap th {
  box-sizing: border-box;
}
/* Not needed for sticky header/column functionality */

td.user-name {
  text-transform: capitalize;
}
.sticky-wrap.overflow-y {
  overflow-y: auto;
  max-height: 50vh;
}
.map {
  height: 175px;
  width: 175px;
  margin-bottom: 0px;
  margin-left: 5px;
  margin-top: 0px;
  margin-right: 8px;
}
.content {
  min-width: 175px;
  min-height: 175px;
  background-color: #099;
  margin-right: 8px;
  color: #FFF;
  padding: 0;
  margin-top: -5px;
}

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Content for class "content" Goes Here

Everything working fine apart from the horizontal scrolling isn't how I'd like it to be. Instead of having to scroll to the bottom of the table to scroll horizontally, I'd like to be able to scroll horizontally using the actual browser window. Is there a way to achieve this?


text:
Q: Почему не работает break; var answer = 100;
var userAnswer1 = +prompt('Первый игрок: Угадайте моё число от 0 до 100:');
var userAnswer2 = +prompt('Второй игрок: Угадайте моё число от 0 до 100:');

while (((userAnswer1 || userAnswer2) != answer) || ((userAnswer1 || userAnswer2) !== null)) {

   if (userAnswer1 == answer || userAnswer1 === null) {
      break;
   } else if (userAnswer1 > answer) {
      alert('Первый игрок: Моё число меньше!');
   } else if (userAnswer1 < answer) {
      alert('Первый игрок: Моё число больше!');
   }

   if (userAnswer2 == answer || userAnswer2 === null) {
      break;
   } else if (userAnswer2 > answer) {
      alert('Второй игрок: Моё число меньше!');
   } else if (userAnswer2 < answer) {
      alert('Второй игрок: Моё число больше!');
   }
   userAnswer1 = +prompt('Первый игрок: Введите число ещё раз:');
   userAnswer2 = +prompt('Второй игрок: Введите число ещё раз:');
}

if (userAnswer1 == answer) {
   alert('Первый игрок: Поздравляю, Вы угадали!');
}
if (userAnswer2 == answer) {
   alert('Второй игрок: Поздравляю, Вы угадали!');
}
document.write('Правильное число: ' + answer);

A: (userAnswer1 || userAnswer2) != answer - это не так сравнивается. Ведь если два ответа будут отменены, то (null || null) != answer будет true. А это не желаемое поведение, судя из задачи.

var answer = 100;
var userAnswer1 = +prompt('Первый игрок: Угадайте моё число от 0 до 100:');
var userAnswer2 = +prompt('Второй игрок: Угадайте моё число от 0 до 100:');

while (userAnswer1 !== answer || userAnswer2 !== answer || !userAnswer1 || !userAnswer2) {
   if (userAnswer1 === answer || !userAnswer1) break;
   else if (userAnswer1 > answer) alert('Первый игрок: Моё число меньше!');
   else if (userAnswer1 < answer) alert('Первый игрок: Моё число больше!');

   if (userAnswer2 === answer || !userAnswer2) break;
   else if (userAnswer2 > answer) alert('Второй игрок: Моё число меньше!');
   else if (userAnswer2 < answer) alert('Второй игрок: Моё число больше!');

   userAnswer1 = +prompt('Первый игрок: Введите число ещё раз:');
   userAnswer2 = +prompt('Второй игрок: Введите число ещё раз:');
}

if (userAnswer1 === answer) alert('Первый игрок: Поздравляю, Вы угадали!');
if (userAnswer2 === answer) alert('Второй игрок: Поздравляю, Вы угадали!');

document.write('Правильное число: ' + answer);


text:
Q: How does a while statement in ruby work? I'm trying to learn ruby and I noticed something strange. When my nth element reaches 101 it will not go out of the loop even when it says
while n < 101. Can someone explain why this is happening ?
n = 0
sum = 0
while n < 101
        n = n +1
        sum = sum + n
        puts "The count is #{n}"
        puts "The sum is #{sum}"
end
puts "The sum is: #{sum}"

A: As @sagarpandya82 mentioned,

Look at where you've put the puts "The count is #{n}". It's after you
  add one to the count: n = n

To answer your original question (i think), in your loop n is 100, then you add 1 to it and reaches 101 and then terminates. That's why your last output is 101.
If you want to do something 100 times, you can also do
sum = 0
100.times do |n|
  sum += n
  puts "the count is: #{n + 1}"
  puts "The sum is: #{sum}"
end

n starts at 0 and goes to 99 (100 times)

A: You may be confuse because it prints count is 101, that's because you're incrementing the counter before you print.

A: To be clear…
Slower…
When n reachs 100:
 n = 100

So:
while n < 101 # => while 100 < 101

… is true, the loop can go on.
We go on:
n = n + 1    # n += 1 should be better

So, now:
n = 101

And we follow:
while n < 101 # => while 101 < 101

… is false.
So we stop with value of n : 101, not 100.


text:
Q: Pointwise and Uniform Convergence on a specific intervall I have the sequence of functions
$$ f_n(x) = \frac{x}{x^2+ \frac{1}{n}} \quad x \in [0, \infty)$$ and I need to show that the sequence converges pointwise as well as uniformly, however only on the intervall $[\alpha, \infty) $ where $\alpha > 0 $.
I started out finding the limit function of $f_n(x)$ in the following manner:
$$ \lim_{n \to \infty} f_n(x) = \lim_{n \to \infty} \frac{x}{x^2+ \frac{1}{n}} \xrightarrow{n \to \infty} \frac{x}{x^2} = \frac{1}{x} $$
which leads me to my first question: Is this enough to show that $f_n(x)$ converges pointwise to $\frac{1}{x}$ ?
I have at first gone on with the idea that I can actually do that, which leads then to my formula for uniform convergence:
$$ |f_n(x) - f(x)| = \left|\frac{x}{x^2 + \frac{1}{n}} - \frac{1}{x}\right| = \left| \frac{-1}{nx^3 + x}\right| \leq \frac{1}{nx^3}$$
My second question is of course if this is at all allowed. If it is, is it then enough to show that as long as $x > 0$ this function is defined and therefore this function is uniformly convergent?

A: You proved correctly that $\lim_{n\to\infty}f_n(x)=\frac1x$ if $x>0$. You should add to this that $\lim_{n\to\infty}f_n(0)=0$. Therefore, your sequence converges pointwise to the function $f\colon[0,+\infty)\longrightarrow\mathbb R$ defined by$$f(x)=\begin{cases}\frac1x&\text{ if }x>0\\0&\text{ if }x=0.\end{cases}$$So, the convergence cannot be uniform, since the uniform limit of a sequence of continuous functions is always continuous.
In order to prove that it converges uniformly on $[\alpha,+\infty)$, you can note that$$\left|\frac x{x^2+\frac1n}-\frac1x\right|=\frac1n\left|\frac1{x^3+\frac xn}\right|=\frac1{nx^3+x}\leqslant\frac1{n\alpha^3+\alpha}\to0.$$

A: Uniformly in $[\alpha,\infty],$ $\alpha >0$
You have :
$|f_n(x)-f(x)| \lt \dfrac {1}{nx^3} \le \dfrac{1}{n\alpha^3}.$
Let $\epsilon >0$ be given.
Archimedes' principle:
There is a $n_0 \in \mathbb{Z^+}$ such that
$n_0 \gt (\epsilon\alpha^3)^{-1}.$
For $n \ge n_0$ we have
$|f_n(x)-f(x)| \lt \dfrac {1}{n\alpha^3} \le  \dfrac{1}{n_0\alpha^3} \lt \epsilon.$

A: All you did so far is correct. It remains to show that the convergence $f_n \to \frac1x$ is uniform on $[\alpha, +\infty)$:
$$\left|f_n\left(x\right) - f\left(x\right)\right|  = \frac1{nx^3+x} \le \frac{1}{nx^3} \le \frac1{n\alpha^3} \xrightarrow{n\to\infty} 0$$
uniformly in $x \in [\alpha, +\infty)$.
The convergence $f_n \to \frac1x$ is not uniform even on $(0, +\infty)$:
$$\left|f_n\left(\frac1n\right) - f\left(\frac1n\right)\right| = \frac{1}{n\left(\frac1n\right)^3 + \frac1n} = \frac{n^2}{n+1}$$
which does not converge to $0$ as $n\to\infty$.


text:
Q: Sorting a date attached to a note I need to sort a list with a note to it.
For instance:
list = ['2015-12-01: remember groceries' , '2017-12-21 : buy presents'] etc.

My problem is that I need to sort the list by the dates and still have the notes attached to that date. Any ideas how to do this? Dictionary? Lists within lists?
I know how to sort just the dates, but I can't seem to figure out how to sort it with the notes attached to it.

A: Assuming that your data all look like this:

*

*Every entry in the array is a string

*Every entry begins with the date in the format 'YYYY-MM-DD'

Then you could do simply do
list.sort();

This would sort the strings in your array lexicographically, and for dates in the above format this is equivalent to sorting them in the normal time line. This would not work if your dates also have other formats like 'YYYY-M-DD'.

A: Your date presentation is sortable as is. just
res = sorted(list)

A: just go for a list of tuples. this is always sorted by the first element and you can get your date value and your note separately
list = [('2015-12-01', 'remember groceries') , ('2017-12-21', 'buy presents'), ('2015-12-21', 'xxx')]
print(sorted(list))
print(list[0][1], list[1][1])


text:
Q: Kohana 3 ORM. How to set up Inflector irregular word arrays in the Bootstrap or Model I am using Kohana 3 ORM and it seems that the Inflector is singularising the word 'causes' to the form 'caus' instead of 'cause'. I have a _has_many_"through" relationship setup and even through all my foreign keys are setup to read 'cause_id' it still wants to setup an ON clause in SQL where it references 'caus_id' rather than 'cause_id'.
Is there a way to set up the Cause model to recognise the default singular form is 'cause'?
Or is there a way to add an Inflector->irregular array in the Bootstrap.php file?
I've hacked the SYSPATH.'config/inflector.php' file adding the exception and it does fix the problem but I would prefer a method that doesn't involve hacking the system files.
What is the 'best practice' approach please.

A: *

*Copy SYSPATH/config/inflector.php to APPPATH/config/inflector.php and change what you want. This will allow you to upgrade framework core without loosing your modifications.

*Post an issue and this will be fixed in the next release.


text:
Q: MYSQL - How to workaround the row size limit of 66 KBytes I have a mysql db. I use innodb. 0ne of my tables contains a little more than 10  columns. The last column has a type of LONGTEXT and it is supposed to contain html code. The problem is, for each record, that field does not conatin the full code and it stops always after the same amount of characters. The weight of the html files I try to insert is around 60KO. So I guess each of my record exceeds the row size limit of mysql (66KO). What I would like to know is if there are some ways to extand that limit. Any workaround would be much appreciated. Thanks in advance for the inputs. Cheers. Marc

A: Values for (LONG)TEXT (and BLOB) are not stored "in the row" but outside of it. Therefor the size of your HTML does not contribute to the size of the individual rows.
From the manual:

The internal representation of a table has a maximum row size of 65,535 bytes, even if the storage engine is capable of supporting larger rows. This figure excludes BLOB or TEXT columns, which contribute only 9 to 12 bytes toward this size
For BLOB and TEXT data, the information is stored internally in a different area of memory than the row buffer.

(emphasis mine)
http://dev.mysql.com/doc/refman/5.5/en/storage-requirements.html

A: When you say "that field does not conatin the full code and it stops always after the same amount of characters", how are you determining what the field contains?  I suspect what you're viewing has been truncated by the max_allowed_packet variable.
As stated in the MySQL manual:

The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers. You can change the message buffer size by changing the value of the max_allowed_packet variable, but you must do so for both the server and your client program. For example, both mysql and mysqldump enable you to change the client-side max_allowed_packet value.   See Section 8.11.2, "Tuning Server Parameters", Section 4.5.1, "mysql — The MySQL Command-Line Tool", and Section 4.5.4, "mysqldump — A Database Backup Program". You may also want to compare the packet sizes and the size of the data objects you are storing with the storage requirements, see Section 11.5, "Data Type Storage Requirements"

A: The accepted answer is wrong (or at least pretty opinionated) - I don't personally want data stored outside of my database, as it creates complications in terms of backup procedures and transactional queries.
As others have pointed out, the manual repeatedly states that BLOB and TEXT columns do not count towards the total row-size, but unfortunately, with the default configuration settings, that's not true, and you end up getting this error-message. (The error-message doesn't make any sense, because it's telling you to use TEXT instead of VARCHAR to address the issue - which you already are.)
The reason for this limitation is the default storage mechanism, Antelope, which stores the first 768 bytes of variable-length columns in the row - and a possible solution is to use INNODB and switch your storage mechanism to the alternative Barracuda storage mechanism:
SET GLOBAL innodb_file_format=Barracuda;

This will have no immediate effect, because this setting is a default for new database files - so you will need to drop and recreate your entire database.
Alternatively, switch to Barracuda (as above) and then (in addition) switch to the file-per-table strategy:
SET GLOBAL innodb_file_per_table=ON;

Again, this will have no immediate effect, because both settings are defaults for new tables - so again, you will need to drop and recreate the table.
If you look in the MySQL data folder after doing this, you can confirm that separate files were created, e.g. for a database named "data", and a table named "test", you should see  a file named "data/test/bigtable.ibd".
If you dislike changing the global settings in MySQL, try SET SESSION instead of SET GLOBAL, e.g. immediately before running your CREATE TABLE statements.

A: There is no way to extend this limit, as it is not dependent on the storage engine but it is a hard limit on the server:

Every table (regardless of storage engine) has a maximum row size of
  65,535 bytes. Storage engines may place additional constraints on this
  limit, reducing the effective maximum row size.

In this case the solutions should revolve around deferring the storage of HTML to some other place - on the filesystem or on the cloud (S3) and then refer to the file name in the table column.

A: We resolved it with following below steps.
Step-1: Run below queries into MySql to set global variables.

*

*SET GLOBAL innodb_file_format=Barracuda;

*SET GLOBAL innodb_file_per_table=ON;

Step-2: Select table from which the error occur when you trying to save large data into single row.
Step-3: Go to Operations
Step-4: Select COMPRESSED from ROW_FORMAT. (By default COMPACT and REDUNDANT will be there when you set global variables innodb_file_format and innodb_file_per_table you can find another options like COMPRESSED and DYNAMIC)
Step-5: Click Go.
:)


text:
Q: Why my Google OAuth 2 login button is not working? I'm trying to learn about OAuth 2 by implementing a login page to my application with google sign-in button. but the button doesn't response or call the signInCallBack() when I click on it, and I don't know what is the problem? .. I already have tried to add onClick action instead of data-callback but this didn't work.
<!DOCTYPE html>

  </script>

  <button type="button" id="signinButton" class="google-button">

      <svg viewBox="0 0 366 372" xmlns="http://www.w3.org/2000/svg"><path d="M125.9 10.2c40.2-13.9 85.3-13.6 125.3 1.1 22.2 8.2 42.5 21 59.9 37.1-5.8 6.3-12.1 12.2-18.1 18.3l-34.2 34.2c-11.3-10.8-25.1-19-40.1-23.6-17.6-5.3-36.6-6.1-54.6-2.2-21 4.5-40.5 15.5-55.6 30.9-12.2 12.3-21.4 27.5-27 43.9-20.3-15.8-40.6-31.5-61-47.3 21.5-43 60.1-76.9 105.4-92.4z" id="Shape" fill="#EA4335"/><path d="M20.6 102.4c20.3 15.8 40.6 31.5 61 47.3-8 23.3-8 49.2 0 72.4-20.3 15.8-40.6 31.6-60.9 47.3C1.9 232.7-3.8 189.6 4.4 149.2c3.3-16.2 8.7-32 16.2-46.8z" id="Shape" fill="#FBBC05"/><path d="M361.7 151.1c5.8 32.7 4.5 66.8-4.7 98.8-8.5 29.3-24.6 56.5-47.1 77.2l-59.1-45.9c19.5-13.1 33.3-34.3 37.2-57.5H186.6c.1-24.2.1-48.4.1-72.6h175z" id="Shape" fill="#4285F4"/><path d="M81.4 222.2c7.8 22.9 22.8 43.2 42.6 57.1 12.4 8.7 26.6 14.9 41.4 17.9 14.6 3 29.7 2.6 44.4.1 14.6-2.6 28.7-7.9 41-16.2l59.1 45.9c-21.3 19.7-48 33.1-76.2 39.6-31.2 7.1-64.2 7.3-95.2-1-24.6-6.5-47.7-18.2-67.6-34.1-20.9-16.6-38.3-38-50.4-62 20.3-15.7 40.6-31.5 60.9-47.3z" fill="#34A853"/></svg>

    Sign in with Google
  </button>

A: Made changes in code :
<!DOCTYPE html>

  </script>

  <button type="button" id="signinButton" class="google-button">

      <svg viewBox="0 0 366 372" xmlns="http://www.w3.org/2000/svg"><path d="M125.9 10.2c40.2-13.9 85.3-13.6 125.3 1.1 22.2 8.2 42.5 21 59.9 37.1-5.8 6.3-12.1 12.2-18.1 18.3l-34.2 34.2c-11.3-10.8-25.1-19-40.1-23.6-17.6-5.3-36.6-6.1-54.6-2.2-21 4.5-40.5 15.5-55.6 30.9-12.2 12.3-21.4 27.5-27 43.9-20.3-15.8-40.6-31.5-61-47.3 21.5-43 60.1-76.9 105.4-92.4z" id="Shape" fill="#EA4335"/><path d="M20.6 102.4c20.3 15.8 40.6 31.5 61 47.3-8 23.3-8 49.2 0 72.4-20.3 15.8-40.6 31.6-60.9 47.3C1.9 232.7-3.8 189.6 4.4 149.2c3.3-16.2 8.7-32 16.2-46.8z" id="Shape" fill="#FBBC05"/><path d="M361.7 151.1c5.8 32.7 4.5 66.8-4.7 98.8-8.5 29.3-24.6 56.5-47.1 77.2l-59.1-45.9c19.5-13.1 33.3-34.3 37.2-57.5H186.6c.1-24.2.1-48.4.1-72.6h175z" id="Shape" fill="#4285F4"/><path d="M81.4 222.2c7.8 22.9 22.8 43.2 42.6 57.1 12.4 8.7 26.6 14.9 41.4 17.9 14.6 3 29.7 2.6 44.4.1 14.6-2.6 28.7-7.9 41-16.2l59.1 45.9c-21.3 19.7-48 33.1-76.2 39.6-31.2 7.1-64.2 7.3-95.2-1-24.6-6.5-47.7-18.2-67.6-34.1-20.9-16.6-38.3-38-50.4-62 20.3-15.7 40.6-31.5 60.9-47.3z" fill="#34A853"/></svg>

    Sign in with Google
  </button>

Here is reference document :
https://developers.google.com/identity/sign-in/web/build-button
Note : You need to get client id from project. it will be something like this
4234760167137-vud910b6hg4o6svll814nbrrr07mp3qt.apps.googleusercontent.com


text:
Q: How do I add extra data to a submitted form in Symfony 2? I have a simple form that only uploads an image. However, in my database I want to extract and record some EXIF data from that image.
I'm not sure what to use in Symfony2. It does't seem like the right place to calculate this extra information in the Entity. Where else could I put it?
<?php

namespace Timeline\DefaultBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class Document
{
    //...

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        // extract EXIF here?
    }

}

A: Doctrine events can work nicely as long as you don't need to modify another entity.
I think the best way to handle your case would be to use form events.
http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-form-events-user-data
For example you could use a POST_SUBMIT event, and dynamically add a 'exif' text field, and on your entity a $exif property mapping your database field.

class Document
{

    /**
     * @ORM\Column(type="text")
     */
    private $exif;
}

class DocumentType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('file', 'file')
        ;

        $builder->addEventListener(
            FormEvents::PRE_SUBMIT,
            function (FormEvent $event) {
                $form = $event->getForm();

                $data = $event->getData();
                $data['exif'] = 'data';
                $event->setData($data);

                $form->remove('exif');
                $form->add('exif', 'string');
            }
        );
    }
}

Edit #1 :
After further research, the only way I found is to define 'exif' key in data array and 'exif' field in form, so it will be able to mapped it to your entity.
I didn't found a way to solve the problem of the remaining 'exif' field in the form after submission. If you define it as hidden, or do not use {{ form_rest() }}, it will not appear, but this not so clean ...