Q: CSS Translate and Scale on Y-Axis? I am taking an online course learning CSS and we are just covering CSS animations. I am trying to practice some of the things I learned (just basic transforms for now) by creating a small animation of a man walking towards the screen down a pathway.
Basically, I want to both translate and scale my image at the same time. I got this working fine, but now I also wanted to add some small rotation so that it looks like the man is slightly moving left and right. Here is my code in a jsfiddle, I don't know how to change the transform-origin so that the man is walking in a straight line on the Y-Axis, the scale makes him walk in a diagonal. I hope that makes sense...
The commented out part of the code includes the scale, as soon as that is added back, and the part without scale is commented out, it acts funny and I'm thinking this has to do with the origin?
https://jsfiddle.net/qLLqdxbm/
HTML:

CSS:
.man-walk {
    width: 100px;
    height: 125px;
    position: absolute;
    top: 0;
    left: 50px;

    animation-name: man-walk;
    animation-duration: 0.45s;
    animation-iteration-count: infinite;
}

@keyframes man-walk {
    0% {
        transform: rotate(0deg);
    }

    25% {
        transform: rotate(1.5deg);
    }

    50% {
        transform: rotate(0deg);
    }

    75% {
        transform: rotate(-1.5deg);
    }

    100% {
        transform: rotate(0deg);
    }
}

.man-scale {
    width: 100px;
    height: 125px;

    animation-name: man-scale;
    animation-duration: 2s;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
}

/* define the animation */
@keyframes man-scale {
/*     0% {
        transform: translate(0px, 5px) scale(1.1);
    }

    25% {
        transform: translate(0px, 15px) scale(1.5);
    }

    50% {
        transform: translate(0px, 25px) scale(1.7);
    }

    75% {
        transform: translate(0px, 35px) scale(2.0);
    }

    100% {
        transform: translate(0px, 45px) scale(2.3);
    } */

    0% {
        transform: translate(0px, 5px);
    }

    25% {
        transform: translate(0px, 15px);
    }

    50% {
        transform: translate(0px, 25px);
    }

    75% {
        transform: translate(0px, 35px);
    }

    100% {
        transform: translate(0px, 45px);
    }
}

Thanks for the help!

A: Each time you scale the image along X and Y, the origin shifts in both dimensions by a specific offset. If you can compensate for that offset in the X dimension then a vertical animation could be achieved.
In this case in first keyframe the scale increased by 0.1 which is 100 * 0.1 = 10px now origin got offset by 5px in X dimension, compensating in terms of translateX(-5px). Similarly for all the other keyframes.
If you want a faster animation in the Y dimension just increase the Y translate values without touching the X translation values.

.man-walk {
    width: 100px;
    height: 125px;
    position: absolute;
    top: 0;
    left: 50px;

    animation-name: man-walk;
    animation-duration: 0.45s;
    animation-iteration-count: infinite;
}

@keyframes man-walk {
    0% {
        transform: rotate(0deg);
    }

    25% {
        transform: rotate(1.5deg);
    }

    50% {
        transform: rotate(0deg);
    }

    75% {
        transform: rotate(-1.5deg);
    }

    100% {
        transform: rotate(0deg);
    }
}

.man-scale {
    width: 100px;
    height: 125px;

    animation-name: man-scale;
    animation-duration: 2s;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
}

/* define the animation */
@keyframes man-scale {
     0% {
        transform: translate(-5px, 30px) scale(1.1);
    }

    25% {
        transform: translate(-20px, 70px) scale(1.4);
    }

    50% {
        transform: translate(-35px, 120px) scale(1.7);
    }

    75% {
        transform: translate(-50px, 180px) scale(2.0);
    }

    100% {
        transform: translate(-65px, 250px) scale(2.3);
    }
}

There might be some advanced CSS techniques to calculate the offset automatically.


Q: RewriteCond with the famous !-f and !-d conditions is not working I have .htaccess file with the following directives:
RewriteEngine on

RewriteBase /amit/public/
RewriteCond ${REQUEST_FILENAME} !-f [OR]
RewriteCond ${REQUEST_FILENAME} !-d [OR]
RewriteCond ${REQUEST_FILENAME} !-s [OR]
RewriteCond ${REQUEST_FILENAME} !-l
RewriteRule ^(.*[^/])/?$ $1.php [NC,L]

Pretty basic redirection. However, I'm getting an infinite internal loop in my apache log files with a 500 error in the browser. The apache log file has the following:
r->uri = /amit/public/activities.php.php.php.php.php.php.php.php.php
redirected from r->uri = /amit/public/activities.php.php.php.php.php.php.php.php
redirected from r->uri = /amit/public/activities.php.php.php.php.php.php.php
redirected from r->uri = /amit/public/activities.php.php.php.php.php.php
redirected from r->uri = /amit/public/activities.php.php.php.php.php
redirected from r->uri = /amit/public/activities.php.php.php.php
redirected from r->uri = /amit/public/activities.php.php.php
redirected from r->uri = /amit/public/activities.php.php
redirected from r->uri = /amit/public/activities.php
redirected from r->uri = /amit/activities.php
redirected from r->uri = /activities.php

That's when I enter the page with the extension. Makes no difference when I try to access the page without the extension. The page exists and I've double checked everything, but it seems to me that the main issue is the RewriteCond.
Any help is appreciated.

A: You don't need 4 conditions and need to have them ANDed together:
RewriteEngine on
RewriteBase /amit/public/

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond ${REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/?$ $1.php [L]

A: Thanks to @anubhava. I've just realized that my code uses $ for all the server variables. It should be %. A silly typo had hacked my brain for close to 24 hours... So the 'ultimate' code with the suggestions made by @anubhava would be:
Options +FollowSymlinks
RewriteEngine on

RewriteBase /amit/public/

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*[^/])/?$ $1.php [NC,L]

Works like a charm.


Q: How does Facebook do it? Checking the file type?
Possible Duplicate:
How to check file types of uploaded files in PHP?

Creating a text file and rename it to anything.jpg and try uploading it on facebook, facebook detects that the file is not an image and says Please select an image file or something like that. How do they do it?
I tested it out on my localhost by creating a dummy html form along with a <input type="file"... element and uploaded an image file created by renaming a text file to something.jpg and  the file type in $_FILES['control_name']['type'] showed image/jpeg... How do I block users from uploading such 'fake' images. I think restriction using $_FILES['control_name']['type'] is not a solution, right?

A: When you process image on server, use image manipulation library (getimagesize for example) to detect it's width and height. When this fails, reject the image. You will probably do it anyway to generate thumbnail, so it is like one extra if.

A: There are many ways of checking the actual files. How Facebook does it, only the ones who created it know i think :).
Most likely they will look at the first bytes in the file. All files have certain bytes describing what they truely are. For this however you need loads of time/money creating a database or such against which you can validate the uploads.
More common solutions are;
FORM attribute
In a lot of browsers, of course excluding Internet Explorer, you can set an accept attribute which checks on extensions client side. More info here: File input 'accept' attribute - is it useful?
Extension
This is not realy secure, for a script can be saved with an image extension
Read file MIME TYPE
This is a solution like you stated in your question. This however is also easy to bypass and relies on the up-to-date status of your server.
Processing the image
The most reliable (for most developer skills and available time) would be to process the image as a test.
Put it in a library like GD or Imagic. They will raise errors when an image is not realy an image. This however will require you to keep that software up to date.
In short, there is not a 100% guarantee to catch this without spending tons of hours. Even then you only get 99,9%. You should weigh your available time against the above options and choose which best suits you. As best practice i recommend a combination of all 3.
This topic is also discussed in Security: How to validate image file uploads?

A: Headers in your file won't be the same.


Q: Table with div layers I have a table inside a div 1.
Then after that div 1 added another div 2 with position:relative; top:-250; so that div 2 layer will be right on top of the table.
But now below the table there is a big space before anything on the page can resume displaying (I guess the second div 2 would have normally been without the -250 position change?)
How do I get rid of the space and clear it?
I tried this...

 ...and it didn't do anything

A: Using absolute positioning rather than relative may do the trick. I'll test this theory and edit my answer accordingly.
Edit: using position: absolute; margin-top: -250px; seems to be the solution.


Q: R: Plot multiple time series in a loop.Error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ I'm trying to plot many time series from a database with 134 columns, one ts per colum and after that, save it in a .jpg file. I'm using a loop. I notice that the ploblem could be the plot() function.
Some data with dput()
 structure(list(X9003 = c(3L, 8L, 6L, 6L, 2L, 3L, 6L, 2L, 6L,
 3L), X9004 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, 0L), X9007 = c(5L,
 8L, 6L, 11L, 4L, 6L, 7L, 9L, 4L, 5L), X9009 = c(1L, 2L, 3L, 0L,
 0L, 1L, 0L, 1L, 0L, 4L), X9010 = c(NA, NA, NA, NA, NA, NA, NA,
 NA, 3L, 15L), X9012 = c(0L, 0L, 0L, 2L, 3L, 0L, 1L, 1L, 0L, 0L
 ), X9014 = c(NA_integer_, NA_integer_, NA_integer_, NA_integer_,
 NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
 NA_integer_), X9016 = c(NA, NA, NA, NA, NA, NA, 12L, 27L, 7L,
 12L), X9019 = c(3L, 8L, 27L, 38L, 19L, 27L, 25L, 47L, 5L, 3L),
 X9020 = c(0L, 1L, 0L, 0L, 4L, 6L, 2L, 2L, 5L, 3L)), row.names = c(NA,
 10L), class = "data.frame")

And
dput(dat_nombres[1:10,1:2])
structure(list(ESTACIONES = c(9003L, 9004L, 9007L, 9009L, 9010L,
9012L, 9014L, 9016L, 9019L, 9020L), CLAVE = c(9003L, 9004L, 9007L,
9009L, 9010L, 9012L, 9014L, 9016L, 9019L, 9020L)), row.names = c(NA,
10L), class = "data.frame")

