text:
Q: Creating dict from file with repeated row names I have a .txt file with values like so:
1 3 4
2 5 6
5 7

I want to create a dictionary like so:
1 [3, 4]
2 [5, 6]
5 [7]

The first number in a line is the key and the rest of the line are the values to be put into the list.
What is the most efficient way to achieve this?
I know the way to iterate using
f = open('data.txt','r')
for i in f:

And then using condition to create a list and then add this to the dict. But I want a neater way to do it.

A: Here's another, more direct, way to do it:
d = {}
with open('somedata.txt', 'rt') as f:
    for line in f:
        numbers = map(int, line.split())
        numbers = list(numbers) # for Python 3
        d.setdefault(numbers[0], []).extend(numbers[1:])

print(d)  # -> {1: [3, 4], 2: [5, 6], 5: [7]}

A: Use collections.defaultdict,
import collections

d = collections.defaultdict(list)

with open('data.txt','r') as fp:
    for line in fp:
        l = map(int, line.strip().split())
        d[l[0]].extend(l[1:])

print(d)
# defaultdict(<type 'list'>, {1: [3, 4], 2: [5, 6], 5: [7]})

A: Split each line into a (key, values) pair, and add them to a default dict with empty list as initial value
from collections import defaultdict

mydict = defaultdict(list)

for line in f.readlines():
    line = [int(item) for item in line.split()]
    key, *values = line
    mydict[key].extend(values)

A: Here's an option without any imports and converts the entries to ints:
testDict = {}

with open('test.txt') as f:
   lines = f.readlines()
   for line in lines:
      line = map(int, line.split(' '))
      testDict[line[0]] = list(line[1:])

print testDict # -> {1: [3, 4], 2: [5, 6], 5: [7]}


text:
Q: How to write an integral as a limit? We know that the derivative of a function called $f(x)$ can be written as a limit, just like here:$$\frac{d}{dx}f(x)=\lim\limits_{\Delta x\to0}\frac{f(x+\Delta x)-f(x)}{\Delta x}$$ but

Is there any definition of integrals in the form of limits?

A: Recall that a partition of an interval $[a,b]$ is simply a set of points of the interval, one which is $a$ and the other which is $b$.
Darboux's Integral The construction is as follows. We define the upper and lower sums, $U$ and $L$, of $f$ for the partition $P$ as follows: $U(f,P) =\sum_{i=1}^n (a_{i}-a_{i-1})M_i $. $L(f,P) =\sum_{i=1}^n (a_{i}-a_{i-1})m_i $ where $M_i = \sup\limits_{[a_{i-1},a_i]} f(x)$ and $m_i = \inf\limits_{[a_{i-1},a_i]} f(x)$. If $f$ happens to be continuous we can just define them as the maximum and minimum of $f$ in the interval $[a_{i-1},a_i]$. Many properties are derived, but an important result is the following  (Spivak's Calculus, Ch. 13, p.355):

If it is the case that
  $$\inf \left\{ U\left( {f,P} \right);\text{ P is a partition of I} \right\} = \sup \left\{ L\left( {f,P} \right); \text{ P is a partition of I} \right\}$$
  then we say $f$ is integrable on $I$ and denote this common value by $$\int_a^b f(x) dx$$

The second important theorem is (Spivak's Calculus, Ch. 13, p.356)

If $f$ is bounded on an interval $I$, then it is integrable on $I$ if for any $\epsilon >0$ there exists a partition $P$ of $I$ such that
  $$U(f,P)-L(f,P)<\epsilon$$

An example would help. Take $f:[0,1]\to\Bbb R$ with $x\mapsto x^2$. We partition $[0,1]$ into $n$ intervals. $[0,1/n],[1/n,2/n],[2/n,3/n],\dots,[(n-1)/n,n/n]$. Note we have that $\Delta P = 1/n$. Since our function is monotone increasing, we can choose the $M$ and $m$ as the maximum and minimums. That is
$$M_i = f(a_i)= \frac{i^2}{n^2}$$
$$m_i = f(a_i)= \frac{(i-1)^2}{n^2}$$
The sums are then
$$\eqalign{
  & U\left( {f,P} \right) = \sum\limits_{i = 1}^n {\frac{1}{n}\frac{{{i^2}}}{{{n^2}}}}  = \frac{1}{{{n^3}}}\sum\limits_{i = 1}^n {{i^2}}   \cr
  & L\left( {f,P} \right) = \sum\limits_{i = 1}^n {\frac{1}{n}\frac{{{{\left( {i - 1} \right)}^2}}}{{{n^2}}}}  = \frac{1}{{{n^3}}}\sum\limits_{i = 1}^{n - 1} {{i^2}}  \cr} $$
Those sums can be evaluated to yield
$$\eqalign{
  & U\left( {f,P} \right) = \frac{1}{{{n^3}}}\frac{{n\left( {2n + 1} \right)\left( {n + 1} \right)}}{6}  \cr
  & L\left( {f,P} \right) = \frac{1}{{{n^3}}}\frac{{n\left( {n - 1} \right)\left( {2n - 1} \right)}}{6} \cr} $$
We have then that
$$\frac{1}{{{n^3}}}\frac{{n\left( {n - 1} \right)\left( {2n - 1} \right)}}{6} < \int\limits_0^1 {{x^2}dx}  < \frac{1}{{{n^3}}}\frac{{n\left( {2n + 1} \right)\left( {n + 1} \right)}}{6}$$
Note that we can make the difference of the sums arbitrarily close to each other taking finer and finer partitions, that is $U\left( {f,P} \right) - L\left( {f,P} \right) < \frac{1}{n}$ and since:
$$\eqalign{
  & \mathop {\lim }\limits_{n \to \infty } \frac{1}{{{n^3}}}\frac{{n\left( {2n + 1} \right)\left( {n + 1} \right)}}{6} = \frac{1}{3}  \cr
  & \mathop {\lim }\limits_{n \to \infty } \frac{1}{{{n^3}}}\frac{{n\left( {n - 1} \right)\left( {2n - 1} \right)}}{6} = \frac{1}{3} \cr} $$
The above allows us to conclude that
$$\int\limits_0^1 {{x^2}dx}  = \frac{1}{3}$$
A final trickery can be used now that we have this result to obtain a new one:
$$\int\limits_0^a {{x^2}dx}  = {a^3}\int\limits_0^a {{{\left( {\frac{x}{a}} \right)}^2}d\left( {\frac{x}{a}} \right)}  = {a^3}\int\limits_0^1 {{u^2}du}  = \frac{{{a^3}}}{3}$$
And then ($b>a$)
$$\int\limits_a^b {{x^2}dx}  = \int\limits_0^b {{x^2}dx}  - \int\limits_0^a {{x^2}dx}  = \frac{{{b^3}}}{3} - \frac{{{a^3}}}{3}$$
Riemann's Integral. Remember given a partition $P=\{x_i\}_{1\leqslant i\leqslant n}$ we call collection of numbers for which $x_{i-1}\leqslant t_i\leqslant x_i$ a set of tags for the partition $P$. In this case we have no upper or lower sums, but a sum:
$$R(f,P)=\sum_{i=1}^n f(t_i) (x_i-x_{i-1})$$

We say that $f$ is Riemann integrable in $I$ and denote $$\int_a^b f(x) dx = \mathcal I$$ if, for any $\epsilon >0$, there exists a $\delta >0$ such that, if $\Delta P < \delta$, then
$$\left| R(f,P)- \mathcal I\right|<\epsilon$$

Note that for any Riemann sum, we have that
$$L(f,P) \leqslant R(f,P) \leqslant  U(f,P)$$
This can be used to prove the assertion that

$f$ is Darboux integrable $\iff$ $f$ is Riemann integrable.

A: Yes, a definite integral is also defined as a limit. (There are several ways of doing this)
$$
\int_a^b f(x) \; dx = \lim_{n\to \infty} \sum_{i=1}^{n}  f(x_{i})\Delta x
$$
where
$$\Delta x = \frac{b-a}{n}$$
and
$$x_i = a + i\Delta x.$$
Now to get an understanding of why this makes sense, you can for example take a look at this Wikipedia article:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't understand Java doubly linked list I have this code
public class Doublylinkedlist {
    private DLLNode head;
    private DLLNode tail;
    private int length;
}

What is this DLLNode head declaration? What data type it is? Can someone please explain?
Here is the DLLNode class
Public class DLLNode{
private int data ;
private DLLNode prev;
private DLLNode next;

}
Now what is this 'private DLLNode prev'?
What data type it is ?

A: DLLNode is a user defined class just like your Doublylinkedlist class.
A possible example of what that DLLNode class might look like:
public class DLLNode
{
    int data;
    DLLNode next;
    DLLNode prev;

    public DLLNode(int data)
    {
        this.data = data;
        this.next = null;
        this.prev = null;
    }
}


text:
Q: After using TightVNC, cannot copy/paste between Windows applications This is very similar to this, this, and this question asked here on SO and elsewhere. But differs significantly. I have tried used these commands on the machine running VNC
vncserver :22 -geometry 1600x1200
vncconfig display :22 -nowin &

I also tried these commands
export XKL_XMODMAP_DISABLE=1
autocutsel -fork

The experience I have experienced is different, as follows.

*

*Before running the VNC Viewer, I can copy/paste between Windows apps

*I start the VNC Viewer, and open a command prompt terminal

*I can copy/paste between Windows apps, between Linux terminals, and
from Windows apps to a Linux terminal.

*I can copy/paste from a Linux terminal to Windows app, by
double-clicking on the Linux content and using ctrl-v in Windows.
However, when I do this, I can no longer copy/paste between Windows
apps, and from Windows to Linux. That is, the content of the Windows
clipboard retains the Linux content, and can never be updated using
ctrl-c. In this case, ctrl-v always pastes the Linux content. To fix
this, I have to kill the VNC Window and kill the vncserver session.

Anyone else seen this?
Thanks for reading,
Paul

A: It seems that TightVNC is the culprit here. When I use TigerVNC the issue disppears, and I can copy/paste between Windows apps, and from TightVnc into Windows.

A: Restarting VNC Server fixed issue for me:
vncserver -kill :1
from terminal:
vncserver -geometry 1900x1000 -DisconnectClients=0


text:
Q: Deployment to Azure Blob Storage ends up with error Trying to deploy artifacts ends up with the following error:

The input is not a valid Base-64 string as it contains a non-base 64
  character, more than two padding characters, or an illegal character
  among the padding characters.

I'm running two scripts before and after I build the app in AppVeyor:
cd $env:APPVEYOR_BUILD_FOLDER\patch;
npm install;
node patch-project-json.js $env:APPVEYOR_BUILD_FOLDER\src\Project1\project.json $env:APPVEYOR_BUILD_VERSION;
node patch-project-json.js $env:APPVEYOR_BUILD_FOLDER\src\Project2\project.json $env:APPVEYOR_BUILD_VERSION;
node patch-project-json.js $env:APPVEYOR_BUILD_FOLDER\src\Project3\project.json $env:APPVEYOR_BUILD_VERSION;

cd $env:APPVEYOR_BUILD_FOLDER
dotnet restore

and
dotnet publish .\src\Project1 --output $env:APPVEYOR_BUILD_FOLDER\deploy\Project1 --configuration Release --no-build;
dotnet publish .\src\Project2 --output $env:APPVEYOR_BUILD_FOLDER\deploy\Project2 --configuration Release --no-build;
dotnet publish .\src\Project3 --output $env:APPVEYOR_BUILD_FOLDER\deploy\Project3 --configuration Release --no-build

As you can see, I am using this to set versions in project.json files based on the $env:APPVEYOR_BUILD_VERSION. I don't know if it's relevant information. So after successful build and publish, I want to upload an artifact to the blob storage.

A: Turned out I had typos in Deployment settings for Storage access key entry ;)