My code:
  data<- read.csv("GranizoAnualCompleto_1961-2019_columnas.csv", header =
   TRUE)
    dat_nombres<-read.csv("Nombres_Estaciones_CLICOM.csv", header=TRUE )
    Estaciones<-dat_nombres$ESTACIONES  # List
    Estacionestmp<-data[,-1]

    # Loop

    for (i in seq_along (Estacionestmp)) {
      serie<-ts(Estacionestmp[,i], start = 1961, frequency = 1)
      mypath<-file.path("C:","00 FENIX","03 Data", "Data_Est_Select_1961-
       2019", "SeriesTiempo_GranizoAnual",
                paste("Ts_Granizo4_", Estaciones[i],".jpg", sep = ""))
      jpeg(filename = mypath)

      plot(serie,
         col="darkblue",
         main="Días con granizo 1961-2019 \n Estación", Estaciones[i] ,
         cex.main=2,
         sub=paste("Estación",Estaciones[i]),
         cex.sub= 1.5,
         col.main="darkred",
         xlab= "Tiempo",
         ylab= "Días con granizo",
         cex.lab=0.8,
         col.axis= "gray34",
         col.lab= "gray25",
         type= "l"
         )
       dev.off() }

The error message are:
      Error in xy.coords(x, y, xlabel, ylabel, log) :
      'x' and 'y' lengths differ

But when I just code plot(serie) (without any details in the plot function) in the loop, there are no ploblem with the result and the files are created in the specific path that I have defined. Recently, I used this code but on a dataframe with 20 columns and it worked.
Why that details in the plot function argument are causing the error message? How can I fix the loop for create multiple time series plots? Is there any better solution to do it?
Thank you so much!
EDIT: I find that the problem are when I trying to change the main for name and subpaste every plot, the problem with the Estaciones[i]; I prove write a # before for comment it, and now it works! So, I converted it to a list
  Estaciones_list<-as.list(Estaciones)

and tried with this new list in the main for every plot but it doesn't work either.
Any suggestions?
Thanks!


Q: PHP function to extract a field value from a database I'm trying to get a value of a mysql database using a php function.
I have a database like this:
NAME     | EMAIL                | PASSWORD  | OTHER
-------------------------------------------------------
example  | example@example.com  | password  | other
-------------------------------------------------------
example2 | example2@example.com | password2 | other2

and in my PHP file I've tried to use this function:
function selectUserField($email, $field, $connection){
    $select_user = "SELECT '$field' FROM users WHERE email='$email' LIMIT 1";
    $result = mysqli_query($connection, $select_user);
    $value = mysqli_fetch_assoc($result);
    return $value[$field];
}

//And I try to echo the result of the function
$connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

echo selectUserField("example@example.com", "name", $connection);

But as result I get only the field name and not its content (for this example I get "NAME" and not "example"). How can i do to get the content of the database cell?

A: Try this
function selectUserField($email, $field, $connection){
    $select_user = "SELECT `$field` FROM users WHERE `email`='$email' LIMIT 1"; //wrap it with ` around the field or don't wrap with anything at all
    $result = mysqli_query($connection, $select_user);
    $value = mysqli_fetch_assoc($result);
    return $value[$field];
}

//And I try to echo the result of the function
$connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

echo selectUserField("example@example.com", "name", $connection);

A: No quotes around $field.
"SELECT $field FROM users WHERE email='$email' LIMIT 1";


Q: How to continue the code on the next line in VBA I would like to type the mathematical forumla in VBA code which many lines. I would like to split it into many lines. How do I do it?
For example:
U_matrix(i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + (k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

is very long. would like to split it.
Tried this:
U_matrix(i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n)
_+ (k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

But not working.. Need some guidance on this..

A: If you want to insert this formula =SUMIFS(B2:B10,A2:A10,F2) into cell G2, here is how I did it.
Range("G2")="=sumifs(B2:B10,A2:A10," & _

"F2)"

To split a line of code, add an ampersand, space and underscore.

A: (i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

From ms support
To continue a statement from one line to the next, type a space
  followed by the line-continuation character [the underscore character
  on your keyboard (_)].
You can break a line at an operator, list separator, or period.

A: In VBA (and VB.NET) the line terminator (carriage return) is used to signal the end of a statement. To break long statements into several lines, you need to

Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return).
(From How to: Break and Combine Statements in Code)

In other words: Whenever the interpreter encounters the sequence <space>_<line terminator>, it is ignored and parsing continues on the next line. Note, that even when ignored, the line continuation still acts as a token separator, so it cannot be used in the middle of a variable name, for example. You also cannot continue a comment by using a line-continuation character.
To break the statement in your question into several lines you could do the following:
U_matrix(i, j, n + 1) = _
     k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
     (k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

(Leading whitespaces are ignored.)

A: To have newline in code you use _
Example:
Dim a As Integer
a = 500 _
  + 80 _
  + 90

MsgBox a


Q: How can I implement model revisions in Laravel? This question is for my pastebin app written in PHP.
I did a bit of a research, although I wasn't able to find a solution that matches my needs. I have a table with this structure:
+-----------+------------------+------+-----+---------+----------------+
| Field     | Type             | Null | Key | Default | Extra          |
+-----------+------------------+------+-----+---------+----------------+
| id        | int(12) unsigned | NO   | PRI | NULL    | auto_increment |
| author    | varchar(50)      | YES  |     |         |                |
| authorid  | int(12) unsigned | YES  |     | NULL    |                |
| project   | varchar(50)      | YES  |     |         |                |
| timestamp | int(11) unsigned | NO   |     | NULL    |                |
| expire    | int(11) unsigned | NO   |     | NULL    |                |
| title     | varchar(25)      | YES  |     |         |                |
| data      | longtext         | NO   |     | NULL    |                |
| language  | varchar(50)      | NO   |     | php     |                |
| password  | varchar(60)      | NO   |     | NULL    |                |
| salt      | varchar(5)       | NO   |     | NULL    |                |
| private   | tinyint(1)       | NO   |     | 0       |                |
| hash      | varchar(12)      | NO   |     | NULL    |                |
| ip        | varchar(50)      | NO   |     | NULL    |                |
| urlkey    | varchar(8)       | YES  | MUL |         |                |
| hits      | int(11)          | NO   |     | 0       |                |
+-----------+------------------+------+-----+---------+----------------+

This is for a pastebin application. I basically want paste revisions so that if you open paste #1234, it shows all past revisions of that paste.
I thought of three ways:
Method 1
Have a revisions table with id and old_id or something and for each ID, I would insert all old revisions, so if my structure looks like this:
rev3: 1234
rev2: 1233
rev1: 1232

The table will contain this data:
+-------+----------+
| id    | old_id   |
+-------+----------+
| 1234  | 1233     |
| 1234  | 1232     |
| 1233  | 1232     |
+-------+----------+

The problem which I have with this is that it introduces a lot of duplicate data. And the more the revisions get, it has not only more data but I need to do N inserts for each new paste to the revisions table which is not great for a large N.
Method 2
I can add a child_id to the paste table at the top and just update that. And then, when fetching the paste, I will keep querying the db for each child_id and their child_id and so on... But the problem is, that will introduce too many DB reads each time a paste with many revisions is opened.
Method 3
Also involves a separate revisions table, but for the same scenario as method 1, it will store the data like this:
+-------+-----------------+
| id    | old_id          |
+-------+-----------------+
| 1234  | 1233,1232       |
| 1233  | 1232            |
+-------+-----------------+

And when someone opens paste 1234, I'll use an IN clause to fetch all child paste data there.
Which is the best approach? Or is there a better approach? I am using Laravel 4 framework that has Eloquent ORM.
EDIT: Can I do method 1 with a oneToMany relationship? I understand that I can use Eager Loading to fetch all the revisions, but how can I insert them without having to do a dirty hack?
EDIT: I figured out how to handle the above. I'll add an answer to close this question.

A: If you are on Laravel 4, give Revisionable a try. This might suite your needs

A: So here is what I am doing:
Say this is the revision flow:
1232 -> 1233 -> 1234
1232 -> 1235

So here is what my revision table will look like:
+----+--------+--------+
| id | new_id | old_id |
+----+--------+--------+
| 1  | 1233   | 1232   |
| 2  | 1234   | 1233   |
| 3  | 1234   | 1232   |
| 4  | 1235   | 1232   |
+----+--------+--------+

IDs 2 and 3 show that when I open 1234, it should show both 1233 and 1232 as revisions on the list.
Now the implementation bit: I will have the Paste model have a one to many relationship with the Revision model.

*

*When I create a new revision for an existing paste, I will run a batch insert to add not only the current new_id and old_id pair, but pair the current new_id with all revisions that were associated with old_id.

*When I open a paste - which I will do by querying new_id, I will essentially get all associated rows in the revisions table (using a function in the Paste model that defines hasMany('Revision', 'new_id')) and will display to the user.

I am also thinking about displaying the author of each revision in the "Revision history" section on the "view paste" page, so I think I'll also add an author column to the revision table so that I don't need to go back and query the main paste table to get the author.
So that's about it!

A: There are some great packages to help you keeping model revisions:

*

*If you only want to keep the models revisions you can use:

Revisionable

*

*If you also want to log any other actions, whenever you want, with custom data, you can use:

Laravel Activity Logger
Honorable mentions:

*

*Activity Log. It also has a lot of options.


Q: Why Python.h of python 3.2 must be included as first together with Qt4 I have a qt application and I want to implement python interpreter into it so that I can extend it with python scripts. While this works fine for regular C++ application, including Python.h even for most simple, empty Qt4 project always result in:
g++ -c -m64 -pipe -O2 -Wall -W -D_REENTRANT -DQT_WEBKIT -DQT_NO_DEBUG -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++-64 -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4 -I/usr/include/python3.2mu -I. -o main.o main.cpp
In file included from /usr/include/python3.2mu/Python.h:8:0,
                 from main.cpp:16:
/usr/include/python3.2mu/pyconfig.h:1182:0: warning: "_POSIX_C_SOURCE" redefined [enabled by default]
/usr/include/features.h:164:0: note: this is the location of the previous definition
/usr/include/python3.2mu/pyconfig.h:1204:0: warning: "_XOPEN_SOURCE" redefined [enabled by default]
/usr/include/features.h:166:0: note: this is the location of the previous definition
In file included from /usr/include/python3.2mu/Python.h:67:0,
                 from main.cpp:16:
/usr/include/python3.2mu/object.h:402:23: error: expected unqualified-id before ‘;’ token
make: *** [main.o] Error 1

I only implemented this in my .pro file:
INCLUDEPATH += "/usr/include/python3.2"
now anytime when I do
#include <Python.h>

in any .h file it makes it unbuildable. Why is that?
Note: This all works perfectly with python 2.7, just python 3x doesn't work
EDIT: I figured out, that when I include Python.h as first file, before Qt includes, it works, is this a bug in python? Are they missing some safe guards?

A: The documentation of the Python C-API states:

Note Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included.

It is very likely that some of the Qt headers include standard headers (as evident from the error you get, it does include /usr/include/features.h, or example), therefore #include <Python.h> should be placed before the Qt headers. In fact, it should generally be placed before any other include-statement.
Note that this is the case with Python 2.7, too. If a different include order works for you with Python 2.7, then you are simply lucky.


Q: Best SCM practices for live databases I've been building out an SCM environment (that has to be PCI compliant, but that's tangential to this issue).
I've got to the point where I want to automate database updates, but I'm not 100% sure that's the best way forward.
Say I want to add a field to a DB table. Easy enough to add it to the dev environment, but what about rolling out to the live environment? I took a look at MySQL::Diff but the thought of spending time completely automating this seems like overkill for me.
I want to have a rollback option, and want to avoid the overkill of complete DB duplication. All the tutorials I've found on SCM appear to either not cover this, or say it can be very messy. Is there a best practice for this? Or should I just use MySQL diff to identify changes and backup individual tables before manually tweaking at rollout?

A: We store an SQL script of the changes that are needed in git, with the branch that contains the changes.
This SQL script can be applied repeatedly to "fresh" copies of production data, verifying that it will work as expected.
It is our strong opinion that a focused DBA or Release Engineer should apply the changes, AFTER making appropriate backups and restoration measures.
--
Navicat MySQL is also an amazing tool for helping with that.  Their schema diff tool is great for verifying changes, and even applying them.


Q: How to remove previous text from a calculation? I have recently started learning Kivy and made a calculator app but I can't figure out how to remove the previous text from a calculation when a button is pressed for the next calculation and the text only gets removed when clear is used.
Here is the code https://github.com/Rakshan22/Calcy2 . So does anyone here know the answer to this question? Thanks for the assistance!

A: You should identify when the text is the final answer and reset the text before adding new one.
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.widget import Widget

Window.size = (350, 450)

class MainWidget(Widget):
    def __init__(self):
        self.textIsResult = false

    def clear(self):
        self.ids.input.text=""

    def back(self):
        expression = self.ids.input.text
        expression = expression[:1]
        self.ids.input.text = expression

    def pressed(self, button):
        expression = self.ids.input.text

        if self.textIsResult:
            self.ids.input.text = f"{button}"

        if "Fault" in expression:
            expression = ""
            self.textIsResult = false

        if expression == "0":
            self.ids.input.text = ""
            self.ids.input.text = f"{button}"

        else:
            self.ids.input.text = f"{expression}{button}"

    def answer(self):
        expression = self.ids.input.text
        try:
            self.ids.input.text = str(eval(expression))
            self.textIsResult = true

        except:
            self.ids.input.text = "Fault"

class TheLabApp(App):
    pass

TheLabApp().run()


Q: How to make Android TestRunner wait until activity finishes I am closing an Activity at the end of a testcase, so that it is null at the beginning of the next testcase:
public void test1() throws Exception {

    //activity is calling the RegisterActivity in onCreate
    activity = getActivity();

    // register next activity that need to be monitored.
    RegisterActivity nextActivity = (RegisterActivity) getInstrumentation()
        .waitForMonitorWithTimeout(activityMonitor, 5);
    // next activity is opened and captured.
    assertNotNull(nextActivity);
    if (nextActivity != null) {
        nextActivity.finish();
    }
}

public void test2() throws Exception {
    //nextActivity.finish() from the previous test has not yet finished

    //body of test2
    //...
    //...
}

If I set a Thread sleep in test1 then problem is solved:
    if (nextActivity != null) {
        nextActivity.finish();
        Thread.sleep(1500);
    }

Is there a better way to to this? Is there a method that blocks the TestRunner until nextActivity is finished?

A: Try creating a new thread for the nextActivity to run in. After calling the thread.start() method, call thread.join() where you want the TestRunner blocked.


Q: Call DLL C++ functions form C# without block the form controls I have an interesting study case for you :)
I have a problema with a wrapper integration. I made a Dll in write in C++. CLR Windows. This Dll is called form a C# application (for a the), till here all rigth.
The C# aplications is form a thrid part and I Cannot modify this source code.
When I call some C++ function since a button for example. The applications si bloqued an I can't doing any more until the C++ function return.
I need that when I wating for a C++ function the different the formulary controlls has enabled again so on, I need some additional process.
I try to do it with async methods and treads but I can't figure out the way to deploy it.
C++ function
__declspec(dllexport) HANDLE openport(char *ComPort, int BR);
C# function:
[DllImport("mydll.dll")]
        public static extern IntPtr openport(string ComPort, int BR);
Thanks in advance for your help.
Regards.

A: Your code needs to run in a new thread. Look into the System.Threading namespace for instructions and examples of how to create a new thread. Essentially, you create the thread
Here is an example from one of my old test programs.
Thread thdOneOfTwo = new Thread(new ParameterizedThreadStart(TextLogsWorkout.DoThreadTask));

In the above example, TextLogsWorkout.DoThreadTask is a static method on class TextLogsWorkout, which happens also to contain the above statement.
You have the option of giving each thread a name, and of using a WaitHandle  that it can signal when it has completed its assignment. Both are optional, but you must execute the Start method on the instance.
Be aware that you are entering the world of multi-threaded programming, where many hazards await the unwary. If you aren't already, I suggest you read up on mutexes, wait handles, and the intrinsic lock () block.
Of the three, lock() is the simplest way that a single application can synchronize access to a property. Of the other two, WaitHandles and Mutexes are about equal in complexity. However, while a WaitHandle can synchronize activities within a process, a Mutex is a filesystem object, and, as such, can synchronize activities between multiple processes.
In that regard, be aware that if a mutex has a name, as it must if it is to synchronize more than one process, that name must begin with "\?\GLOBALROOT", unless all of them run in the same session. Failure to do this bit me really hard a few years ago.


Q: How to open another activity from Interface method I write an application in Kotlin language on the platform Firebase. And after authentication, I need to open another activity from Interface.
While checking I get the error in this line:
startActivity(Intent(applicationContext, AnotherActivity::class.java))

Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

My code:
Interface:
interface OnResultSuccessListener  {
    fun onResultSuccess(isSuccess: Boolean)
}

class an Authentication:
class AuthenticationActivity : AppCompatActivity(), OnResultSuccessListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_authentication)
        ...
    }

    override fun onResultSuccess(isSuccess: Boolean) {
        if (isSuccess) {
            startActivity(Intent(applicationContext, AnotherActivity::class.java)) /*ERROR IS HERE*/
            overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            val task = GoogleSignIn.getSignedInAccountFromIntent(data)
            try {
                // Google Sign In was successful, authenticate with Firebase
                val account = task.getResult(ApiException::class.java)
                firebaseAuthWithGoogle(account)
            } catch (e: ApiException) {

            }
        }
    }
}

Helper class with CRUD methods Firebase:
class FirestoreCRUD {

    val db = Firebase.firestore
    var geoPoint: GeoPoint? = null

    private val authenticationActivity = AuthenticationActivity()

    val COLLECTION_USERS = "Users"
    ...
    ...
    //add new user to Firestore
    fun addNewUserToFirestore(firebaseUser: FirebaseUser?) {
        FirebaseInstanceId.getInstance().instanceId
            .addOnCompleteListener(OnCompleteListener { task ->
                if (task.isSuccessful) {
                    ...
                    ...
                    // Add a new document with a generated ID
                    db.collection(COLLECTION_USERS)
                        .document(firebaseUser.uid)
                        .set(userModel)
                        .addOnSuccessListener { documentReference ->
                            /*CALL onResultSuccess IN AuthenticationActivity */
                            authenticationActivity.onResultSuccess(true)

                        }
                        .addOnFailureListener { e ->
                            Log.d(LOG_TAG, "Error adding document", e)
                            authenticationActivity.onResultSuccess(false)
                        }
                }
                else authenticationActivity.onResultSuccess(false)
            })
    }
}

Call onActivityResult failed from onResultSuccess.
I will happy for any help!
Thanks a lop!

A: The only way the context of an Activity can be null is if you are passing around an instance of your Activity that you instantiated yourself, which you should never do. Would have to see more of your code to know where you are doing that.

A: So, I resolved the problem. It was easy.
How said Tenfour04:

The only way the context of an Activity can be null is if you are passing around an instance of your Activity that you instantiated yourself, which you should never do...

It is true.
Solution:

*

*should send context to FirestoreCRUD class:
FirestoreUtil(this).addNewUserToFirestore(user)

*FirestoreCRUD class receivers straight to Interface:
class FirestoreUtil(var onResultSuccessListener: OnResultSuccessListener) {}

*And call the Interface method in AuthenticationActivity class from FirestoreCRUD class:
onResultSuccessListener!!.onResultSuccess(true)
And then my activity doesn't restart and everything runs smoothly!
I hope this helps somebody.