text:
Q: Building an URL according to values sent from multiple select boxes I'm working at some e-commerce website where I have a bunch of filters for each product category. The filters are displayed in select boxes and each filter has more than one value.
For example if you are browsing the watches category, possible filters are: brand (Tissot, Certina, Timex), movement type (automatic, mechanic, quartz), chronograph (yes, no).
The value for each select option is a pair of filter id and filter option id, separated by a comma.
For example:
Sex
<select id="filter-sex" name="filter-sex">
  <option value="">All</option>
  <option value="1,1">For her</option>
  <option value="1,2">For him</option>
</select>

Brand
<select id="filter-brand" name="filter-brand">
  <option value="">All</option>
  <option value="3,10">Tissot</option>
  <option value="3,11">Certina</option>
</select>

What I would like to accomplish is to pass those values in the URL.
For example if I select "For her" from the filter mentioned above, my URL must look like http://www.mystore.com/watches/filters-1,2/
Then, if I select Tissot from the brand filter, the URL must look like http://www.mystore.com/watches/filters-1,2-3,10/
Any ideas how can I build that URL according to selected values?

A: I am assuming you have a button that when the user clicks, it takes them to the url, right?
$('select').change(function(){
 buildURL();
});

function buildURL(){
    var baseUrl = 'http://www.mystore.com/watches/filter';
    var url = baseUrl;
    $('select').each(function(index, value){
        if(value.value != "")
            url += '-' + value.value;
    });
    $('#url').html(url);
}

For this version, check out: http://jsfiddle.net/jCq9U/
If you would like to do it server side, it would be the same logic.
 $baseUrl = 'http://www.mystore.com/watches/filters';
 $filterSex = $_POST['filter-sex'];
 $filterBrans = $_POST['filter-brand'];

 header('Location: ' . $baseUrl . "-" . $filterSex . "-" . $filterBrand);


text:
Q: ggplot2 moving legend in to plot area without borders around key Hi im trying to add my legend area to my plot area without the white borders around my key. So far i have this:
Legend in plot area but white border present:

Legend style i want:

ggplot(data=Pig, aes(x=breed, y= p1_plus_p3_fat_depth_mm, color=sex))+
geom_boxplot()+
theme(legend.title=element_blank()) +
theme(panel.grid.major = element_blank()) +
theme(panel.grid.minor = element_blank())+
xlab("Pig Breed") +
ylab("The P1 and P3 Fat Depth in mm")+
scale_colour_discrete(name  ="Sex",breaks=c("B", "S"),labels=c("Boar", "Sow"))+
theme(legend.justification = c(1, 1), legend.position = c(1, 1))+
theme(legend.background = element_rect(fill="transparent"))

A: You will need to use legend.key = element_blank() to drop the background and borders around the boxplot icons.
ggplot(data=iris[c("Species", "Sepal.Length")], aes(x=Species, y= Sepal.Length, color=Species))+
  geom_boxplot()+
  theme(legend.title=element_blank()) +
  theme(panel.grid.major = element_blank()) +
  theme(panel.grid.minor = element_blank())+
  theme(legend.justification = c(1, 1), legend.position = c(1, 1))+
  theme(legend.background = element_blank(),
        legend.key = element_blank())

I prefer using element_blank() which will remove a theme element as opposed to setting it to transparent and leaving it there. I've found depending on the graphics device the transparent can be interpreted differently.


text:
Q: Magento 2 : Is it possible to add order cancellation functionality in frontend? I want to give the order cancellation functionality in frontend to user in case of order not shipped.
What would be the step to achieve this functionality ?

A: This is more complicated than it sounds.
Cancellation while pending is easy. The method is described in Cancel Order from magento 2 frontend? and I've implemented it in a module with the template tweaks needed (and confirmation dialogues).
https://github.com/lingwooc/cancel-magento2
You should note this only works for pending orders. Most orders (especially online payments) won't go into pending, they will go into processing. For online payments this means the money will have been taken and will need to be refunded. Magento doesn't allow cancellation at this stage, only shipping or refund. I would think carefully about whether you want your customers to be able to generate a refund automatically. There is the potential you may ship refunded goods if you don't have a robust process. I would implement this as a refund request which should generate a support ticket. The module above has the templates/layouts that you would need to change to add such a button.
This chart shows the status change flow of a mangeto2 order.

Source question: New order status staying "pending" instead of processing in Magento 2
Source: https://www.mexbs.com/magento-blog/magento-order-statestatus-flow

A: You must create an extension:

*

*First of all you have to overwrite the customer account page layout in order to introduce the control (button) that links to a functionality.

*The button you added should link to a controller that does the job.

*Eventually you will need to add some blocks to render any output/intermediate interaction.


text:
Q: In Applescript, Why does my "Tell app Finder" block not delete "f" even when it exists? This question is similar to AppleScript set directory path in Finder but the answer there did not work for me!
local destination, libraryName, f
set destination to "/Users/bryandunphy/Music/Result"
set libraryName to "Testing"
if not ((libraryName ends with ".xml") or (libraryName ends with ".XML")) then set libraryName to libraryName & ".xml"
menuClick({"iTunes", "File", "Library", "Export Library…"})
set f to "/Users/bryandunphy/Music/Result/Testing.xml" -- (destination & "/" & libraryName) as string
tell application "Finder"
    if POSIX file f exists then
        delete f
        beep
    end if
end tell
tell application "System Events" to tell process "iTunes" to tell its front window to set the value of its text field "Save As:" to libraryName
if switchDir(destination, "iTunes", true, true) then return destination & "/" & libraryName -- first true = click default (Save) button, last = create path if needed

The "if switchDir" line causes a "File Exists, Replace?" dialog to appear.

A: Found the answer myself by combining the answers to two other "Related" questions!
the "tell block" should be replaced with
if f begins with "~" then tell application "System Events" to set f to ((home directory of current user) & items 2 through -1 of (get f))
tell application "System Events" to if exists disk item (POSIX file f as string) then delete disk item (POSIX file f as string)

A: The simplest solution is to use alias objects in the "System Events" context:
set f to "/Users/bryandunphy/Music/Result/Testing.xml" # sample POSIX path
tell alias f of application "System Events"
    if it exists then delete it
end tell

Caveat: This instantly deletes the target file instead of moving it to the trash folder.
To do the latter, see the Finder-based solution below.
In the "System Events" context, alias objects can work directly with POSIX paths, and file operations can be performed as well.
Working in the "System Events" context rather than the "Finder" context is generally preferable for performance reasons, but note that not some operations are only possible in the "Finder" context - moving a file to the trash instead of instantly deleting it being one example.

As for why your "Finder"-context approach didn't work:
The ways of the AppleScript are mysterious: POSIX file f exists does not work - it doesn't detect the file's existence - but f as POSIX file exists does:
set f to "/Users/bryandunphy/Music/Result/Testing.xml" # sample POSIX path
tell application "Finder"
    if f as POSIX file exists then delete f as POSIX file
end tell

Another quirk: a tell f as POSIX file ... end tell block with if it exists then delete it in it - analogous to the "System Events" solution above - does not work.
Unlike the "System Events" solution at the top, this:

*

*moves the file to the trash instead of deleting it right away,

*

*which causes the system sound for moving something to the trash to sound.

*returns the file object that was just moved to the trash (already in its new location, the trash folder).


text:
Q: Asterisk GUI - Checking Write Permission for GUI Folder I have installed Asterisk and Asterisk GUI on an Ubuntu Desktop 14.04. When I go to the GUI page and login it comes up and says "Checking write permission for gui folder" and stays on that screen.
http.conf file:
[general]
enabled = yes
bindaddr = 10.0.0.16
bindport = 8088
prefix = asterisk
;sessionlimit=100
enablestatic = yes
redirect = / /asterisk/static/config/index.htm

manager.conf file:
[general]
enabled = yes
webenabled = yes
port = 5038
bindaddr = 10.0.0.16

;#include "manager.d/*.conf"

[admin]
secret = admin
read = system,call,log,verbose,command,agent,user,config
write = system,call,log,verbose,command,agent,user,config,originate

A: Those config files have no any relation.
1) check in asterisk.conf which user it use(usualy asterisk)
2) do
 chown asterisk /var/lib/asterisk/ /var/spool/asterisk -R