Q: How to display ImageView below TextView in LinearLayout I'm writing a sports app and I want to place the text exactly under the picture, but I can't get it aligned.  If there is a large text somewhere, then the picture is not in the middle.  how to make sure that the text is always exactly under the picture, or the picture is always exactly under the text?
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:background="@drawable/shadow_matches_background"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="190dp">

            <LinearLayout
                android:id="@+id/title_team_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:weightSum="2">

                <TextView
                    android:id="@+id/title_team_1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="35dp"
                    android:layout_weight="1"
                    android:fontFamily="@font/roboto_medium"
                    android:text="Chelsea"
                    android:textColor="@color/black"
                    android:textSize="20sp" />

                <TextView
                    android:id="@+id/title_team_2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="25dp"
                    android:layout_weight="1"
                    android:fontFamily="@font/roboto_medium"
                    android:text="Manchester City"
                    android:textColor="@color/black"
                    android:textSize="20sp" />

            </LinearLayout>

            <RelativeLayout
                android:id="@+id/image_team_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/img_team_1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/title_team_1"
                    android:src="@drawable/image_3" />

                <ImageView
                    android:id="@+id/img_team_2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/image_5"
                    tools:ignore="DuplicateIds" />

            </RelativeLayout>

            <TextView
                android:id="@+id/date_team_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/image_team_list"
                android:layout_marginTop="5dp"
                android:fontFamily="@font/roboto"
                android:text="25 сентября 2021 года"
                android:textAlignment="center"
                android:textSize="15sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/date_team_list">

                <Button
                    android:id="@+id/btn_subscribe"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="#00000000"
                    android:text="@string/btn_subscribe"
                    android:textColor="@color/colorMatchesBtn" />

                <Button
                    android:id="@+id/btn_detail"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="#00000000"
                    android:text="@string/btn_detail"
                    android:textColor="@color/colorMatchesBtn" />

            </LinearLayout>

        </RelativeLayout>

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#00000000">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="190dp">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="180dp"
                    android:layout_marginStart="20dp"
                    android:layout_marginEnd="20dp"
                    android:layout_marginBottom="20dp">

                    <LinearLayout
                        android:id="@+id/title_team_list"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5dp"
                        tools:ignore="DuplicateIds">

                        <TextView
                            android:id="@+id/title_team_1"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="35dp"
                            android:layout_weight="1"
                            android:fontFamily="@font/roboto_medium"
                            android:text="Everton"
                            android:textColor="@color/black"
                            android:textSize="20sp"
                            tools:ignore="DuplicateIds" />

                        <TextView
                            android:id="@+id/title_team_2"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginRight="25dp"
                            android:layout_weight="1"
                            android:fontFamily="@font/roboto_medium"
                            android:text="Norvich City"
                            android:textColor="@color/black"
                            android:textSize="20sp"
                            tools:ignore="DuplicateIds" />

                    </LinearLayout>

                    <LinearLayout
                        android:id="@+id/image_team_list"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/title_team_list"
                        android:layout_marginTop="5dp"
                        tools:ignore="DuplicateIds">

                        <ImageView
                            android:id="@+id/img_team_1"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:src="@drawable/image_3"
                            tools:ignore="DuplicateIds" />

                        <ImageView
                            android:id="@+id/img_team_2"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:src="@drawable/image_5"
                            tools:ignore="DuplicateIds" />

                    </LinearLayout>

                    <TextView
                        android:id="@+id/date_team_list"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/image_team_list"
                        android:layout_marginTop="5dp"
                        android:fontFamily="@font/roboto"
                        android:text="25 сентября 2021 года"
                        android:textAlignment="center"
                        android:textSize="15sp"
                        tools:ignore="DuplicateIds" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/date_team_list">

                        <Button
                            android:id="@+id/btn_subscribe"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:background="#00000000"
                            android:text="@string/btn_subscribe"
                            android:textColor="@color/colorMatchesBtn"
                            tools:ignore="DuplicateIds" />

                        <Button
                            android:id="@+id/btn_detail"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_weight="1"
                            android:background="#00000000"
                            android:text="@string/btn_detail"
                            android:textColor="@color/colorMatchesBtn"
                            tools:ignore="DuplicateIds" />

                    </LinearLayout>

                </RelativeLayout>

            </RelativeLayout>

        </androidx.cardview.widget.CardView>

A: And take a look at ConstrainsLayout It will help you out build more complex layouts easily.Also your list of teams is completely hardcoded you should definetely switch to RecyclerView.

A: you should follow Constraint layout, for your desired output I have attached some code. I hope, it helps.
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">

<TextView
    android:id="@+id/tvTitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="@id/ivPic"
    app:layout_constraintRight_toRightOf="@id/ivPic"
    app:layout_constraintBottom_toTopOf="@id/ivPic"
    android:text="Your desired text"
    android:textColor="@color/black"
    android:textSize="15sp"
    android:singleLine="true"
    android:marqueeRepeatLimit="marquee_forever"
    />
<ImageView
    android:id="@+id/ivPic"
    android:layout_width="100dp"
    android:layout_height="100dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@id/tvTitle"
    android:src="@drawable/yourImage"
    android:scaleType="centerCrop"
    android:padding="2dp"
    />

<TextView
    android:id="@+id/tvClubName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="@id/ivPic"
    app:layout_constraintRight_toRightOf="@id/ivPic"
    app:layout_constraintTop_toBottomOf="@id/ivPic"
    android:text="Liverpool"
    android:textColor="@color/black"
    android:textSize="15sp"
    android:singleLine="true"
    android:padding="3dp"
    android:gravity="center_vertical|center"
    android:marqueeRepeatLimit="marquee_forever"
    />
</androidx.constraintlayout.widget.ConstraintLayout>


Q: xslt 2.0 format-number repeating pattern with alternate group-separator I'm trying to understand why XSLT 2.0 is repeating the following pattern when I attempt to provide an alternate grouping-separator to the format-number function like so:
 <xsl:decimal-format grouping-separator="-" name="hyphenFormatting"/>

 <xsl:template match="/">
     <xsl:value-of select="format-number(642120, '####-##', 'hyphenFormatting')"/>
 </xsl:template>

Output: 64-21-20 when I expected the output to be: 6421-20
Is there a way I can bypass this pattern repetition so it evaluates my mask literally?

A: Are you using Saxon? With Saxon 9.8 I get the same behaviour as you do.
The specification was rephrased between 2.0 and 3.0. In 2.0 it says:

In addition, if these integer-part-grouping-positions are at regular
intervals (that is, if they form a sequence N, 2N, 3N, ... for some
integer value N, including the case where there is only one number in
the list), then the sequence contains all integer multiples of N as
far as necessary to accommodate the largest possible number.

While 3.0 says the following (the third rule is new):

The grouping is defined to be regular if the following conditions
apply:

*

*There is an least one grouping-separator in the integer part of the sub-picture.

*There is a positive integer G (the grouping size) such that the position of every grouping-separator in the integer part of the
sub-picture is a positive integer multiple of G.

*Every position in the integer part of the sub-picture that is a positive integer multiple of G is occupied by a grouping-separator.
If the grouping is regular, then the integer-part-grouping-positions sequence contains all integer
multiples of G as far as necessary to accommodate the largest possible
number.

So your grouping is regular under the 2.0 definition but not under the 3.0 definition. Saxon is apparently implementing the 2.0 definition. I suspect the change was intended as a bug fix, and it appears Saxon has not implemented this change.
As a workaround, you could define the picture as
#-###############################################-##

with the extra grouping separator placed so far out to the left that you will never have a number this large.
(Raised a Saxon issue here: https://saxonica.plan.io/issues/3669)


Q: Add “selected” Class to the Menu Item - MVC I fallow this tutorial (link) how to add "selected" class to the menu in MVC, in other words this tutorial shows how to create navigator menu in MVC, when you click on nav button it stays selected.
But when I write this code in begining
using System.Web;
using System.Web.Mvc;

namespace AdminRole.HtmlHelpers
{
   ...
}

My Visual Studio 2012 shows error in all of this area

and it says Identifier expected?
What identifier? Thanks for help

A: Ok, I solve it...
This code:
using System.Web;
using System.Web.Mvc;

namespace AdminRole.HtmlHelpers

Rewrite to:
using System.Web;
using System.Web.Mvc;

namespace AdminRole.HtmlHelpers

Now it works :)


Q: Cin inside switch statement, makes my program stuck In my program it should be an option to ask a user for input, and then save input string into the file. My problem is, - when I put cin in any of it forms, inside Switch, program will stuck circling indefinitely, right after i press enter after finish typing new text. What could cause the problem?

#include <iostream>
#include <fstream>
#include <iterator>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <algorithm>
#include <chrono>
#include <random>
#include <vector>

using namespace std;

void changePlainText()
{
    ofstream nFile("plaintext.txt");
    string newText;
    cout << "Enter new plain text" << endl;
    getline(cin, newText);
    nFile << newText;
    nFile.close();
}

int main()
{
    int uInput = 0;
    do
    {
        printf("2.Change content of the plain text file: \n");
        cin >> uInput;
        switch (uInput)
        {
        case 1:
             break;
        case 2:
            changePlainText();
            break;
        }
    } while (uInput != 5);
    cout << "Closing program" << endl;
    system("pause");
}

After I type something in console and press enter, the program enters never ending circle. It still stuck even if I just write simple cin >> i, in switch case.

A: Take a look at this question. I debugged your code and I experienced that exact behavior. The accepted answer explains quite well what's happening and also provides a solution.
I tried with boost, I changed
cin >> uInput;

to
string inputString; // so you know what inputString is

getline(cin, inputString);
uInput = boost::lexical_cast<int>(line);

and it's working fine now.


Q: Android equivalent of iOS's beginIgnoringInteractionEvents This SO answer suggest to iterate through the childviews and disable them. It doesn't smell right to me (performance wise)
What's the best approach to disable ALL touch events in the application prevent the user from interacting with the application (during an animation, let's say)?

A: Check out how we solved this by overriding the dispatch methods in Activity.


Q: Calling full trust assembly from a low trust assembly with AllowPartiallyTrustedCallers 'proxy' assembly If you have a third party assembly that requires full trust for say a logging operation (This assembly does not have AllowPartiallyTrustedCallers).
You use this assembly through a custom assembly with AllowPartiallyTrustedCallers then deploy it to the GAC.
How can you use your custom assembly from low trust code when it's dependency (third party assembly) issues security demands?
Note: Context is sharepoint.

A: Best guess : missing assert for security demands. Check out MSDN tutorial to get started. And SecurityPermission class for Assert method.


Q: Not sure how to pass data from frontend app to backend I need to send data from the 'change' variable below to the backend flask route. Here's how my react app is-
import React, {useState, useEffect} from "react";
import ReactQuill from "react-quill";
import { Card, CardBody, Form, FormInput } from "shards-react";

import "react-quill/dist/quill.snow.css";
import "../../assets/quill.css";

function Editor(props) {
  const[change, setChange] = useState('')
  const handleChange = (value) => {
  setChange(value)
}
  console.log(change)
  console.log(JSON.stringify(change));

  const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(change)
    };

  useEffect( () => {
    fetch('http://127.0.0.1:5000/lang', requestOptions)
    .then(response => response.json())
    .then(data => setChange(change))
    console.log('datas')
  }, [] )

  return <Card small className="mb-3">
    <CardBody>
      <Form className="add-new-post" action="http://127.0.0.1:5000/lang" method="POST">
        <FormInput size="lg" className="mb-3" placeholder="Your Post Title" />
        <ReactQuill className="add-new-post__editor mb-1" value={change} onChange={handleChange} />
        <button class="ml-auto btn btn-accent btn-sm" type="submit"><i class="material-icons">file_copy</i> Publish</button>
      </Form>
    </CardBody>
  </Card>;
}

export default Editor;

I have tried to use useEffect above. Upon attempting to post data to flask, Following is the error it returns:
127.0.0.1 - - [06/Jun/2021 04:36:03] "POST /lang HTTP/1.1" 500 - TypeError: 'NoneType' object is not subscriptable
My backend server in flask looks like the following-
from flask import Flask, render_template, jsonify, request #import objects from the Flask model
from flask_cors import CORS
from werkzeug.utils import secure_filename
import requests
import logging
import json
import pymongo
from pymongo import MongoClient
from flask_sqlalchemy import SQLAlchemy
from localStoragePy import localStoragePy
import config

app = Flask(__name__) #define app using Flask

languages = [{'title' : 'Blog Overview'}, {'subtitle' : 'Dashboard'}, {'file' : 'file'}, {'sm' : '4'}, { 'title2': 'Add New Post'}, {'subtitle2': 'Blog Posts'}]

@app.route('/', methods=['GET'])
def test():
    return jsonify({'message' : 'It works!'})

@app.route('/lang', methods=['POST'])
def addOne():
    language = {'title' : request.json['title'], 'subtitle' : request.json['subtitle'], 'sm' : request.json['sm'], 'title2': request.json['title2'],'subtitle2': request.json['subtitle2'] }
    languages.append(language)
    return jsonify(languages)

@app.route('/lang', methods=['GET'])
def returnAll():
    return jsonify(languages)

if __name__ == '__main__':
    app.run(debug=True, port=8080) #run app on port 8080 in debug mode

A: Change request.json to request.form in the AddOne function.


Q: Find distinct values group by another field mongodb I have collection with documents like this :
{
    "_id" : ObjectId("5c0685fd6afbd73b80f45338"),
    "page_id" : "1234",
    "category_list" : [
        "football",
        "sport"
    ],
    "time_broadcast" : "09:13"
}

{
    "_id" : ObjectId("5c0685fd6afbd7355f45338"),
    "page_id" : "1234",
    "category_list" : [
        "sport",
        "handball"
    ],
    "time_broadcast" : "09:13"
}

{
    "_id" : ObjectId("5c0694ec6afbd74af41ea4af"),
    "page_id" : "123456",
    "category_list" : [
        "news",
        "updates"
     ],
     "time_broadcast" : "09:13"
}

....
now = datetime.datetime.now().time().strftime("%H:%M")

What i want is : when "time_broadcast" is equal to "now",i get list of distinct "category_list" of each "page_id".
Here is how the output should look like :
{
   {
     "page_id" : "1234",
     "category_list" : ["football", "sport", "handball"]
   },

   {
     "page_id" : "123456",
     "category_list" : ["news", "updates"]
   }
}

I have tried like this :
category_list = db.users.find({'time_broadcast': now}).distinct("category_list")

but this gives me as output list of distinct values but
of all "page_id" :
 ["football", "sport", "handball","news", "updates"]

not category_list by page_id .
Any help please ?
Thanks

A: you need to write an aggregate pipeline

*

*$match - filter the documents by criteria

*$group - group the documents by key field

*$addToSet - aggregate the unique elements

*$project - project in the required format

*$reduce - reduce the array of array to array by $concatArrays
aggregate query
db.tt.aggregate([
    {$match : {"time_broadcast" : "09:13"}},
    {$group : {"_id" : "$page_id", "category_list" : {$addToSet : "$category_list"}}},
    {$project : {"_id" : 0, "page_id" : "$_id", "category_list" : {$reduce : {input : "$category_list", initialValue : [], in: { $concatArrays : ["$$value", "$$this"] }}}}}
]).pretty()

result
{ "page_id" : "123456", "category_list" : [ "news", "updates" ] }
{
        "page_id" : "1234",
        "category_list" : [
                "sport",
                "handball",
                "football",
                "sport"
        ]
}

you can add $sort by page_id pipeline if required


Q: uWSGI: disable logs for given urls I need to disable uWSGI logs just for one url. I played around uWSGI config but didn't find anything that can helps(maybe route directive, but it didn't give me required result).
Do you have any ideas about it?

A: Use its internal routing framework with the donotlog action:
route = ^foo donotlog:

But ensure your instance has internal routing support compiled in (if not you should see a warning in the startup logs).


Q: How to parse a CSV with multiple key-value pairs? I have a CSV in this format:
"Account Name","Full Name","Customer System Name","Sales Rep"
"0x7a69","Mike Smith","0x7a69","Tim Greaves"
"0x7a69","John Taylor","0x7a69","Brian Anthony"
"Apple","Steve Jobs","apple","Anthony Michael"
"Apple","Steve Jobs","apple","Brian Anthony"
"Apple","Tim Cook","apple","Tim Greaves"
...
I would like to parse this CSV (using Java) so that it becomes:
"Account Name","Full Name","Customer System Name","Sales Rep"
"0x7a69","Mike Smith, John Taylor","0x7a69","Tim Greaves, Brian Anthony"
"Apple","Steve Jobs, Tim Cook","apple","Anthony Michael, Brian Anthony, Tim Greaves"
Essentially I just want to condense the CSV so that there is one entry per account/company name.
Here is what I have so far:
String csvFile = "something.csv";
String line = "";
String cvsSplitBy = ",";

List<String> accountList = new ArrayList<String>();
List<String> nameList = new ArrayList<String>();
List<String> systemNameList = new ArrayList<String>();
List<String> salesList = new ArrayList<String>();

try (BufferedReader br = new BufferedReader(new FileReader(csvFile)))
    {

        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] csv = line.split(cvsSplitBy);

            accountList.add(csv[0]);
            nameList.add(csv[1]);
            systemNameList.add(csv[2]);
            salesList.add(csv[3]);

        }

So I was thinking of adding them all to their own lists, then looping through all of the lists and comparing the values, but I can't wrap my head around how that would work. Any tips or words of advice are much appreciated. Thanks!

A: By analyzing your requirements you can get a better idea of the data structures to use. Since you need to map keys (account/company) to values (name/rep) I would start with a HashMap. Since you want to condense the values to remove duplicates you'll probably want to use a Set.
I would have a Map<Key, Data> with
public class Key {
    private String account;
    private String companyName;

    //Getters/Setters/equals/hashcode
}

public class Data {
    private Key key;
    private Set<String> names = new HashSet<>();
    private Set<String> reps = new Hashset<>();

    public void addName(String name) {
        names.add(name);
    }

    public void addRep(String rep) {
        reps.add(rep);
    }

    //Additional getters/setters/equals/hashcode
}

Once you have your data structures in place, you can do the following to populate the data from your CSV and output it to its own CSV (in pseudocode)
    Loop each line in CSV
      Build Key from account/company
      Try to get data from Map
      If Data not found
        Create new data with Key and put key -> data mapping in map
      add name and rep to data

    Loop values in map
      Output to CSV

A: Well, I probably would create a class, let's say "Account", with the attributes "accountName", "fullName", "customerSystemName", "salesRep". Then I would define an empty ArrayList of type Account and then loop over the read lines. And for every read line I just would create a new object of this class, set the corresponding attributes and add the object to the list. But before creating the object I would iterate overe the already existing objects in the list to see whether there is one which already has this company name - and if this is the case, then, instead of creating the new object, just reset the salesRep attribute of the old one by adding the new value, separated by comma.
I hope this helps :)


Q: Giving a different object name for the content of the returned list of purrr::map2() I'm trying to conduct a certain a calculation using purrr::map2() taking two different arguments.
purrr::map2(
  .x = c(1, 3),
  .y = c(10, 20),
  function(.x, .y)rnorm(1, .x, .y)
)

purrr::map2() returns a list, but I want to assign a distinct object name to each content within the list. For example, I want to name the first list [[1]] [1] -5.962716 as model1 and [[2]] [1] -29.58825 as model2. In other words, I'd like to automate the object naming like model* <- purrr::map2[[*]]. Would anybody tell me a better way?
> purrr::map2(
+ .x = c(1, 3),
+ .y = c(10, 20),
+ function(.x, .y)rnorm(1, .x, .y)
+ )
[[1]]
[1] -5.962716
[[2]]
[1] -29.58825

This question is similar to this, though note that I need the results of the calculation in separate objects for my purpose.

A: You could assign the name to the result using setNames :
result <- purrr::map2(
  .x = c(1, 3),
  .y = c(10, 20),
  function(.x, .y)rnorm(1, .x, .y)
) %>%
  setNames(paste0('model', seq_along(.)))

Now you can access each individual objects like :
result$model1
#[1] 6.032297

If you want them as separate objects and not a part of a list you can use list2env.
list2env(result, .GlobalEnv)


Q: PRTweenOperation timingFunction member not found in Swift I'm trying to use the PRTween library in a Swift iPhone app.
Original example code from GitHub:
PRTweenPeriod *period = [PRTweenPeriod periodWithStartValue:100 endValue:200 duration:3];
PRTweenOperation *operation = [[PRTweenOperation new] autorelease];
operation.period = period;
operation.target = self;
operation.timingFunction = &PRTweenTimingFunctionLinear;

My Swift port:
var period = PRTweenPeriod.periodWithStartValue(100, endValue: 200, duration: 3) as PRTweenPeriod
var operation = PRTweenOperation()
operation.period = period
operation.target = self
operation.timingFunction = PRTweenTimingFunctionLinear

Xcode is giving me this error:
'PRTweenOperation' does not have a member named 'timingFunction'