A: chmod 777 should only be required, when the user asterisk has not been added or when it's group membership is somehow messed up - otherwise a chown should be enough to open the astdb.sqlite3 in read/write mode.
chown -R asterisk:asterisk /etc/asterisk/ /var/lib/asterisk /usr/share/asterisk
chmod 644 /etc/asterisk/*

wiki


text:
Q: findViewById not recognized this is part of my function, android studio isnt recognizing the findViewById function.
can anyone please help me figure out the problem is?\
 public void onClick(View v) {
                p1 = (EditText) findViewById(R.id.p1);
                p2 = (EditText) findViewById(R.id.p2);
                if (v.getId() == R.id.btnrock) {
                    if (player1.equals("")) {
                        player1 = "rock";
                        if (p1.getText().toString().length() == 0 || p2.getText().toString().length() == 0) {
                            Toast.makeText(c, "fill both names", Toast.LENGTH_LONG).show();
                        }
                        if (p1.getText().toString().equals(p2.getText().toString())&&p2.getText().toString().length()!=0) {
                            Toast.makeText(c, "use different names", Toast.LENGTH_LONG).show();
                        }
                        if (p2.getText().toString().length()!=0)score.setText("now "+ p2.getText());
                    }
                    else {
                        if (player1.equals("rock"))
                            score.setText("its a tie");
                        if (player1.equals("paper"))
                            score.setText(p1.getText() + " won");
                        if (player1.equals("scissors"))
                            score.setText(p2.getText() + " won");
                        if (player1.equals("lizard"))
                            score.setText(p2.getText() + " won");
                        if (player1.equals("spock"))
                            score.setText(p1.getText() + " won");
                        player1="";
                    }

A: If you are in Fragment
You have to use the View v object to access the findviewById() method
Here is how you would get it, also note that (EditText) cast is redundant
    public void onClick(View v) {
                    p1 =  v.findViewById(R.id.p1);
                    p2 =  v.findViewById(R.id.p2);
    .
    .
    .
    .....
}


text:
Q: Stackoverflowerror while running Javadoc Attempted to Javadoc my group's App project, but got stackoverflowerror.  Tried increasing heap space, but that did not seem to help.  I've googled this question, but all I've seen are questions and answers about apps that use recursion.  Anybody else encountered this problem with Javadoc? More to the point, does anybody know why Javadoc would do this?

A: In case of a StackOverflowError, increasing the Heap space does not help at all, as you don't have a "HeapOverflowError" (usually manifested as OutOfMemoryError).
Increase the stack size instead, use the -Xss VM option (i.e. passed with -J... before all other options and arguments).
Note that normally a stack overflow error is a sign of a bug in the program, which would be Javadoc in your case. Try a newer version of the JDK, if you don't do already.


text:
Q: Jobby/SuperClosure not working: The file containing the closure, "... : eval()'d code" did not exist I'm trying to use Jobby with PDO as my cronjobs manager. I've used SuperClosure (which is used by Jobby as well) to serialize my closure and insert it to database. Then I get all records from my database and I unseralize the closure before adding it as job to Jobby but all I get is:

root@test:/home/.../public_html/public# /usr/local/bin/php ./cron.php
  PHP Notice:  Serialization of closure failed: The file containing the closure, "/home/.../public_html/vendor/jeremeamia/SuperClosure/src/SerializableClosure.php(210) : eval()'d code" did not exist. in /home/.../public_html/vendor/jeremeamia/SuperClosure/src/SerializableClosure.php on line 117

Notice:  Serialization of closure failed: The file containing the closure, "/home/.../public_html/vendor/jeremeamia/SuperClosure/src/SerializableClosure.php(210) : eval()'d code" did not exist. in /home/.../public_html/vendor/jeremeamia/SuperClosure/src/SerializableClosure.php on line 117

Here is my code:
$config = array(
    'output' => ROOT_PATH . 'closure.log',
    'debug' => 1,
);
$jobby = new Jobby\Jobby( $config );
$serializer = new SuperClosure\Serializer();

$jobs = $model->getCronJobs();
foreach ( $jobs as $job )
{
    $job = array_filter( $job );

    try {
        $job['closure'] = $serializer->unserialize( $job['closure'] );
        unset( $job['command'] );
    } catch (SuperClosure\Exception\ClosureUnserializationException $e) {
    }

    $jobName = $job[ 'name' ];
    unset( $job[ 'name' ] );
    unset( $job[ 'id' ] );

    $jobby->add( $jobName, $job );
}

$jobby->run();

And what I get from $model->getCronJobs();:
array(1) {
    [0]=>
    array(23) {
        ["id"]=>
        string(2) "11"
        ["name"]=>
        string(9) "testzcron"
        ["command"]=>
        string(1) " "
        ["closure"]=>
        string(243) "C:32:"SuperClosure\SerializableClosure":197:{a:5:{s:4:"code";s:                                                                                102:"function () {
        echo 'I\'m a function (' . date('Y-m-d H:i:s') . ')!' . PHP_EOL;
        return true;
        };";s:7:"context";a:0:{}s:7:"binding";N;s:5:"scope";N;s:8:"isStatic";b:0;}}"
        ["schedule"]=>
        string(9) "* * * * *"
        ["mailer"]=>
        string(4) "smtp"
        ["maxRuntime"]=>
        NULL
        ["recipients"]=>
        NULL
        ["smtpHost"]=>
        NULL
        ["smtpPort"]=>
        NULL
        ["smtpUsername"]=>
        NULL
        ["smtpPassword"]=>
        NULL
        ["smtpSender"]=>
        string(15) "jobby@localhost"
        ["smtpSenderName"]=>
        string(5) "Jobby"
        ["smtpSecurity"]=>
        NULL
        ["runAs"]=>
        NULL
        ["environment"]=>
        NULL
        ["runOnHost"]=>
        NULL
        ["output"]=>
        NULL
        ["dateFormat"]=>
        string(11) "Y-m-d H:i:s"
        ["enabled"]=>
        string(1) "1"
        ["haltDir"]=>
        NULL
        ["debug"]=>
        string(1) "0"
    }
}

From log file:
PHP Fatal error:  Uncaught exception 'SuperClosure\Exception\ClosureUnserializationException' with message 'The closure did not unserialize to a SuperClosure.' in /home/.../public_html/vendor/jeremeamia/SuperClosure/src/Serializer.php:103
Stack trace:
#0 /home/.../public_html/vendor/hellogerard/jobby/src/BackgroundJob.php(233): SuperClosure\Serializer->unserialize('N;')
#1 /home/.../public_html/vendor/hellogerard/jobby/src/BackgroundJob.php(88): Jobby\BackgroundJob->runFunction()
#2 /home/.../public_html/vendor/hellogerard/jobby/bin/run-job(20): Jobby\BackgroundJob->run()
#3 {main}
thrown in /home/.../public_html/vendor/jeremeamia/SuperClosure/src/Serializer.php on line 103

Edit:
$serializer->unserialize( $job['closure'] ); is:
object(Closure)#9 (0) {
}

and when I call it it works perfectly fine:
root@test:/home/.../public_html/public# /usr/local/bin/php cron.php
I'm a function (2016-04-13 11:46:52)!
bool(true)

A: What's happening is that by unserializing the closure yourself (using SuperClosure) you're creating a different context for the closure, which can not be used to serialize it again. The long version:
SuperClosure uses Reflection; it accepts the Closure you pass and it figures out the php-file where this Closure was actually created. This is the only way to 'convert' the runtime Closure to serializable code, by storing the original source.

*

*By calling $serializer->unserialize() you are indirectly using eval() to convert serialized to runtime

*This creates a new Closure (in runtime) which you can use (with the eval function as its source)

*However, jobby also uses SuperClosure to serialize this closure (from runtime)

*SuperClosure needs the source for this Closure, and uses Reflection to find the code for your closure

*Instead of finding the actual source of the code, it finds the eval() that doesn't really contain this code

As for the solution, I think the best thing to do might be to remove this line:
$job['closure'] = $serializer->unserialize( $job['closure'] );

and convince Jobby to accept your SuperClosure directly; you might need to update Jobby like this:
     protected function getExecutableCommand($job, array $config)
     {
-        if (isset($config['closure'])) {
+        if (isset($config['closure']) && gettype($config['closure']) != 'string') {
             $config['closure'] = $this->getSerializer()->serialize($config['closure']);
         }

However, I have never used SuperClosure or Jobby and I can't really test this. Please let us know if this works.


text:
Q: How to calculate percentages using z scores? sample distribution of 10
(20,12,8,10,7,11,13,6,4,16) miles
What percent of the commuters travel more than 8 miles to class?

A: Using the Stabilized Normal Probability Plot technique, the data tests as normal:
   Obs    Xprime    Yprime      AbsDif alpha=.10 alpha=.05 alpha=.01
1    4 0.1435663 0.1728315 0.029265254 0.1324046 0.1453979 0.1724372
2    6 0.2531833 0.2554858 0.002302456 0.1324046 0.1453979 0.1724372
3    7 0.3333333 0.3028740 0.030459327 0.1324046 0.1453979 0.1724372
4    8 0.4030133 0.3534983 0.049515038 0.1324046 0.1453979 0.1724372
5   10 0.4681157 0.4612687 0.006847004 0.1324046 0.1453979 0.1724372
6   11 0.5318843 0.5166183 0.015266013 0.1324046 0.1453979 0.1724372
7   12 0.5969867 0.5716814 0.025305320 0.1324046 0.1453979 0.1724372
8   13 0.6666667 0.6255154 0.041151249 0.1324046 0.1453979 0.1724372
9   16 0.7468167 0.7711199 0.024303246 0.1324046 0.1453979 0.1724372
10  20 0.8564337 0.9069053 0.050471623 0.1324046 0.1453979 0.1724372

(JQT v21 i3 Technical Aids; Jul 1989.  Lloyd S. Nelson.  The power of this test was shown to compare favorably with the Shapiro-Wilk test and the Anderson-Darling test.)
Accepting the null hypothesis of normality, percentages can be calculated based on z-scores in the following manner:
Using R:
commute <- c(20,12,8,10,7,11,13,6,4,16)
pnorm((mean(commute)-8)/sd(commute))

Using Excel:
=NORM.S.DIST((AVERAGE(A1:A10)-8)/STDEV.S(A1:A10),TRUE)

where your sample is in the range A1:A10.


text:
Q: jQuery UI Highlight Effect - how can I use the border? I try to use highlight in jQuery but color works but border doesn't work.
How can I use the border? border: 2px solid #32a511
$("div").click(function () {
      $(this).effect("highlight", {
color: '#effdeb', border: '2px solid #32a511'}, 3000);
});

A: the jQuery .effect() simply applies pre-made animations to your element. as per Daniel's comment, it seems that the highlight effect does not work on borders.
instead, you could use the jQuery .animate() to animate your div manually:

$("div").click(function() {
  $(this).animate({
    "background-color": '#effdeb',
    "border-color": "32a511",
    "border-width": "2px"
  }, 500);
});
div {
  width: 100px;
  height: 100px;
  display: inline-block;
  border: 1px solid black;
  box-sizing:border-box;
}


text:
Q: ASP.NET MVC - Cannot upload more than 5 files I am using HttpPostedFileBase for uploading files in MVC. It is working fine when I upload 5 files at a time. But as I select more than 5 files, even 6 files it won't work and save functionality is also not working while I select more than 5 files.
This is my ActionMethod for saving other data with uploading files.
ActionMethod
[HttpPost]
public ActionResult AddEditCoffinCasketItem(CoffinCasketItemModel model)
{
    if (ModelState.IsValid)
    {
        // Some code

        if (coffinData.ID > 0)
        {
            if (model.Image != null)
            {
                coffinData.ThumbImageUrl = CommonHelper.UploadFile(SystemEnum.EntityType.Coffin.ToString(), model.Image);
            }

            if (model.Image360 != null)
            {
                coffinData.Image360FileSize = CommonHelper.ToKiloBytes(model.Image360.ContentLength);
                coffinData.Image360Url = CommonHelper.UploadFile(SystemEnum.EntityType.Coffin.ToString(), model.Image360);
            }
        }
        else
        {
            coffinData.ThumbImageUrl = CommonHelper.UploadFile(SystemEnum.EntityType.Coffin.ToString(), model.Image);
            if (model.Image360 != null)
            {
                coffinData.Image360FileSize = CommonHelper.ToKiloBytes(model.Image360.ContentLength);
                coffinData.Image360Url = CommonHelper.UploadFile(SystemEnum.EntityType.Coffin.ToString(), model.Image360);
            }

            if (model.IsBuildYourOwn == true)
            {
                coffinData.TopImageUrl = CommonHelper.UploadFile(SystemEnum.EntityType.Coffin.ToString(), model.TopImage);
                coffinData.BottomImageUrl = CommonHelper.UploadFile(SystemEnum.EntityType.Coffin.ToString(), model.BottomImage);
            }
        }

        int id = this.coffinService.SaveCoffin(coffinData);

        foreach (HttpPostedFileBase item in model.LargeImage)
        {
            if (item != null)
            {
                CoffinCasketImage coffinImage = new CoffinCasketImage();

                coffinImage.LargeImageUrl = CommonHelper.UploadFile(SystemEnum.EntityType.Coffin.ToString(), item);
                int coffinImageId = this.coffinService.SaveCoffinLargeImage(coffinImage);
            }
        }

        this.TempData["msg"] = string.Format(Messages.MessageTypeSave, ExtentionMethods.GetEnumDescription(SystemEnum.Category.Coffin.GetHashCode() == model.CategoryId ? SystemEnum.EntityType.CoffinItem : SystemEnum.EntityType.CasketItem));
        this.TempData["status"] = SystemEnum.MessageType.success.GetHashCode();
        return this.RedirectToAction("Index", "Coffin", new { categoryId = model.CategoryId });
    }
}

UploadFile Method
public static string UploadFile(string uploadDir, HttpPostedFileBase file)
{
    string fileName = string.Empty;
    try
    {
        if (file != null && file.ContentLength > 0)
        {
            DateTime dt = DateTime.Now;
            string second = dt.Day + "_" + dt.Month + "_" + dt.Year + "_" + dt.Hour + "_" + dt.Minute + "_" + dt.Second;
            fileName = Path.GetFileNameWithoutExtension(file.FileName) + second + Path.GetExtension(file.FileName);
            string serverPath = HttpContext.Current.Server.MapPath(@"~/Upload/");
            string filePath = Path.Combine(serverPath, uploadDir, fileName);
            if (!Directory.Exists(Path.Combine(serverPath, uploadDir)))
            {
                Directory.CreateDirectory(Path.Combine(serverPath, uploadDir));
            }

            file.SaveAs(filePath);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }

    return "/Upload/" + uploadDir + "/" + fileName;
}

Web.config
<system.web>
    // other stuff
    <httpRuntime targetFramework="4.5.1" maxRequestLength ="2097151"/>
</system.web>
<system.webServer>
    <security>
        <requestFiltering>
            <!-- Limit file uploads to 55MB -->
            <requestLimits maxAllowedContentLength="57671680"/>
        </requestFiltering>
    </security>
</system.webServer>

What to do with this problem ?

A: I have faced the same issue in the past. Now I am using Http-Multipart-Data-Parser, where all images are merged in the single stream object.
Refer this page: https://github.com/Vodurden/Http-Multipart-Data-Parser
public string UploadImages(Stream imgstram)
    {
        var parser = new MultipartFormDataParser(imgstram);
        foreach (var file in parser.Files)
        {
            //file => stream of single image.
            //convert stream to image
        }
    }


text:
Q: How to pass number of "column names" and "values" for a where claues for a select query in a stored procedure dynamically..? CREATE OR REPLACE PROCEDURE test_attendee (
    out_chr_err_code   OUT                VARCHAR2,
    out_chr_err_msg    OUT                VARCHAR2,
    out_attendee_tab   OUT                return_attendee_arr_result,
    in_from_date       IN                 VARCHAR2,
    in_to_date         IN                 VARCHAR2,
    in_location        IN                 VARCHAR2,
    in_keys            char_array,
    in_values          char_array
) IS

    l_chr_srcstage        VARCHAR2(200);
    l_chr_biqtab          VARCHAR2(200);
    l_chr_srctab          VARCHAR2(200);
    l_chr_bistagtab       VARCHAR2(200);
    l_chr_err_code        VARCHAR2(255);
    l_chr_err_msg         VARCHAR2(255);
    l_out_chr_errbuf      VARCHAR2(2000);
    lrec                  return_attendee_report;
    l_num_counter         NUMBER := 0;
    l_sort_column         VARCHAR2(30) := lower(in_sort_column);
    l_order_by            VARCHAR2(10) := lower(in_order_by);
    l_location_id         VARCHAR2(256) := in_location;
    l_start_row           NUMBER := l_start_row_num;
    l_end_row             NUMBER := l_end_row_num;
    l_keys                char_array := in_keys;
    l_values              char_array := in_values;
    CURSOR cur_attendee_data IS
    SELECT
        r.id              request_id,
        TO_CHAR(a.event_date, 'MM/DD/YYYY') startdate,
        r.customer_name   customer_name,
        r.country         country,
        r.duration        duration,
        r.customer_name   ext_att_customer_company,
        c.first_name      ext_att_first_name,
        c.last_name       ext_att_last_name
    FROM
        bi_request r
        LEFT JOIN bi_request_activity_day a ON a.request_id = r.id
        LEFT JOIN bi_request_catering_activity b ON b.request_activity_day_id = a.id
        LEFT JOIN bi_request_attendees c ON c.request_id = r.id
        LEFT JOIN bi_request_act_day_room d ON d.request_activity_day_id = a.id
                                               AND d.room = b.room
    WHERE
        r.state = 'CONFIRMED'
        AND a.event_date BETWEEN l_start_date AND l_end_date
        AND r.location_id = l_location_id
        AND country IN (
            SELECT
                column_value
            FROM
                TABLE ( l_values
                --dynamic array here
                 )
        )
        AND room IN (
            SELECT
                column_value
            FROM
                TABLE ( l_values
            --dynamic array here
                 )
        )
        -- like the above where clause condition I need to add columns and values dynamically ;
        ;

    TYPE rec_attendee_data IS
        TABLE OF cur_attendee_data%rowtype INDEX BY PLS_INTEGER;
    l_cur_attendee_data   rec_attendee_data;
BEGIN
out_attendee_tab := return_attendee_arr_result();
OPEN cur_attendee_data;
LOOP
  FETCH cur_attendee_data BULK COLLECT INTO l_cur_attendee_data;
  EXIT WHEN l_cur_attendee_data.count = 0;
  dbms_output.put_line('here in first insert');
  lrec := return_attendee_report();
  out_attendee_tab := return_attendee_arr_result(return_attendee_report());
  out_attendee_tab.DELETE;
   FOR i IN 1..l_cur_attendee_data.count LOOP
  BEGIN
  l_num_counter := l_num_counter + 1;
  lrec := return_attendee_report();
  lrec.requestid := l_cur_attendee_data(i).request_id;
  --some code here
  IF l_num_counter > 1 THEN
  out_attendee_tab.extend();
  out_attendee_tab(l_num_counter) := return_attendee_report();
  ELSE
  out_attendee_tab := return_attendee_arr_result(return_attendee_report());
  END IF;
  out_attendee_tab(l_num_counter) := lrec;
  EXCEPTION
  WHEN OTHERS THEN
  dbms_output.put_line('Error occurred : ' || sqlerrm);
            END;
        END LOOP;

    END LOOP;

EXCEPTION
    WHEN OTHERS THEN
        dbms_output.put_line('HERE INSIIDE OTHERS' || sqlerrm);
END;

I need to add filters dynamically, a user has to pass column names and values for each filed. how to map column name with values array.
Input for example:
 {'column_1,value1,value2,value3',
  'column_2,value1,value2,value3',
  'column_3,value1,value2,value3'}

How to handle it dynamically? Thanks in advance.

A: You can try and open a cursor for a dynamic query as a String.
CREATE OR REPLACE PROCEDURE test_attendee (
    out_chr_err_code   OUT                VARCHAR2,
    out_chr_err_msg    OUT                VARCHAR2,
    out_attendee_tab   OUT                return_attendee_arr_result,
    in_from_date       IN                 VARCHAR2,
    in_to_date         IN                 VARCHAR2,
    in_location        IN                 VARCHAR2,
    in_keys            char_array,
    in_values          char_array
) IS

    l_chr_srcstage        VARCHAR2(200);
    l_chr_biqtab          VARCHAR2(200);
    l_chr_srctab          VARCHAR2(200);
    l_chr_bistagtab       VARCHAR2(200);
    l_chr_err_code        VARCHAR2(255);
    l_chr_err_msg         VARCHAR2(255);
    l_out_chr_errbuf      VARCHAR2(2000);
    lrec                  return_attendee_report;
    l_num_counter         NUMBER := 0;
    l_sort_column         VARCHAR2(30) := lower(in_sort_column);
    l_order_by            VARCHAR2(10) := lower(in_order_by);
    l_location_id         VARCHAR2(256) := in_location;
    l_start_row           NUMBER := l_start_row_num;
    l_end_row             NUMBER := l_end_row_num;
    l_keys                char_array := in_keys;
    l_values              char_array := in_values;
    CURSOR cur_attendee_data SYS_REFCURSOR;

    TYPE rec_attendee_data IS
        TABLE OF cur_attendee_data%rowtype INDEX BY PLS_INTEGER;
    l_cur_attendee_data   rec_attendee_data;

    v_query CLOB; --> You can declare even as VARCHAR2 if you know that the size of the query will not increase
BEGIN
    out_attendee_tab := return_attendee_arr_result();

    v_query := 'SELECT
        r.id              request_id,
        TO_CHAR(a.event_date, ''MM/DD/YYYY'') startdate,
        r.customer_name   customer_name,
        r.country         country,
        r.duration        duration,
        r.customer_name   ext_att_customer_company,
        c.first_name      ext_att_first_name,
        c.last_name       ext_att_last_name
    FROM
        bi_request r
        LEFT JOIN bi_request_activity_day a ON a.request_id = r.id
        LEFT JOIN bi_request_catering_activity b ON b.request_activity_day_id = a.id
        LEFT JOIN bi_request_attendees c ON c.request_id = r.id
        LEFT JOIN bi_request_act_day_room d ON d.request_activity_day_id = a.id
                                               AND d.room = b.room
    WHERE
        r.state = ''CONFIRMED''
        AND a.event_date BETWEEN l_start_date AND l_end_date
        AND r.location_id = l_location_id
        AND country IN (
            SELECT
                '|| column_value || '
            FROM
                TABLE ( l_values
                '|| dynamic_array_here || '
                 )
        )
        AND room IN (
            SELECT
                '|| column_value || '
            FROM
                TABLE ( l_values
            '|| dynamic_array_here || '
                 )
        )';

    OPEN cur_attendee_data FOR v_query;
    LOOP
      FETCH cur_attendee_data BULK COLLECT INTO l_cur_attendee_data;
      EXIT WHEN l_cur_attendee_data.count = 0;
      dbms_output.put_line('here in first insert');
      lrec := return_attendee_report();
      out_attendee_tab := return_attendee_arr_result(return_attendee_report());
      out_attendee_tab.DELETE;
       FOR i IN 1..l_cur_attendee_data.count LOOP
      BEGIN
      l_num_counter := l_num_counter + 1;
      lrec := return_attendee_report();
      lrec.requestid := l_cur_attendee_data(i).request_id;
      --some code here
      IF l_num_counter > 1 THEN
      out_attendee_tab.extend();
      out_attendee_tab(l_num_counter) := return_attendee_report();
      ELSE
      out_attendee_tab := return_attendee_arr_result(return_attendee_report());
      END IF;
      out_attendee_tab(l_num_counter) := lrec;
      EXCEPTION
      WHEN OTHERS THEN
      dbms_output.put_line('Error occurred : ' || sqlerrm);
                END;
            END LOOP;

        END LOOP;

    EXCEPTION
        WHEN OTHERS THEN
            dbms_output.put_line('HERE INSIIDE OTHERS' || sqlerrm);
END;

*Note: This method might drop in performance if you are using this in a transactional table.

A: create or replace FUNCTION fn_json_to_array (
    json_doc    IN          VARCHAR2,
    in_column   IN          VARCHAR2
) RETURN char_array AS

    x               char_array;
    company_array   VARCHAR2(100);
    varpath         VARCHAR2(30);
    v_query_str     VARCHAR2(4000);
BEGIN
    varpath := in_column;
    v_query_str := 'SELECT
        JSON_VALUE('''
                   || json_doc
                   || ''',  ''$.'
                   || varpath
                   || ''')
    FROM
        dual';
    EXECUTE IMMEDIATE v_query_str
    INTO company_array;
    SELECT
        fn_varchar_to_array(company_array)
    INTO x
    FROM
        dual;

    RETURN x;
END fn_json_to_array;

By passing JSON as a string and convert it as an array.
EX:-json_doc := '{
          "country"      : "India,American Samoa",
          "room"      : "101",
}';


text:
Q: Immediately invoked function expression for setTimeout doesn't work I'm trying to wrap a setTimeout in an immediately invoked function expression which creates the function, which then calls itself again as above, and automatically starts the loop:
Here is the reference:  enter link description here
For some reason it runs once and then stopped.
//Spaceship move
function spaceShipMove(spaceShipToMove){

    var randomY = Math.floor(Math.random());
    spaceShipToMove.style.webkitTransform = 'translate(-3000px, ' + randomY + 'px)';
}
  //Spaceship
    var spaceShipsList = createMultipleSpaceShips(500);
    for (var i = 0; i < spaceShipsList.length; i++){
        var aSpaceShip = spaceShipsList[i];
        app.dom.mainWrapper.appendChild(aSpaceShip);

        (function t() {
            setTimeout(function (spaceShipGo) {
                spaceShipMove(spaceShipGo);
            }, i * 300, aSpaceShip)
        })();

A: try this
for (var i = 0; i < spaceShipsList.length; i++){
 var aSpaceShip = spaceShipsList[i];
 app.dom.mainWrapper.appendChild(aSpaceShip);

 setTimeout(spaceShipMove.bind(null, aSpaceShip), i * 300)
}


text:
Q: Windows 7 Clean Install: Installing Driver trough Windows Update or Manually Whenever i doing clean install of my Thinkpad T410, i'm always wondering if it is better to use Lenovo's own tools (Thinkvantage System Update), or Windows Update to install drivers (Graphic Driver, Network, Display,..).
Previously, i always thought that installing driver trough vendor-specific tools like Thinkvantage System Update provides better quality, since they do test for specific device target. But, since this tool installs so much bloat and had some issues (these tools must be installed manually, eventhough i had checked it with the others), i'm questioning the quality of OEM to provide the drivers.
Which one do you think is better? What i need is bare-essential drivers for my Windows, not some Graphical Utilities nonsense

A: It depends on your goals. Do you just want a driver, do you want the most up to date driver, or do you want the driver and additional bloatware?
For some things the additional bloatware is actually nice. E.g. some wireless drivers come with a nice interface, while the bare XP interface is annoyingly minimal.
For other items the branded drivers are often older than the one provided by the manufacturer. E.g. graphics drivers which rarely get an update, and where the Bvidia or AMD drivers may have years of improvements over the old branded drivers.
Thus the best *1 solution seems to be a mix of those options.

*1 Alsways fun to the 'best'.

A: Well, I had the vary question you asked an year back. But, some research gave me an optimum solution. See, basically all the stuff that comes with laptop, from manufacturer, can be classified into three categories,

*

*Device drivers,

*Utilities,

*Software/Applications,

In above three, 3rd category is what we can call BLOATWARE for sure. So, I'd recommend just to ignore this category. But, first and second category is actually something you should install, because the drivers and utilities are optimized for your laptop model. They do consist some tweaks and modifications that are best suited to your machine.
I also used to install drivers from hardware manufacturers instead of laptop manufacturers. But the outcome was little different.

*

*I installed Bluetooth and WiFi drivers from respective hardware manufacturers, but then I realized, Sony (since I own Vaio) provided this little utility, VAIO Smart Network, that allowed me to switch on/off either of two wireless services, Bluetooth and WiFi or both from my taskbar, which was indeed helpful when energy saving comes into picture.

*Then this another time, I got new Vaio with Sandy Bridge CPU and a discreet AMD GPU. When I installed drivers from AMD, I realized that I can not switch between AMD's discreet GPU and Sandy Bridge's Intel HD3000, which is essential for both performance and again energy saving cases, which was available when I installed drivers specifically designed for my Vaio from its support page.

*These Vaios come with some stupid application by Sony, VAIO Gate, which is indeed an eye-candy, that little glob hanging from top of the screen, but it occupies memory, and also takes lot of time to boot up. So I simply removed it.

All in all, I'd recommend you to install only drivers and utilities from laptop manufacturer and ignore the applications from them.
Hope it helps.

A: please note that Windows Update download the drivers you can find on producers website (e.g. nVidia drivers are shown on windows update usually one day after the official pubblication)
However, if you have updated driver from your hardware producer, use always those drivers.


text:
Q: After login pull data for respective users from db M building a web app here.The authentication php code looks like this  (Please ignore the threats for time being) :

<?php
session_start();

if(isset($_POST['submit']))
{
 mysql_connect('localhost','*****','******') or die(mysql_error());
 mysql_select_db('cl29-demodb') or die(mysql_error());
 $name=$_POST['name'];
 $pwd=$_POST['password'];
 if($name!='' && $pwd!='')
 {
   $query=mysql_query("select * from EmployeeTable where EmployeeName ='".$name."' and password='".$pwd."'") or die(mysql_error());
   $res=mysql_fetch_row($query);
   if($res)
   {
     $_SESSION['id']=$res['id'];

 header('location: profileindex.php');
   }
   else
   {
    echo "user name and password are incorrect" ;
 echo "<a href=index.php> click here to go back </a>";
   }
 }
if(!isset($_SESSION['id'])){
echo "Sorry, Please login and use this page";
exit;
}
}
?>

I am able to login successfully and reach the profile of the user.But I want the profile to display only the information for respective users.The profile looks like this:

I have written the php to retrive the name,designation,weekly points,overall points,weekly rank and overall rank respectively.

I tried to echo the variables in the html.
But I am not able to do so.It isnot pulling any data.I have column for all the above fields in the table.

Kindly help.

A: May be this is the cause
mysql_fetch_row() return the numeric array and you are accessing as $res['id']
either replace mysql_fetch_row with mysql_fetch_array or try numeric index of your id
$_SESSION['id']=$res[0]; or $_SESSION['id']=$res[1];

A: use mysqli_fetch_assoc so you could call the columns by name if you are using mysql_fetch_array you should call the columns by their index no the by the column name.

A: There is no need to start a session again in the profileindex.php as the session has already started in the login page.
print the sql and run it in the backend to check if you are getting the desired result in order to further debug this.


text:
Q: Stop RTC baseline from being delivered I created a baseline in my workspace and forgot I had some undelivered changes. These changes are not supposed to be part of the baseline.
The changes and baseline have not been delivered to the stream, is there anyway to get rid of this undelivered baseline and undelivered changes?
Would deleting the workspace and creating a new one work?

A: This thread is clear:

Both the internals and the users of RTC SCM system depend on the fact that a baseline is immutable.
  A baseline is visible (via various search menus) as soon as it is created, so it would not be safe to change the content of a baseline, even if you haven't yet delivered it.
  That is why RTC makes it very fast and cheap to create a new baseline whenever you need one.
BUT I agree that you should be able to:

*

*drop a baseline from your outgoing changes list in the Pending Changes view (Story 18512: Discard a baseline: nothing done yet 8 years later) and:

*hide/archive a baseline:

*

*Enhancement 170855: Provide the ability to hide (archive) baselines that are no longer needed, 2011, reformulated in

*Enhancement 169438: Need true database archive and restore capability for work items and SCM objects: 2011, itself encompassed in

*Enhancement 294112: Archival techniques and tools: 2013.
Nothing is done yet.

So try simply to:

*

*rename your current baseline with a name which makes it clear it is not meant to be used,

*create a new baseline including only the change sets you want

*deliver both baselines


text:
Q: Is there a way of constraining a generic type to be a member of a set of types? I have the following record
type RecordPath<'a,'b> = {
    Get: 'a -> 'b
    Path:string
}

I want to constrain 'b to be a member of the set of types that can naturally be represented in a relational database column (int; string; DateTime; etc).
I could use a class instead of a record with a private constructor and some static creator methods that only cater for the types I care about. But I was wondering if there is a way to do this with a record.
I also considered extending the types I want to allow with something like this
type String with static member CanBeUsedInRecordPath = true

And then use SRTPs for all functions that operate on a RecordPath, but then it is technically possible (although unlikely) for someone to decide to extend some type I don't want to support with that extension method.
So is a class with a private constructor the only way to do this in F#?

A: The following seems to satisfy my requirements.
module RecordPath =
    type RecordPath<'a, 'b> = private {
        Get: 'a -> 'b
        Path:string
    }
    with
        static member Create (f: 'a -> string) = {Get = f; Path = "not important for this demo"}
        static member Create (f: 'a -> int) = {Get = f; Path = "not important for this demo"}
        static member Create (f: 'a -> DateTime) = {Get = f; Path = "not important for this demo"}

I'll wait a bit before accepting this as the answer in case someone comes up with a better way.


text:
Q: wp_enqueue_style not loading CSS I am attempting to load a script using wp_enqueue_style following the advice on the Wordpres Codex, but the script doesn't seem to be included in the source. Is this the correct way to do it?
    function load_scripts() {
        wp_enqueue_style('bootstrap.css', get_template_directory_uri() . '/css/bootstrap.min.css');
    }
    add_action('wp_enqueue_scripts', 'load_scripts');

A: *

*Okay, first step is to ensure you are using the correct path of the CSS file.
Add the following line in the functions.php of your theme or other appropriate place.
 print( get_template_directory_uri() . '/css/bootstrap.min.css' );

This should print the URL of your desired stylesheet on top of the page. Copy and paste this URL in a new tab, if it opens a stylesheet then you are good to go. Otherwise, there is a mistake in the path.

*Second step is to ensure that wp_head() is being called on the page you are displaying. It can be placed in your header template or top of archives/post files etc. This function actually renders the styles and scripts on the page.
Without wp_head(), its basically useless to enque anything as you can add links and scripts manually if you know the exact paths.

A: Note that in admin mode there is a special hook 'admin_enqueue_scripts'. So, if there is need to load CSS in both modes, it should be done on two hooks.
function load_scripts() {
    wp_enqueue_style('bootstrap.css', get_template_directory_uri() . '/css/bootstrap.min.css');
}

add_action('wp_enqueue_scripts', 'load_scripts');
add_action('admin_enqueue_scripts', 'load_scripts');

A: You are trying to enqueue style on wp_enqueue_scripts  hook.
Try wp_print_styles.
add_action('wp_print_styles', 'load_scripts');

Also try to register style, first.

A: Your action and function looks fine from here. The wp_enqueue_scripts hook should work perfectly for both stylesheets and scripts.
Have you tried echoing something out in the function to see if it's actually being called at all? I.e:
    function load_scripts() {
        echo "Does this output to the actual page?";
        wp_enqueue_style('bootstrap.css', get_template_directory_uri() . '/css/bootstrap.min.css');
    }
    add_action('wp_enqueue_scripts', 'load_scripts');

If it's not, you might have a problem with your placement of the code, but if you keep everything in functions.php and outside of any other scope this shouldn't be a problem.
Another thing that can cause this behaviour is if you have already registered a stylesheet or script with the same handle ("bootstrap.css" in this case). The first argument in the wp_enqueue_style() function is just a handle for internal dependency management and should be unique, try renaming it to something else and see if that fixes your problem.

A: in case you don't want to use wp_head(); in your template, you could also include your styles directly:
<link rel="stylesheet" href="<?php echo get_theme_file_uri( 'style.css' ); ?>">

beware though: wp_head() includes tons of stuff (scripts, styles,...), by wordpress itself as well as most plugins, so only omit it if you know what you're doing.

A: Register the style first:
function register_plugin_styles() {
    wp_register_style('my-plugin', plugins_url('my-plugin/css/plugin.css'));
    wp_enqueue_style('my-plugin');
}

http://codex.wordpress.org/Function_Reference/wp_register_style
Do that way. Dont try to enqueue directly. And put code into functions.php of course.

A: Fist confirm path of the css file is correct or not if is it a correct try with below code :
  function load_scripts() {
    wp_enqueue_style('load-custom-css-new', get_template_directory_uri() . '/css/bootstrap.min.css');
}
add_action('wp_enqueue_scripts', 'load_scripts');

or Go with this URL.
https://developer.wordpress.org/reference/functions/wp_enqueue_style/

A: I had the same problem. Although I have implemented this many times before, I lost many hours to find out what went wrong with this.
Because I made my own themes, I had declared this file unit as "fuctions.php" (I lost the -n- letter).
So, besides all the things described above you should also consider, take a good look at the file name and confirm that is "functions.php" (not fuctions, not function etc).
This might be also the reason for you.

A: I had the same issue. I fixed it by hard refreshing the page with Ctrl + F5 to clear cache and the css loaded normally.

A: If you are protecting the directory with .htpasswd, the https call generated by get_stylesheet... will fail, and you might lose some time chasing that one.


text:
Q: Unreduced Hessenberg matrix QR factorization by Givens I have the following assignment question, but I can't seem to be able to do it. Can somebody guide me through?
Let $A_{1} \in \mathbb{R}^{n \times n}$ be an unreduced Hessenberg matrix. Given $\mu\in \mathbb{R}$, which is an eigenvalue of $A_{1}$.
We compute the QR factorization $A_{1} - \mu I = Q_1R_1$ by Givens rotations. Then we compute $A_{2} = R_1Q_1 +\mu I $.
a) Show that $R_{1}(n,n) = 0$.
b) Show that the last row of $A_2$ is $[0, ..., 0, \mu ]$. Thus from this we see $\mu$ is an eigenvalue of $A_{2}$ too.
c) Show that $A_{2}(i+1, i)) \neq 0$ for $i = 1 : n-2$.\
d) Suppose there is another orthogonal $\hat{Q_{1}} \in \mathbb{R}^{n \times n}$ such that $\hat{Q_{1}}e_{1} = \pm Q_{1}e_{1}$ and $\hat{A_{2}} = \hat{Q_{1}}^{T}A_{1}\hat{Q_{1}}$ is also Hessenberg. Show that $\hat{Q_{1}}e_{i} = \pm Q_{1}e_{i}$ for $i = 2 : n$ and $\hat{A_{2}} = DA_{2}D$, where $D = diag(\pm 1, ..., \pm 1)$.

A: If $ \mu $ is an eigenvalue of $ A_1 $, then $ 0 $ is an eigenvalue of $ A_1 - \mu I $.  But that means $ A_1 - \mu I $ is singular.  What does that mean about the QR factorization of $ A_1 $?  What does that mean about the QR factorization of $ A_1 $ given that $ A_1 $ is unreduced?  (Meaning it has no zeroes on the subdiagonal)?   The answer to this should get you past a).
Parts b) and c) are then a matter of thinking of what happens when you apply the Givens rotations in the appropriate order to an upper triangular matrix that has a zero in the n,n entry.
For part d), get your inspiration from the "implicit Q" theorem.


text:
Q: Ubuntu 13.04 RAOP to Airport Express 2nd Generation doesn't work, how do I debug and get it working? I have never had any luck with RAOP or Stream2Ip from Ubuntu 12.04 or 13.04 to my airport express 2nd generation.
In pulseaudio the airplay device either discovered by RAOP in paprefs or connected to by stream2ip appears and is selectable. However, when I start to play audio from VLC or Rhythmbox the players just sit there. The play button is "pressed" and the pause icon appears but the track doesn't start playing it just 'sits there'. No audio at all. If I change the output back to local speakers then the track starts playing.
It's frustrating to say the least, no one else seems to report this issue.
How can I debug what is going awry?

A: Unfortunately we do not have an Airport Express 2nd generation to test and debug this here. In case the old RAOP protocol is still recognized and supported by this device we may however be successful in streaming audio.

*

*With my old 1st generation Airport Express I was able to reproduce the behaviour of your player stopping playback after I added a wrong port to the IP of the device.

*In newer Airport Express devices it was possible to change the port the device listens to from default 5000 to any other port. That is why stream2ip >= 0.3.4 supports streaming via a port different to default 5000 (as was in 1st generation devices). You can do so by adding this port to the IP of the device:
192.168.xxx.xxx:<port>

Let me therefore suggest you find the port of your device (best from the setup programm run from Windows or MacOS) and try if adding this port to the IP line resolves the issue.
We can not however provide a solution for devices where the stream is set up to be password protected and hence needs encryption (this encryption is not open source).
We also can not support the newer RAOP2 protocol used in newer AirPlay devices as it still is not available for pulseaudio.


text:
Q: Changing Cortana system settings I'd like to change the Cortana system settings specifically the 'Hey Cortana' setting.
However, the two most relevant resources (Windows universal samples and WinAPI function for system settings) don't appear to show any way to change these settings.
Perhaps I haven't looked at SystemParametersInfo hard enough or it doesn't support Cortana settings. So I wonder, is there any way to programmatically change these settings?


text:
Q: Awesomium WebControl Hang I have a tabcontrol and in the tabcontrol I have two tabitems, and both of them contain an awesomium Webcontrol. However after some random time the Webcontrols don't display anything.  When I try to call a method on them I get an InvalidOperationExcepion which tells me: "This IWebView instance is invalid. It has either been destroyed or it was never properly instantiated."
Why is that? Am I Missing some extra configuration?

A: Tuned out it was an Awesomium bug, it was fixed.


text:
Q: connect/pair gopro Hero 4 camera using python I am trying to use the python library for the GoPro API and I am new to this. I searched everywhere online and all posts seem to assume your camera is already paired with the computer. How do I connect my GoPro camera to the computer (wifi, USB?) so I can start talking to it via the python API ? I started by executing the following commands:
from goprocam import GoProCamera
from goprocam import constants
gpCam = GoProCamera.GoPro()

I get an error on line three and I assume it's because the camera is not yet connected to he computer.

A: developer of gopro-py-api here. You need to turn on WiFi on your GoPro Camera, to App mode/Smartphone mode not Remote mode, then connect your camera to your computer via WiFi. Then run the commands again.


text:
Q: Generar un gráfico en ggplot2 Necesito ayuda por favor, al cargar el ggplot2 me sale esto: Error: package or namespace load failed for 'ggplot2' in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]):
namespace 'rlang' 0.4.12 is already loaded, but >= 1.0.0 is required
gracias


text:
Q: How to request for more 100 device in wso2iot? How to increase the offet and limit more than 100 ? At present we are unable to request more than 100 limit. Can you please help me ???

A: Pagination works like below;
 - offset =   0, limit = 100 ->   0-100 devices
 - offset = 101, limit = 100 -> 100-200 devices
 - offset = 201, limit = 100 -> 200-300 devices
 - ....continues....

As you can see above limit can be a positive integer(less than 100). Most of the time limit is constant, and we keep increasing the offset for the next API calls.
For example;
let offset = 0 limit = 100 when starting; you can do offset = offset + limit for the next call.
- https://192.168.1.18:8243/api/device-mgt/v1.0/devices?offset=0&limit=100
- https://192.168.1.18:8243/api/device-mgt/v1.0/devices?offset=101&limit=100
- https://192.168.1.18:8243/api/device-mgt/v1.0/devices?offset=201&limit=100


text:
Q: Python: Keyword to Links I am building a blog on Google App Engine. I would like to convert some keywords in my blog posts to links, just like what you see in many WordPress blogs.
Here is one WP plugin which do the same thing:http://wordpress.org/extend/plugins/blog-mechanics-keyword-link-plugin-v01/
A plugin that allows you to define keyword/link pairs. The keywords are automatically linked in each of your posts.
I think this is more than a simple Python Replace. What I am dealing with is HTML code. It can be quite complex sometimes.
Take the following code snippet as an example. I want to conver the word example into a link to http://example.com:
Here is an example link:example.com

By a simple Python replace function which replaces example with example, it would output:
Here is an example link:<a href="http://example.com">example.com

but I want:
Here is an example link:example.com

Is there any Python plugin that capable of this? Thanks a lot!

A: This would probably be better suited to client-side code. You could easily modify a word highlighter to get the desired results. By keeping this client-side, you can avoid having to expire page caches when your 'tags' change.
If you really need it to be processed server-side, then you need to look at using re.sub which lets you pass in a function, but unless you are operating on plain-text you will have to first parse the HTML using something like minidom to ensure you are not replacing something in the middle of any elements.

A: This is roughly what you could do using Beautifulsoup:
from BeautifulSoup import BeautifulSoup

html_body ="""
Here is an example link:example.com
"""
soup = BeautifulSoup(html_body)
for link_tag in soup.findAll('a'):
    link_tag.string = "%s%s%s" % ('|',link_tag.string,'|')
for text in soup.findAll(text=True):
    text_formatted = ['example'\
    if word == 'example' and not (word.startswith('|') and word.endswith('|'))\
    else word for word in foo.split() ]
    text.replaceWith(' '.join(text_formatted))
for link_tag in soup.findAll('a'):
    link_tag.string = link_tag.string[1:-1]
print soup

Basically I'm stripping out all the text from the post_body, replacing the example word with the given link, without touching the links text that are saved by the '|' characters during the parsing.
This is not 100% perfect, for example it does not work if the word you are trying to replace ends with a period; with some patience you could fix all the edge cases.


text:
Q: react value is undefined when the value is clearly not empty

   console.log(e.target.value)}>
  <audio loop autoPlay></audio>

I am stupid, why is this not working.

A: i elements have no value property, they have textContent and innerHTML, but no value. value is only for form elements. The value attribute you have on i is an invalid attribute, and isn't reflected by a property. You could use e.target.getAttribute("value"), but value would still be invalid.
With more context, we might be able to give you a more React-specific answer (you probably have an in-scope variable containing the value you could just use directly), but in the absense of more context, here's a baseline answer:
You can use a data-* attribute and access that value either with e.target.getAttribute("data-value"):

   console.log(e.target.getAttribute("data-value"))}>
  <audio loop autoPlay></audio>

...or with dataset (e.target.dataset.value):

   console.log(e.target.dataset.value)}>
  <audio loop autoPlay></audio>


text:
Q: Drawing on Leaflet map give incorrect coordinate I am using Leaflet and OpenLayers. When I draw a bounding box I am getting the correct lat and lon if I use OpenStreetMap tilelayer.  When I switch to using EarthData tilelayer the bounding box is incorrect. Map
Using this layer bring incorrect bounding box
 L.tileLayer('//gibs-{s}.earthdata.nasa.gov/wmts/epsg4326/best/MODIS_Terra_CorrectedReflectance_TrueColor/default/'+tile_date+'/EPSG4326_250m/{z}/{y}/{x}.jpg

gives correct bounding box.
 L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png

A: Thanks for all the help.  I changed the tileLayer to use the default projection for leaflet //gibs-{s}.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_CorrectedReflectance_TrueColor/default/'+tile_date+'/EPSG3857_250m/{z}/{y}/{x}.jpg


text:
Q: Is it possible for manually to add crashlytics frame and it working I'm added Crashlytics for my iOS app. I downloaded  framework from it via their site link, and went through all the steps for integrating the frameworks, adding the run script, etc.but problem is that i add framework in manually and not receiving a email.

A: Did you follow the instructions mentioned here to manually add the Crashlytics SDK?
Did you also integrate the Firebase SDK?
To use Firebase Crashlytics, you also need to install the Firebase SDK along with the related configuration. E.g. Installing the GoogleService-Info.plist file and the initialization code.
Once you do this, you will need to cause a crash. For this, you need to run the app, stop Xcode, and from the device run the app and cause the crash. Then you will need to run the app again from the device. If everything was done correctly, then you should see the report in your Crashlytics console.


text:
Q: Combine two queries to count distinct strings with different filters I am trying to write a single Postgres query that will result in a table which looks like this:
source |yes_gap|no_gap|
-------|-------|------|
allivet|     29|    25|
amazon |    692|   255|

I've been able to write two separate queries, but haven't been able to figure out how to combine them into one.
Here's my query for product_gap='yes':
select
source,
count(distinct(sku)) as yes_gap
from product_gaps where
product_gap='yes' and
ingestion_date <= '2021-05-25'
/* aggregate by source */
group by source