I'm not sure how to fix this. I can clearly see the member definition in PRTween.h. I'm thinking it might be related to the fact that this is where the definition of PRTweenTimingFunction takes me.
typedef CGFloat(*PRTweenTimingFunction)(CGFloat, CGFloat, CGFloat, CGFloat);

Has anyone else seen an error like this? Any suggestions for fixes?
P.S. I'm not really sure what to call that typedef. Is it a function pointer?
EDIT
As a workaround, I used this code that does not ask for a timing function:
let period = PRTweenPeriod.periodWithStartValue(100, endValue: 200, duration: 2) as PRTweenPeriod

PRTween.sharedInstance().addTweenPeriod(period,
    updateBlock: { (p: PRTweenPeriod!) in
        NSLog("\(Int(p.tweenedValue))"
    },
    completionBlock: { NSLog("Completed tween") })

A: Yes, that's a function pointer. This is a current limitation of C interoperability:

Note that C function pointers are not imported in Swift.

You might consider filing a bug if you'd like this to work. (Note that block-based APIs are fine and work with Swift closures.)


Q: Swagger-codegen-js not finding not translating the response schema defined on the api endpoint Summary
I am using swagger-codegen-js to generate typescript files according to the swagger.json defined by an external api.
packages used
"swagger-js-codegen": "^1.12.0",
Alleged Problem
The return type on the method listMovies on the generated TS file is simply Promise<Request.Response> and not Promise<Array<Movie>>, i did expect it to be array of movies as the response clearly state the schema and thought/assumed that would be translated.
Given a json along the lines of the following, the
 "/movies": {
    "get": {
      "description": "Lists movies",
      "operationId": "listMovies",
      "responses": {
        "200": {
          "description": "Movie",
          "schema": {
            "type": "array",
            "items": {
              "$ref": "#/definitions/Movie"
            }
          }
        },
        "default": {
          "$ref": "#/responses/genericError"
        }
      }
    },
 "definitions": {
  "Movie": {
    "description": "something",
    "type": "object",
    "properties": {
      "archivedAt": {
        "description": "When the movie was archived",
        "type": "string",
        "format": "nullable-date-time",
        "x-go-name": "ArchivedAt",
        "readOnly": true
      }
  }
}

Generated TS Method
 /**
 * Lists movies
 * @method
 * @name Api#listMovies
 */
listMovies(parameters: {
    $queryParameters ? : any,
    $domain ? : string
}): Promise <request.Response> {
    const domain = parameters.$domain ? parameters.$domain : this.domain;
    let path = '/movies';
    .
    .
    .
        this.request('GET', domain + path, body, headers, queryParameters, form, reject, resolve);
    });
}

The script i use to generate the above ts file is straight from the github sample
const generateTSFilesUsingSwaggerJsCodegen = function () {
var fs = require('fs');
var CodeGen = require('swagger-js-codegen').CodeGen;

var file = 'build/sample.json';
var swagger = JSON.parse(fs.readFileSync(file, 'UTF-8'));
var tsSourceCode = CodeGen.getTypescriptCode({ className: 'Api', swagger: swagger, imports: ['../../typings/tsd.d.ts'] });
fs.writeFileSync('src/api/api.ts', tsSourceCode)

}
Am i missing something on the wire up/options passed or is this the expected generated file given the json file and that i need to write custom script to get what I want?

A: It is only possible to edit the codegen to change this.
But you can just use the body of the return value
<restMethod>(<paramters>).then(respose: <request.Response>) {
  let responseObject: Array<ListMovies> = response.body as Array<ListMovies>;
  ...
}

If you want to adapt the codegen, pull it from git and change the following files:
lib/codegen.js:
var getViewForSwagger2 = function(opts, type){
var swagger = opts.swagger;
var methods = [];
var authorizedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'COPY', 'HEAD', 'OPTIONS', 'LINK', 'UNLIK', 'PURGE', 'LOCK', 'UNLOCK', 'PROPFIND'];
var data = {
    isNode: type === 'node' || type === 'react',
    isES6: opts.isES6 || type === 'react',
    description: swagger.info.description,
    isSecure: swagger.securityDefinitions !== undefined,
    moduleName: opts.moduleName,
    className: opts.className,
    imports: opts.imports,
    domain: (swagger.schemes && swagger.schemes.length > 0 && swagger.host && swagger.basePath) ? swagger.schemes[0] + '://' + swagger.host + swagger.basePath.replace(/\/+$/g,'') : '',
    methods: [],
    definitions: []
};

_.forEach(swagger.definitions, function(definition, name){
    data.definitions.push({
        name: name,
        description: definition.description,
        tsType: ts.convertType(definition, swagger)
    });
});

the last _.forEach is moved from the bottom of the method to here.
var method = {
            path: path,
            className: opts.className,
            methodName: methodName,
            method: M,
            isGET: M === 'GET',
            isPOST: M === 'POST',
            summary: op.description || op.summary,
            externalDocs: op.externalDocs,
            isSecure: swagger.security !== undefined || op.security !== undefined,
                          isSecureToken: secureTypes.indexOf('oauth2') !== -1,
                          isSecureApiKey: secureTypes.indexOf('apiKey') !== -1,
                          isSecureBasic: secureTypes.indexOf('basic') !== -1,
            parameters: [],
            responseSchema: {},
            headers: []
        };
        if (op.responses && op.responses["200"]) {
            method.responseSchema = ts.convertType(op.responses["200"], swagger);
        } else {
            method.responseSchema = {
                "tsType": "any"
            }
        }

this is starting at line 102. add responseSchema to method and append the if / else
templates/typescript-class.mustache (line 68)
resolve(response.body);

templates/typescript-method.mustache (line 69)
}): Promise<{{#responseSchema.isRef}}{{responseSchema.target}}{{/responseSchema.isRef}}{{^responseSchema.isRef}}{{responseSchema.tsType}}{{/responseSchema.isRef}}{{#responseSchema.isArray}}<{{responseSchema.elementType.target}}>{{/responseSchema.isArray}}> {

That only works for simple types, Object types and arrays of simple / object types. I did not implement the enum types.

A: That seems like the expected behaviour.
The TypeScript Mustache template outputs a fixed value:
    ...
}): Promise<request.Response> {
    ...


Q: Dynamically resize UICollectionViewCell in non-scrolling UICollectionView I have a small, single row horizontal layout UICollectionView at the top of the screen. It can contain up to a maximum of 6 items. The problem is that I want all 6 items visible without scrolling (this collection view is also going to be used in a Today extension which doesn't allow scrolling). What I want to do is reduce the cell-size and inter-item spacing a little bit to allow all 6 cells to fit.
Basically I'm trying to avoid this:

I've been playing with this for a while but I'm not sure how to approach it. I created a method that's fired every time an item is added or removed from the collection view, just before [self.collectionview reloadData] is called.
-(void)setupCollectionViewLayout{

     UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.buttonBarCollectionView.collectionViewLayout;

        //Figure out if cells are wider than screen
    CGFloat screenwidth = self.view.frame.size.width;

    CGFloat sectionInsetLeft = 10;
    CGFloat sectionInsetRight = 10;
    CGFloat minItemSpacing = flowLayout.minimumInteritemSpacing;
    CGSize  itemsize = CGSizeMake(58,58);
    CGFloat itemsizeWidth = itemsize.width;
    CGFloat totalWidth = sectionInsetLeft + sectionInsetRight +
                        (itemsizeWidth * _armedRemindersArray.count) +
                        (minItemSpacing * (_armedRemindersArray.count -2));

    CGFloat reductionAmount = itemsizeWidth;
    if (totalWidth > screenwidth) {

        while (totalWidth > screenwidth) {
            totalWidth = totalWidth - 1;
             reductionAmount = reductionAmount - 1;
        }

        CGSize newCellSize = CGSizeMake(reductionAmount, reductionAmount);
        flowLayout.itemSize = newCellSize;

    }

    else flowLayout.itemSize = itemsize;

}

This is the result.

Not exactly what I was expecting. Not only did it squash everything to the left and also added a second line, but I also seem to have a cell-reuse issue. Truthfully I would just use static-cells if it was even an option, but unfortunately it seems like it's not possible.
What should I be doing? Subclassing UICollectionViewFlowLayout? Won't that basically do the same thing I'm doing here with the built-in flow layout?
EDIT:
Kujey's answer is definitely closer to what I need. I still have a cell-reuse issue though.

A: Xcode provides an object designed for your need. It's called UICollectionViewFlowLayout and all you need to do is subclass it and place your cells the way you want. The function prepareForLayout is call every time the collection view needs to update the layout.
The piece of code you need is below :
#import "CustomLayout.h"

#define MainCell @"MainCell"

@interface CustomLayout ()

@property (nonatomic, strong) NSMutableDictionary *layoutInfo;

@end

@implementation CustomLayout

-(NSMutableDictionary *) layoutInfo
{
    if (!_layoutInfo) {
        _layoutInfo = [NSMutableDictionary dictionary];
    }

    return _layoutInfo;
}

-(void) prepareLayout
{
    NSMutableDictionary *cellLayoutInfo = [NSMutableDictionary dictionary];

    NSIndexPath *indexPath;

    CGFloat itemWidth;
    CGFloat itemSpacing;

    CGFloat widthWithoutSpacing = [self collectionViewContentSize].width / ([self.collectionView numberOfItemsInSection:0]);

    if (widthWithoutSpacing > [self collectionViewContentSize].height) {
        itemWidth = [self collectionViewContentSize].height;
        itemSpacing = ([self collectionViewContentSize].width - itemWidth*[self.collectionView numberOfItemsInSection:0])/
        ([self.collectionView numberOfItemsInSection:0]+1);
    }
    else {
        itemWidth = widthWithoutSpacing;
        itemSpacing = 0;
    }

    CGFloat xPosition = itemSpacing;

    for (NSInteger section = 0; section < [self.collectionView numberOfSections]; section++) {

        for (NSInteger index = 0 ; index < [self.collectionView numberOfItemsInSection:section] ; index++) {

            indexPath = [NSIndexPath indexPathForItem:index inSection:section];
            UICollectionViewLayoutAttributes *itemAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];

            CGRect currentFrame=itemAttributes.frame;

            currentFrame.origin.x = xPosition;
            currentFrame.size.width = itemWidth;
            currentFrame.size.height = itemWidth;

            itemAttributes.frame=currentFrame;
            cellLayoutInfo[indexPath] = itemAttributes;

            xPosition += itemWidth + itemSpacing;
        }
    }

    self.layoutInfo[MainCell] = cellLayoutInfo;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *allAttributes = [NSMutableArray arrayWithCapacity:self.layoutInfo.count];

    [self.layoutInfo enumerateKeysAndObjectsUsingBlock:^(NSString *elementIdentifier, NSDictionary *elementsInfo, BOOL *stop) {
        [elementsInfo enumerateKeysAndObjectsUsingBlock:^(NSIndexPath *indexPath, UICollectionViewLayoutAttributes *attributes, BOOL *innerStop) {
            if (CGRectIntersectsRect(rect, attributes.frame)) {
                [allAttributes addObject:attributes];
            }
        }];
    }];

    return allAttributes;
}

-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return self.layoutInfo[MainCell][indexPath];
}

-(CGSize) collectionViewContentSize
{
    return self.collectionView.frame.size;
}

@end

You can also change the y origin of your cells if you need to center them vertically.

A: try with this code. I get the width and use _armedRemindersArray (i guess you use this array for the items).
-(void)setupCollectionViewLayout{
         UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.buttonBarCollectionView.collectionViewLayout;

         //Figure out if cells are wider than screen
         CGFloat screenwidth = self.view.frame.size.width;
         CGFloat width = screenwidth - ((sectionInsetLeft + sectionInsetRight) *_armedRemindersArray.count  + minItemSpacing * (_armedRemindersArray.count -2));
         CGSize  itemsize = CGSizeMake(width,width);
         flowLayout.itemSize = itemsize;
}

A: I don't know why you're setting the itemsize first, and then reducing it. I think you should do it the other way around:
-(void)setupCollectionViewLayout{

     UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.buttonBarCollectionView.collectionViewLayout;

    CGFloat sectionInsetLeft = 10;
    CGFloat sectionInsetRight = 10;
    CGFloat minItemSpacing = flowLayout.minimumInteritemSpacing;

    // Find the appropriate item width (<= 58)
    CGFloat screenwidth = self.view.frame.size.width;
    CGFloat itemsizeWidth = (screenwidth - sectionInsetLeft - sectionInsetRight - (minItemSpacing * (_armedRemindersArray.count -2))) / _armedRemindersArray.count
    itemsizeWidth = itemsizeWidth > 58 ? 58 : itemsizeWidth;

    flowLayout.itemSize = CGSizeMake(itemsizeWidth, itemsizeWidth);
}

Does this work? If not, could you please include more of your code?


Q: Openshift new-app from image creates service with incorrect ports I am using openshift oc new-app to create a app from a image.
However oc new-app is creating the associated openshift service incorrectly with only one tcp port, not the two ports than the application uses.
Is there any simple way to force openshift new-app to correctly create the service with the two correct ports when building from a image rather than incorrectly with only one port ?
Alternatively is there a command line way to add the extra port to the service created that can be scripted (I know about oc edit) ..
(Disclaimer.. I am new to openshift and have lots to learn)


Q: How can I get rid of the parentheses in the dataframe column?(Python) I have dataframe like this

I want to remove the parentheses in the Movie_Name column.
Here is a few example
df_Movie["Movie Name"].str.findall(r'\([^()]*\)').sum()

['(500)',
 '(Eksiteu)',
 '(Mumbai Diaries)',
 '(Geukhanjikeob)',
 '(Erkekler Ne İster?)',
 '(The Witch)',
 '(Ji Hun)']

And then ı tried this solution.
import re
df_Movie["Movie Name"] = df_Movie["Movie Name"].str.replace(r'\([^()]*\)', ' ', regex = True)

Here is the output of the solution for one example.
df_Movie.iloc[394, :]
Movie Name      Days of Summer
Year                      2009
IMDB                       7.7
Name: 394, dtype: object

In this case, the values between the parentheses are completely lost. I don't want that.
I want output like this : (500) Days of Summer --> 500 Days of Summer
How can ı solve this ?

A: You can remove all parentheses from a dataframe column using
df_Movie["Movie Name"] = df_Movie["Movie Name"].str.replace(r'[()]+', '', regex=True)

The [()]+ regex pattern matches one or more ( or ) chars.
See the regex demo.


Q: pyspark - how to handle unicode from hive I am trying read a hive table in pyspark
from pyspark.sql import SQLContext
from pyspark import HiveContext
hivec = HiveContext(sc) sqlc = SQLContext(sc)
t = hivec.sql("select * from database.table").collect()

data = sqlc.createDataFrame(t)
data.registerTempTable("masterTable")
sqlc.sql("select * from masterTable").show()

I get the below error

UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in
  position 8871: ordinal not in range(128)

What I have tried:
I figured out the record that was falling over, when I "select * from    " in hive for the same record, there is no error reported nor can I    see any unicode
 - t = hivec.sql("select * from database.table").collect() there are    no errors reported in t variable itself
   '>>>t
   prints out all the rows

As soon as t  gets converted to DataFrame the issue pops up
I tried encoding and decoding, combination between 'utf-8' and    'ascii' mainly as I couldn't tell if the field was a unicode or a ascii visually as hive select nor printing the list was showing anything visible or throwing errors.
data.select(*(c.encode("ascii","ignore") if not isinstance(c,unicode) else c for c in data.columns )).show(10)

Throws the same error. Any suggestions how to get around this?


Q: The removeChild(); is removing two inputs? I just need to remove 1 input I'm new to javascript, and currently, I need an individual delete function. I decided to use variable.removeChild() but it's deleting 2 inputs
document.addEventListener('DOMContentLoaded', () => {

  document.getElementById("delete").addEventListener("click", function deletes(){

    var parent = document.getElementById("list");

    var child = parent.getElementsByTagName("li")[0];

    console.log(child);

    parent.removeChild(child); //deletes a pair of my li inputs

  });

});

Here is how my HTML code looks like

LIST

Items:

test

        <form id="insert">
            <input type="text" id="itemInput" placeholder="Item" name="item">
            <input type="submit" id="add" value="Add">

        </form>
        <input type="submit" id="search" value="Search"> //search doesn't do anything yet
        <input type="submit" id="delete" value="Delete first item">  //Here is where it begins

Here is my other function. I also use addEventListener() perhaps is that the problem?
This code allows me to add list items dynamically to how the user wishes
document.addEventListener('DOMContentLoaded', () => {
//calls function once #insert has submit a form/hit the input
document.querySelector('#insert').onsubmit = () => {

    //create variable
    if(document.querySelectorAll('li').length >= 10){
        return false;
    };

    //get the value of the input
    let name = document.querySelector('#itemInput').value;
    //stores value in the h3 tag

    //create element of 'li'
    const li = document.createElement('li');
    //add the contents to the value of 'name'
    li.innerHTML = name;

    //now append the element to the #list section
    document.querySelector('#list').append(li);

    //gets the length of all the list items (li) and stored it in counter
    counter = document.querySelectorAll('li').length;
    //change the h2 tag with the updated list items
    document.querySelector('h2').innerHTML = `Items: ${counter}`;

    //prevents the form from submitting (good for debugging!!!)
    return false;
};

});

A: Get the list with document.querySelector('#list') and the first li by adding .querySelectorAll('li')[0], then find inputs inside.

document.addEventListener('DOMContentLoaded', () => {
    document.querySelector('#delete').addEventListener("click", function deletes(){
        let li = document.querySelector('#list').querySelectorAll('li')[0];
        let inputs = li.querySelectorAll('input');
        // Is there any input in li?
        if(inputs.length > 0) {
            // Delete only the first one
            inputs[0].remove();
            // If you want to keep other inputs, just disable the button
            this.disabled = true;
        }
    });
});

     <input type="text" value="input1">
     <input type="text" value="input2">

<button id="delete">Delete</button>

querySelector() and querySelectorAll() lets you find items by id, classname, tagname, attributes, etc. Just like jQuery does. Reference: https://developer.mozilla.org/en/docs/Web/API/Document/querySelector


Q: Select select form options using links and asmselect I have integrated jquery-asmselect  and would like to be able to also select the options using other links on the page.  To visualize what I'm trying to do, you can view the page here
Here is the jquery code I'm using for asmselect:
$(document).ready(function() {
    $("#CategoryID").asmSelect({
        addItemTarget: 'bottom',
        animate: true,
        highlight: false,
        sortable: false
    }).after($("select all neighborhoods").click(function() {
        $("#CategoryID").children().attr("selected", "selected").end().change();
        return false;
    }));
    $("#search_SubCategoryID").asmSelect({
        addItemTarget: 'bottom',
        animate: true,
        highlight: false,
        sortable: false
    }).after($("select all cuisines").click(function() {
        $("#search_SubCategoryID").children().attr("selected", "selected").end().change();
        return false;
    }));
});

A: First of all, you'll need to identify in wich neighborhood you are clicking. Adding a rel (like in the options) might work:
...

    East Village/LES

...

Then, add this script:
$(".search-map a").click(function(event) {
    event.preventDefault();
    var hood = $(this).attr('rel');
    var $option = $('option[rel=' + hood + ']');

    $option.change();
    return false;
});

Based on this asmselect example. You just need to get the correspondig option depending on the clicked link, and then call the change(); trigger on it.
EDITED:
The above code failed big time :P Here's the new version (With a working fiddle):
$(".search-map a").click(function() {

    var $city = $(this).html();
    var $rel = $(this).attr('rel');
    var disabled = $('#asmSelect0 option[rel=' + $rel + ']:first').attr('disabled');

    if (typeof disabled !== 'undefined' && disabled !== false) {
        return false;
    }

    var $option = $('<option></option>').text($city).attr({'selected': true, 'rel': $rel});

    $('#asmSelect0').append($option).change();
    $('#asmSelect0 option[rel=' + $rel + ']:first').remove();

    return false;
});