Result:
source |yes_gap|
-------|-------|
allivet|     29|
amazon |    692|

And here's my query for product_gap='no':
select
source,
count(distinct(sku)) as no_gap
from product_gaps where
product_gap='no' and
ingestion_date <= '2021-05-25'
/* aggregate by source */
group by source

Result:
source |no_gap|
-------|------|
allivet|    25|
amazon |   255|

Can I get both counts in a single query?

A: Much faster and simpler with conditional aggregates using the aggregate FILTER clause:
SELECT source
     , count(DISTINCT sku) FILTER (WHERE product_gap = 'yes') AS yes_gap
     , count(DISTINCT sku) FILTER (WHERE product_gap = 'no')  AS no_gap
FROM   product_gaps
WHERE  ingestion_date <= '2021-05-25'
GROUP  BY source;

See:

*

*Aggregate columns with additional (distinct) filters
Aside 1: DISTINCT is a key word, not a function. Don't add parentheses for the single column. distinct(sku) is short notation for DISTINCT ROW(sku). It happens to work because Postgres strips the ROW wrapper for a single column, but it's just noise.
Aside 2: product_gap should probably be boolean.

A: You did 95% of the work , it just remains to join the 2 sources
 SELECT source, yes_gap,no_gap FROM
       ( select
    source,
    count(distinct(sku)) as yes_gap
    from product_gaps where
    product_gap='yes' and
    ingestion_date <= '2021-05-25'
    /* aggregate by source */
    group by source ) r1
       FULL OUTER JOIN
       ( select
    source,
    count(distinct(sku)) as no_gap
    from product_gaps where
    product_gap='no' and
    ingestion_date <= '2021-05-25'
    /* aggregate by source */
    group by source ) r2
       USING ( source )
       ORDER BY source;