I had to do something I don't really like, but I couldn't find any other way of doing this without conflicting with the plugin. Anyway, it's not that bad. Basically I get the name of the neighborhood, the rel to identify the option, generate a new <option>, change(); it, and delete the old option tag. The plugin didn't like trying to change the tag itself without creating a new one... I had to add the if (...) thing because when adding a neighborhood (disabling it on the select), and clicking again on the same neighborhood, it enabled it on the select (And we don't want that, since it's already selected). With that condition, if we click on a link whose neighborhood is disabled, we'll do nothing and the option will remain the same.
Sorry if my explanation sucks, It took me a while to get the problem, I had to build everything up again, and I felt like having a lack of english xD Hope it works!


Q: IFilterProvider Injection without a Service Locator My goal: To inject an IFilterProvider in the case where one is provided by DI, but to fallback to the global FilterProviders.Providers.GetFilters() method by default.
There are a lot of resources on the Internet (including an "official" Microsoft one) that demonstrate how to inject the IFilterProvider interface into a class. However, all of them use the service locator anti-pattern (per Mark Seeman) to do so. Here is a list of the ones I found:

*

*http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvcdependencyinjection_topic4.aspx

*http://merbla.blogspot.com/2011/02/ifilterprovider-using-autofac-for-mvc-3.html

*http://thecodinghumanist.com/blog/archives/2011/1/27/structuremap-action-filters-and-dependency-injection-in-asp-net-mvc-3

*IFilterProvider and separation of concerns
So what's wrong with these methods? They all inject a DI container into the target class instead of the other way around. If you see something in your class like container.Resolve(), then you are not yielding control of the lifetime of objects to the DI container, which is what inversion of control is really about.
In addition, the problem with trying to create a fallback to the global FilterProviders.Providers instance is that although it has the same signature as the IFilterProvider interface, it does not actually implement this interface. So how can the global static member be injected as a logical default and still allow the use of DI to override it?

A: Create an wrapper class based on IFilterProvider that returns the global FilterProviders.Providers.GetFilters() result, like this:
public class FilterProvider
    : IFilterProvider
{
    #region IFilterProvider Members

    public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        return FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor);
    }

    #endregion
}

Then, adjust the constructor in your classes that require the dependency.
public class MyBusinessClass
    : IMyBusinessClass
{
    public MyBusinessClass(
        IFilterProvider filterProvider
        )
    {
        if (filterProvider == null)
            throw new ArgumentNullException("filterProvider");
        this.filterProvider = filterProvider;
    }
    protected readonly IFilterProvider filterProvider;

    public IEnumerable<AuthorizeAttribute> GetAuthorizeAttributes(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        var filters = filterProvider.GetFilters(controllerContext, actionDescriptor);

        return filters
                .Where(f => typeof(AuthorizeAttribute).IsAssignableFrom(f.Instance.GetType()))
                .Select(f => f.Instance as AuthorizeAttribute);
    }
}

Next, configure your DI container to use FilterProvider concrete type as the default.
container.Configure(x => x
    .For<IFilterProvider>()
    .Use<FilterProvider>()
);

If you need to override the default and provide your own IFilterProvider, now it is just a matter of creating a new concrete type based on IFilterProvider and swapping what is registered in the DI container.
//container.Configure(x => x
//    .For<IFilterProvider>()
//    .Use<FilterProvider>()
//);

container.Configure(x => x
    .For<IFilterProvider>()
    .Use<NewFilterProvider>()
);

Most importantly, there is no service locator anywhere in this pattern.


Q: How to read checkbox value in Angular I am trying to get the value of checkbox - i.e true or false. But this is only returning me Object Object.
<mat-cell *matCellDef="let row">
   <mat-checkbox [checked]="row.isDisabled" (change)="UpdateValue($event,row)">
   </mat-checkbox>
</mat-cell>

In my TS, I have this:
UpdateValue(event:any, myStock: stock) {
  alert(event);
  ...
}

Does anyone know how I can get the value as true or false?

A: Simply use:
UpdateValue(event:any,myStock: stock) {
   // ...
   console.log(event.checked);
}

Here's a working stackblitz for the same.

A: Just use ngModel
<mat-cell *matCellDef="let row"> <mat-checkbox
   [checked]="row.isDisabled"
   [(ngmModel)]="checkValue"
   (change)="UpdateValue($event,row)"></mat-checkbox> </mat-
    cell>

UpdateValue(event:any,myStock: stock) {
     alert(this.checkValue);
 }


Q: Is it possible to parse a remote file with ajax/javascript prototype I want to solve this puzzle but the file resides on remote server. How can I parse this file because I keep getting this error.
XMLHttpRequest cannot load http://www.weebly.com/weebly/publicBackend.php. Origin http://mysite.com is not allowed by Access-Control-Allow-Origin.
Refused to get unsafe header "X-JSON"
Code Below
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Untitled Document</title>
        <script type="text/javascript" src="prototype.js"></script>
        <!-- Puzzle starts here -->
<script type='text/javascript'>

  // Note: there may be some unfinished code here, that needs finishing...

  // You should probably try to get this function working...
  function solvePuzzle() {

        new Ajax.Request('http://www.weebly.com/weebly/publicBackend.php', {
          parameters:{
            pos: 'solvepuzzle'
          },
          onSuccess:handlerSolvePuzzle,
          onFailure:function() { alert('Transmission error. Please try again.'); }
        });

  }

  function handlerSolvePuzzle(t) {

        var responseText = t.responseText;
        responseText = responseText.replace(/\n/, "");

        if (responseText.match(/!!$/)) {

          alert("Oops: "+responseText);

        } else {

          // Still need to decode the response

          // Once the response is decoded, we can fire off the alert
          // giving the user further instructions
          //alert(responseText);
          //alert('To complete the challenge, '+t.responseText);

        }

  }

</script>
    </head>
    <body>

<input type="button" onclick="solvePuzzle()" value="hello"/>
    </body>
</html>

A: Chrome and Firefox's developer tools allow you to modify JS on the fly.
If you're on Chrome, open up the console by going to the menu View->Developer->JavaScript Console. Copy the js from the page source. Alter it. Then paste altered javascript function(s) into the console. Hit enter. Then start typing 'solvePuzzle();' Hit enter. You'll see the response come back.
For Firefox, you'll need to download Firebug plugin.

A: You cannot do this from JavaScript due to the same origin policy: https://developer.mozilla.org/en/Same_origin_policy_for_JavaScript.  If this weebly site supports some sort of JSON API, you could use JSONP: http://en.wikipedia.org/wiki/JSONP.  Other than that, you're probably better off interacting with this site via the server side due to security restrictions on the client side.

A: Consider installing a HTTP tunnel on your "mysite.com" so that the browser does not have to access "weebly.com" directly.


Q: Updated command to start blank project with ionic2 and angular2? Trying to create blank project with ionic2 not ionic1 or ionic3 using the below command in terminal
ionic start SqliteDemo blank --type ionic2

Error comes as below:
✔ Creating directory ./SqliteDemo - done!
✖ Looking up starter - failed!
[ERROR] Unable to find starter template for blank

        If this is not a typo, please make sure it is a valid starter template
        within the starters repo: https://github.com/ionic-team/starters

what i have tried ?
ionic start SQliteDemo blank --v2

not worked
all above commands just create Folder for the given name and nothing is inside.
Actually Trying:
I need to work with sqlite storage/ with any android native api's, as first attempt i try to do a sample project based on sqlite so that i can add android platform to this project and open with Android-Studio and check whether the .db file is created and working or not using Android-Monitor. If any references for this question will be very much appreciated.


Q: Java code is running select and update query for every data I am writing a Java code in Spring JPA which can add or update a data when saveData function is called. what I am trying to do is that if data is new it gets added as a new record in the database or else it will be updated.
public void saveData(List<StudentTable> studentTableList){

    List< StudentTable > data= new ArrayList<>();

    for(StudentTable dt: studentTableList){
        if(dt.getStudentId() ==null) {
            data.add(dt);

        }else{
            studentRepository.findById(dt.getStudentId()).map(
                    student->{
                        student.setFirstName(dt.getFirstName());
                        student.setLastName(dt.getLastName ());
                        student.setPhone(dt.getPhone());
                        student.setAddress(dt.getAddress());

                        return data.add(student);
                    });
        }
        studentRepository.saveAll(data);
        data.clear();
    }
}

While this code is working fine I see performance issues as my entries grow. I see that update and select queries are run for each row of the table which is slowing down the performance.
I want to know if there is any way to run queries only for those rows which are updated or added on a single post request or to improve the performance?

A: What about 2 blocks of code for each case?
Student student = studentRepository.findById(dt.getStudentId());
if(student == null){
  Student newStudent = new Student();
  //add data
  newStudent.save();
} else {
  student.setFirstName(dt.getFirstName());
  student.setLastName(dt.getLastName ());
  student.setPhone(dt.getPhone());
  student.setAddress(dt.getAddress());
  student.update();
}

A: You can follow what @fladdimir mentioned. Or, here is my suggestion[will not provide any code, leaving up to you]:

*

*filter objects which are old ones[contains id as I can see from your code]  and news ones in two separate lists

*List all ids

*use id <--> object as keyValue in a map

*Query all the objects with idList you got using IN clause

*Now, set value as you are doing in your 2nd code block from the map, add them in a list

*merge this list with new objectList

*save them altogether with saveAll(your_merged_list)

I am not saying this is the optimized way, but at least you can reduce load on your db.


Q: How to get a list from WebApi controller using jquery ajax I have this controller that returns correct results when I call it from a browser.
public async Task<IHttpActionResult> Get(string Id)
{
    if (Id == null)
        return BadRequest();

    try
    {
        var items = await obj.GetItems(Id);
        return Ok(items.ToList());
    }
    catch (Exception e)
    {
        return Content(HttpStatusCode.BadRequest, e.Message);
    }
}

In my view, I have this jquery.
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        data: {
            Id: "5AE158",
        },
        success: function (data) {
            alert('success');
        },
        error: function (x) {
            alert("error");
        }
    });

When I trigger the function from the UI, I hit a breakpoint in the Controller and I see that it returns correct results, but in the view control flows to the error handler.
I experimented with many combinations of dataType, type and function signatures but I'm not able to get a success return value.
Any help is appreciated.

A: Thanks to all that responded for the clues that helped me solve this. I looked in the console and saw the error message "No 'Access-Control-Allow-Origin' header is present on the requested resource".
What wasn't clear in my question was that the url I was trying to reach was on a different server and I was encountering this problem.
Thanks for the help.