text:
Q: evaluation of integral using residue theorem I do not fully understand how to use the residue theorem for evaluating integrals. Can someone evaluate the following integral using the residue theorem explaining step by step?
$$\int_\gamma \frac{e^{z\pi}}{z^2(z^2+2z+2)} \,dz$$
where $\gamma$ is circle of centre $0$ and radius $3$

A: *

*Find the zero of $z^2(z^2+2z+2)$.

*Find the residue at the zeroes of ${e^{z\pi}\over{z^2+2z+2}}$ multiply them by $2i\pi$  and add the result.


text:
Q: Pine Script: Exit strategy X bars after opening strategy I am trying to close a strategy either after it crosses above the MA or after 50 bars, whichever comes first
I have been trying to look into and it seems "barstate.isconfirmed" or "barsince" function should be used.
Currently I have the below, what do I need to add to include closing after 50 bars?
strategy.close("buy",when = close[0]>basis

A: You can use the strategy.opentrades.entry_bar_index built-in variable to get the bar index of the open trade. Then compare it with the current bar index.
n = 50
open_idx = strategy.opentrades.entry_bar_index(strategy.opentrades-1)
diff_idx = bar_index - open_idx

if (diff_idx >= n)
    strategy.close("buy")

A: For the 50 bars, use this with v5:
//Start counting after trade entry
barsSinceLastEntry() =>
    strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index
(strategy.opentrades - 1) : na

// Setup for closing the long position after 50 bars.
if barsSinceLastEntry() >= 50
    strategy.close("Long")

//Exit when greater than 50 bars after entering the trade
if barsSinceLastEntry() >= 50
    strategy.close("Long")


text:
Q: AngularJS Array keeps on updating after ngClick I have a lot of array stuff going on, I've managed to shorten it off and I've uploaded it on the link below.
http://www.asaadmahmood.com/asaad/edited/edit.php
You can view the code for my angular, the code is very short and can be seen in the file below:
http://www.asaadmahmood.com/asaad/edited/js/main.js
What I'm doing is I'm pushing the people titles inside an array called EventGroups.list; The reason I'm making this an array of objects is that I have a bunch of values and I need to access them by their specific key.
The checkboxes I click are added/subtracted from another array selectedGroupCri on ng-click on the checkbox themselves.
The issue here is that when I add an object inside the array the object gets added and the people get added too, however after adding them the people are linked by the checkboxes above even after being edited into the array. I would like to find a proper way of adding the people and then closing this link off between the two so when a person has created the object, those checkboxes can no longer interfere with it.
My markup is like this:

Select people *

            <input type="checkbox" value="{{criterion.title}}" ng-checked="selectedGroupCri.indexOf(criterion) > -1" ng-click="toggleCriSelection(criterion)">

{{criterion.title}}

    <input type="button" ng-click="groupAdd()" class="btn btn-default" value="Add Group">

{{group}}

A: When the "Add Group" button is clicked, you are calling the groupAdd() function. This presumably is defined in your EventCriCtrl controller. I suspect that in this function, you are pushing the current checked array into the $scope.groups array. However, this is just pushing a pointer to the object into the array. Instead, you need to make a copy of the array with Angular.copy() so that a deep copy is created that is no longer bound to the checkboxes.
If you're currently doing something like this:
 $scope.groups.push($scope.selectedCheckboxes);

Then you should change to something like:
 $scope.groups.push(angular.copy($scope.selectedCheckboxes));

if you post your controller code, I can see if this is the exact issue, and update the code accordingly.
UPDATE (Just looked at the source of the code you linked):
Where you have (in the $scope.groupAdd definition):
var criteria = $scope.selectedGroupCri;

change to:
var criteria = angular.copy($scope.selectedGroupCri);


text:
Q: Viewing Mathematica Demonstrations Project Code I hope I am going insane and the I'm not seeing the snake about to bite me...
How does one view the code in the demonstration projects that one can download from wolfram.com?
It seems like all of them come down as an 'Authoring Notebook' and I cannot always get the notebook to show a view of the code the author used.
Some of the notebooks have the cells 'docked' and you can view the code by double clicking the cell. Others, do not show the icon on the cell brackets to open their content, but the demonstration still functions.
It appears the code is definitely available by looking at the plain text of the file.
Are authors encouraged to obfuscate the code in their demonstrations? If not please direct me to the snake...

A: Usually you can scroll down the cdf and find a "Download Source Code" button:

Clicking this button downloads another notebook where the code is explicitly visible.

A: On other browsers/platforms, you may see this:

and if you click on (preview) you'll see this:

although you can't copy this, because it's a GIF...

A: In order to see the code in the demonstration files, you simply click on the right bar of the section with the code, and select 'convert to input form'...
Then you can copy the entire code snippet and paste it into your new file, where it will then get syntax formatting & coloring.


text:
Q: MySQL EVENT error, PREPARE I need to move random numbers from column "car" to column "bar" every 10 minutes.
This my table:
+---+---+
|car|bar|
+---+---+
| 6 | 4 |
+---+---+
| 2 | 2 |
+---+---+

This my event
DROP EVENT IF EXISTS `tezzt`;
CREATE EVENT tezzt
ON SCHEDULE EVERY 1 MINUTE
STARTS CURRENT_TIMESTAMP
ENDS CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO

SET @sums := ROUND( (
RAND( ) * ( 100 -10 ) ) +10
);
SET @vcar := 'car';
SET @vbar := 'bar';
SET @sql = CONCAT( 'UPDATE wp_users SET
`', @vcar , '`=`', @vcar , '`-', @sums,',','
`', @vbar , '`=`', @vbar, '`+', @sums
) ;
PREPARE stmt FROM @sql ;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

And this my error
Error

SQL query:

PREPARE stmt FROM @sql ;

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL' at line 1

@vcar and @vbar variables are very much needed. please, help


text:
Q: xBIM Viewer: Create a screenshot from canvas I am using xBim Toolkit (http://docs.xbim.net/) for 3D object rendering and there was a requirement to create a screenshot of the current scene on button click.
xBim is using canvas for graphical representation of the object.
The entire project is based on C#, .NET tools and Javascript, so this is the range of the tools that can be used for solving this.
I have already tried by using html2canvas (https://html2canvas.hertzen.com/) and dom-to-image (https://github.com/tsayen/dom-to-image) libraries, but also tried with default canvas methods (like myCanvas.toDataUrl() or myCanvas.toBlob()).
All of them produce just an empty image with black or white background, but no xBim object is saved.
The only way I can get any useful screenshot is by using System.Drawing.Graphics and then creating a screenshot of the whole screen (which is not the best implementation for many reasons).
public static void MakeScreenshot()
{
    var x = Math.Abs(WebBrowser.MousePosition.X);
    var y = Math.Abs(WebBrowser.MousePosition.Y);
    var bounds = Screen.FromPoint(new Point(x, y)).Bounds;

    Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height);

    Graphics graphics = Graphics.FromImage(bitmap as System.Drawing.Image);
            graphics.CopyFromScreen(25, 25, 25, 25, bitmap.Size);

    string screenshotFilePath = Path.Combine(DirectoryPath, "Screenshot.jpg");

    bitmap.Save(screenshotFilePath, ImageFormat.Jpeg);
}

I would like to have screenshot of only canvas area.
It is not important if its implemented by using Javascript or C# code (even with System.Drawing.Graphics, but to cut only part of the screen)

A: If you are using xBim Toolkit as described in question, you need to know that internally it using WebGL for object representation.
In order to take a screenshot when WebGl is running, I found out one way(not sure if it is the best one, but it works).
You can execute the following Javascript code before loading your page and xBim Viewer:
HTMLCanvasElement.prototype.getContext = function (origFn) {
        return function (type, attributes) {
            if (type === 'webgl') {
                attributes = Object.assign({}, attributes, {
                    preserveDrawingBuffer: true,
                });
            }
            return origFn.call(this, type, attributes);
        };
    }(HTMLCanvasElement.prototype.getContext);

It should preserve drawing buffer and enable you to get a screenshot in some of the known ways e.g. using dom-to-image library:
domtoimage.toJpeg(document.getElementById('canvas'), { quality: 0.95 })
            .then(function (dataUrl) {
                var link = document.createElement('a');
                link.download = 'Screenshot.jpeg';
                link.href = dataUrl;
                link.click();
            });


text:
Q: QGIS: Create line vector between line without drawing
*

*I have transected the Transect line(white line) from a densified pink line

*Now I want to draw the green line between my transected line.

*Instead of doing it manually, is there another way to do it by using some processes of copy the line and offset?
TQ

A: You can do this in at least three different ways. On the screenshot, I numbered the three versions accordingly; red lines are original lines, black lines are created with solution 1.
Solution 1 and 2 include both times using the same QGIS expression:  offset_curve( $geometry, [distance]) - replace [distance] with a value for the offset in map units.

*

*Use geometry generator: For visualization purpose only, without creating an actual geometry, use an additional symbol layer on the original line layer, set this symbol layer to geometry generator / geometry type: line and paste the expression from above. Change settings for distance to see changes in realtime.

*To create a new layer with actual geometry of the shifted lines, use Menu Processing / Tollbox / Geometry  by expression. Set your original line as input, geometry type as line and again paste the expression from above.

*Copy the line(s) you want to shift, than use the Move feature tool from the Advanced Digitizing Toolbar (if it is not visible, got to Menu View / Toolbars and checkt the box for Advanced Digitizing Toolbar.
Like in solution 2, you get the actual geometry of the new lines. Like in solution 1, they will be on the same layer (thus you don't need to create a new layer).
However, carefully consider what that means for attributes, because they will be copied as well.

A: You can build an algorithm using the tools below. Needs some tweaking with the expressions to get 100 %:

*

*Densify by interval

*Extract vertices

*Voronoi polygons

*Polygons to line

*Explode lines

*Extract by expression to select line with a length below some threshold

*Extract by location to select segment that are close to the input layer


text:
Q: Merge text files next to each other I have .txt data from spectrometer with 800 lines and 5 columns. And I want to merge about 15 these files next to each other. So final .txt file should have 800 lines and  75 columns.
All .txt files looks like this:
Wave   ;Sample   ;Dark     ;Reference;Absorbance
[nm]   ;[counts] ;[counts] ;[counts] ;[A.U]
200.00;   34.647;   -0.317;   79.668; 0.35734
201.00;   29.937;  -21.220;   70.385; 0.25357
202.00;   48.826;   -0.527;   99.657; 0.30721
203.00;   43.201;    4.165;  136.775; 0.53103
...

Desired file:
Wave   ;Sample   ;Dark     ;Reference;Absorbance; Wave   ;Sample   ;Dark     ;Reference;Absorbance
[nm]   ;[counts] ;[counts] ;[counts] ;[A.U];  [nm]   ;[counts] ;[counts] ;[counts] ;[A.U]
200.00;   34.647;   -0.317;   79.668; 0.35734;    200.00;   34.647;   -0.317;   79.668; 0.35734;
201.00;   29.937;  -21.220;   70.385; 0.25357;    201.00;   29.937;  -21.220;   70.385; 0.25357
202.00;   48.826;   -0.527;   99.657; 0.30721;    202.00;   48.826;   -0.527;   99.657; 0.30721
203.00;   43.201;    4.165;  136.775; 0.53103;    203.00;   43.201;    4.165;  136.775; 0.53103

I tried:
cat *.txt > file.txt

But this add .txt files like new lines not like new columns.

A: You're looking for the paste utility, e.g.
paste *.txt > file.txt

Check its manual page for details, most notably the -d option to specify the delimiter.

A: Simple example
I set the separator to 'space' and eliminate multiple spaces.
$ cat file-1
ett tu tre
1    2   3
11   22 33
$ cat file-2
fyra fem sex
4     5   6
44   55  66

$ cat file-3
sju atta nio
7      8   9
77    88  99

$ paste file-?
ett tu tre  fyra fem sex    sju atta nio
1    2   3  4     5   6 7      8   9
11   22 33  44   55  66 77    88  99

$ paste -d ' ' file-?
ett tu tre fyra fem sex sju atta nio
1    2   3 4     5   6 7      8   9
11   22 33 44   55  66 77    88  99

$ paste -d ' ' file-? | tr -s ' ' ' '
ett tu tre fyra fem sex sju atta nio
1 2 3 4 5 6 7 8 9
11 22 33 44 55 66 77 88 99

Suggested command line
Maybe you want to eliminate the spaces? You want to keep semicolon as separator. Try with the following command line
paste -d ';' input-filespec-with-wildcard | sed 's/ //g' > output-file

where input-filespec-with-wildcard could be *.txt (if the files to be merged are the only txt files in the directory).
Edit (using the real data)

*

*Convert the files to unix/linux text format, CarriageReturn + LineFeed --> LineFeed with dos2unix

*Remove blank lines with the following command
for i in *.TXT;do echo sed '/^$/'d "$i" > "${i/.TXT/.txt}";done

*Remove header lines with the following command
for i in *.txt;do grep ';*;' "$i" > "${i/.txt/.txt1}";done

(Header lines do not contain at least two semicolons.)

*Merge the files with the following command
paste -d ';' *.txt1 | sed 's/ //g' > merged-file.txt

I read the merged file into LibreOffice Calc and used semicolon as separator. It looks like I think you want to have it. I hope it works for you according to these instructions. Otherwise please describe your remaining problem and tell me if you want me to upload 'my' merged-file.txt.
LibreOffice Calc
If you want to do it only once, you can do manually/visually in Libre Office Calc, by pasting the files into the spreadsheet. You can edit the positions in the spreadsheet and remove the lines, that create confusion.
I would say that it is rather easy to do it manually in LibreOffice Calc, but if this is something that you will do many times or with a great number of files, it is better to use and maybe refine the command line method.


text:
Q: Parallelize/vectorize computation of combinations from Pandas Dataframe I have a number of pickled pandas dataframes with a decent number of rows in each (~10k). One of the columns of the dataframe is a numpy ndarray of floats (Yes, I specifically chose to store array data inside a single cell - I've read this may not usually be the right way to go, eg. here , but in this case the individual values are meaningless, only the full list of values has meaning taken together, so I think it makes sense in this case). I need to calculate the euclidean distance between each pair of rows in the frame. I have working code for this, but I am hoping I can do something to improve the performance of it, as right now it is telling me that my smaller dataset is going to take > a month, but I'm pretty sure it's gonna take all my memory long before then.
The code is as follows:
import pandas as pd
import sys
import getopt
import math
from scipy.spatial import distance
from timeit import default_timer as timer
from datetime import timedelta

id_column_1 = 'id1'
id_column_2 = 'id2'
distance_column = 'distance'
val_column = 'val'

# where n is the size of the set
# and k is the number of elements per combination
def combination_count(n, k):
    if k > n:
        return 0
    else:
        # n! / (k! * (n - k)!)
        return math.factorial(n)/(math.factorial(k) * math.factorial(n - k))

def progress(start, current, total, id1, id2):
    if current == 0:
        print('Processing combination #%d of #%d, (%d, %d)' % (current, total, id1, id2))
    else:
        percent_complete = 100 * float(current)/float(total)
        elapsed_time = timer() - start
        avg_time = elapsed_time / current
        remaining = total - current
        remaining_time = timedelta(seconds=remaining * avg_time)
        print('Processing combination #%d of #%d, (%d, %d). %.2f%% complete, ~%.2f s/combination, ~%s remaining' % (current, total, id1, id2, percent_complete, avg_time, remaining_time))

def check_distances(df):
    indexes = df.index
    total_combinations = combination_count(len(indexes), 2)
    current_combination = 0
    print('There are %d possible inter-message relationships to compute' % total_combinations)
    distances = pd.DataFrame(columns=[id_column_1, id_column_2, distance_column])
    distances.set_index([id_column_1, id_column_2], inplace=True)
    start = timer()
    for id1 in indexes:
        for id2 in indexes:
            # id1 is always < id2
            if id1 >= id2:
                continue
            progress(start, current_combination, total_combinations, id1, id2)
            distances.loc[(id1, id2), distance_column] = distance.euclidean(df.loc[id1, embeddings_column], df.loc[id2, embeddings_column])
            current_combination+=1

(I excluded the main() function which just pulls out args and loads in the pickled files based on them)
I've only really started working with Python recently for this task, so there's every chance I'm missing something simple, is there a good way to deal with this?

A: There are some options for parallel calculation of dataframes in pure python.
Most complete may be dask
A simpler, but easier option would be pandaral-lel

A: So the solution ended up being parallelization, but I was unable to figure this out using the Panda specific parallelization libs seeing as the intended result was not a transformation of the existing cell contents, but a new value derived from another dataframe.
I grabbed the joblib library and took the following steps:
first, I created a function that, given two ids, could return the row for that index (as the separate workers cannot mutate the dataframe in the main process, we instead have to move to a paradigm of generating all the data first, THEN building the dataframe):
def get_distance(df, id1, id2):
    return [id1, id2, distance.euclidean(df.loc[id1, embeddings_column], df.loc[id2, embeddings_column])]

and applied joblib parallelization to it:
def get_distances(df):
    indexes = df.index
    total_combinations = combination_count(len(indexes), 2)
    current_combination = 0
    print('There are %d possible inter-message relationships to compute' % total_combinations)
    data = Parallel(n_jobs=-1)(delayed(get_distance)(df, min(ids), max(ids)) for ids in combinations(indexes, 2))
    distances = pd.DataFrame(data, columns=[id_column_1, id_column_2, distance_column])
    distances.set_index([id_column_1, id_column_2], inplace=True)
    return distances

This gave an immediate improvement from months to days for the expected time, but I suspected that passing the full dataframe was going to be creating significant overhead.
After modifying the function to pass in only the required values, another immediate improvement to less than a day (~20 hours) was attained:
def get_distance(id1, id2, embed1, embed2):
    return [id1, id2, distance.euclidean(embed1, embed2)]

# ...later, in get_distances()...

data = Parallel(n_jobs=-1)(delayed(get_distance)(min(ids), max(ids), df.loc[ids[0], embeddings_column], df.loc[ids[1], embeddings_column]) for ids in combinations(indexes, 2))

Finally, based on joblib's docs and the fact that a significant amount of data is still being transferred to the workers, I swapped to the multiprocessing backend, and saw the expected time drop further to ~1.5 hours. (I also added the tqdm lib so I could get a nicer idea of progress than what joblib provides)
data = Parallel(n_jobs=-1, backend='multiprocessing')(delayed(get_distance)(min(ids), max(ids), df.loc[ids[0], embeddings_column], df.loc[ids[1], embeddings_column]) for ids in tqdm(combinations(indexes, 2), total=total_combinations))

Hopefully this helps someone else with their first foray into Python parallelization!


text:
Q: Pop up tab in Google Chrome claiming a virus is present on the computer I have Chrome set to "Do not allow any site to show pop-ups", yet when browsing a regularly visited forum I occasionally get a new tab open claiming the computer has a virus and asking me to call a number to fix it. It is not possible to close this window, except through Task Manager, End Task. Disabling Javascript for that site seems to stop it popping up, but I haven't tested it enough to be completely sure.
Just to be on the safe side I ran AdwCleaner and Malwarebytes Anti-malware scans. The AdwCleaner scan showed that the Search Provider on Chrome had been changed to "uk.ask.com". Malwarebytes Anti-malware came up clean.
Should I contact the forum owner to inform them that they probably have a compromised advert on their page? My guess is that this is the most likely cause of the problem.
I include a screenshot of the window which opened:

A:
I have Chrome set to "Do not allow any site to show pop-ups", yet when
  browsing a regularly visited forum I occasionally get a new tab open
  claiming the computer has a virus and asking me to call a number to
  fix it.

This is because the notification is generated by Javascript and this particular setting has no effect on Javascript.

It is not possible to close this window, except through Task Manager,
  End Task.

This is incorrect.  You can close the window by closing the active tab.  You can acomplish this by using CTRL+F4.

Disabling Javascript for that site seems to stop it popping up

This is because the entire page is javascript and a static image.


text:
Q: How to use between command in 2 string date I am using following  select query, but the problem is IssueDate column is in varchar and it not give correct result. Is any way to use between command string date in SQL:
SELECT Pkid AS [Bill Id],
       InvoiceNumber,
       InvoiceType,
       IssueDate,
       FinalTotal
FROM tblInvoiceMain
WHERE IssueDate BETWEEN '01 June 2016' AND '06 June 2016'
ORDER BY Pkid DESC

Output:

A: Use CONVERT with to cast IssueDate to a DATE type. Also when using date constants, use the YYYYMMDD format.
SELECT
    Pkid AS [Bill Id], InvoiceNumber, InvoiceType, IssueDate, FinalTotal
FROM tblInvoiceMain
WHERE
    CONVERT(DATE, IssueDate, 106) BETWEEN CAST('20160601' AS DATE) AND CAST('20160606' AS DATE)
ORDER BY Pkid DESC

However, if you have an index on IssueDate, this will prevent the use of it. My suggestion is to fix your schema and use the proper data type to store your values.

A: SELECT Pkid AS [Bill Id],
       InvoiceNumber,
       InvoiceType,
       IssueDate,
       FinalTotal
FROM tblInvoiceMain
WHERE CAST(IssueDate AS DATE) BETWEEN '20160601' AND '20160606'
ORDER BY Pkid DESC

If execution time will be very high:
ALTER TABLE dbo.tblInvoiceMain
    ADD IssueDate2 AS CAST(IssueDate AS DATE)
GO
CREATE NONCLUSTERED INDEX ix
    ON dbo.tblInvoiceMain (IssueDate2)
    INCLUDE (Pkid, InvoiceNumber, InvoiceType, IssueDate, FinalTotal)
GO

SELECT Pkid AS [Bill Id],
       InvoiceNumber,
       InvoiceType,
       IssueDate,
       FinalTotal
FROM tblInvoiceMain
WHERE IssueDate2 BETWEEN '20160601' AND '20160606'
ORDER BY Pkid DESC


text:
Q: How to use Java optional operator to map more than one subtype I want to use the java Optional operator to avoid nullchecks like:
if(outher != null && outher.getNested() != null &&
          outher.getNested().getInner() != null && outher.getNested().getAnotherInner() != null)

I looked up some tutorials at the internet + Java cheatsheet but didn't find how to resolve the:outher.getNested.getInner() != null && outher.getNested.getAnotherInner != null part.
So how to do that correctly something like:
Optional.of(outher)
.map(Outher::getNested)
.map(Nested::getInner)
.map(Nested::getAnotherInner)
.isPresent();

would be awesome

A: The problem is that .map(Nested::getInner) returns an instance of Inner, but it should return Outer.
My suggestion is:
Optional.ofNullable(outher)
.map(Outher::getNested)
.map((outer) -> outer.getInner() == null ? null : outer)
.map(Nested::getAnotherInner)
.isPresent();

Not sure about flatMap, because you should map an entity on itself

A: Well, there is a way to use flatmap if you really want to :
 boolean result = Optional.ofNullable(outer)
            .map(Outer::getNested)
            .filter(x-> x.getInner() != null)
            .map(Nested::getAnotherInner)
            .isPresent();


text:
Q: how to move child object inside a moving parent in unity2d using Vector2.MoveTowards()? The Parent object is a moving rectangle and inside the rectangle there is another rectangle. the parent moving to right continuously and the child rectangle moving up and down.

(I Nested The Child into The Parent)
NOW:
I need the child move just inside the parent and don't cross the borders of its parent by using Vector2.MoveTowards()?
UPDATE #1 : the MoveToPoint Script
public float speed = .5f;
public Vector2 moveToPoint;

void Update()
{
    //moveToPoint = transform.InverseTransformPoint (moveToPoint);
    transform.localPosition = Vector2.MoveTowards(new Vector2(transform.localPosition.x, transform.localPosition.y),
    new Vector2(transform.parent.transform.position.x + moveToPoint.x, transform.parent.transform.position.y + moveToPoint.y), speed * Time.deltaTime);
}

the script simply moves the gameobject that attached to, to the point specified. but the issue is when the gameobject is a child of a moving object the script move it to the original point before moving!
in another word I need to move the child in its local position...