text:
Q: socket.io get bad response when I open new window I am building a web app that uses socket.io and web worker api to get updates from the server every second. one of the buttons is opening a new window, and when the new window is opened the socket.io stop working and getting bad request response
//part of the code

var socket = io({transports: ['polling']});

worker = new Worker("web_worker.js");

worker.onmessage = function(event){
   socket.emit("check_for_updates");
}

//this function is called when a button is pressed
function new_window(client)
{
    var uid = client.uid;
    var new_window = window.open("/new?uid="+uid);
}

the errors shown in the console:
polling-xhr.js:270 GET http://localhost/socket.io/?EIO=3&transport=polling&t=Mv0tQCC&sid=LnzFU8ClZrY0NHK5AA-r 400 (Bad Request)
polling-xhr.js:270 POST http://localhost/socket.io/?EIO=3&transport=polling&t=Mv0tQC-&sid=LnzFU8ClZrY0NHK5AA-r 400 (Bad Request)

A: So i manged to worked it out- the problem was that in the new window i opened a new socket with the default setting, that caused the first socket to crash. My solution was using namespace from the Sockt.io docks-
server side:
var main_socket = io(http);
socket = main_socket.of('/first');
socket.once("connection", (socket) =>{
    console.log("user connected");

    socket.on("disconnect", function(){
        console.log("user disconnected");
    });

var second_socket = main_socket.of('/second');
second_socket.once("connection", (second_socket) =>{
    console.log("second connection");

client side:
//part of the code

var socket = io(nsp="/first",Option={transports: ['polling']});

worker = new Worker("web_worker.js");

worker.onmessage = function(event){
   socket.emit("check_for_updates");
}

//this function is called when a button is pressed
function new_window(client)
{
    var socket = io(nsp="/second",Option={transports: ['polling']});
    var uid = client.uid;
    var new_window = window.open("/new?uid="+uid);
}

I hope it will help someone in the future


text:
Q: Vista Not Booting Properly My notebook has not been able to boot into Vista recently. This happened after I restarted my computer today, due to a Windows Update prompt. Additionally, before the problems arose, I also updated iTunes and QuickTime and installed Mobile Mouse; however, that's just today, and it's been a long time since I've rebooted my computer before today.
I have let Startup Repair run many times, with no luck; additionally, I have used System Restore to return to a restore point on the 29th, a RevoUninstaller point. That was successful because I have no restore points after that now, and had none before. However, my problem persists.
I attempted Safe Mode with Networking, which also failed, but it strangely showed that C:\Windows\SysWOW64\speedfan.sys was the last file loaded before the freeze and crash into Startup Repair. Speedfan.sys is related to Speedfan.exe, a program for monitoring system temperatures that I installed a while ago. I did not think it should load during Safe Mode. I then used del "C:\Windows\SysWOW64\speedfan.sys" to delete the file. Safe Mode still failed to boot, with a different file at the end. In Startup Repair again, all the Restore Points were back; I chose one today, as I updated iTunes.
Again, did not resolve the problem. I tried to delete speedfan.sys again with an error telling me the directory was incorrect. I rebooted into Safe Mode, and speedfan.sys was indeed loaded again, right before Startup Repair.
From Startup Repair, problem details are as follows:
Problem Event Name: StartupRepairV2
Problem Signature 01: AutoFailover
Problem Signature 02: 6.0.6.000.16386.6.0.6001.18000
P.S. (abbreviated, obviously) 03: 5
P.S. 04: 589833
P.S. 05: Corrupt File
P.S. 06: Corrupt File
P.S. 07: 3221226536
P.S. 08: 2
P.S. 09: SystemRestore
P.S. 10: 6.0.6000.2.0.0.256.1
Locale ID: 1033
I have Windows Vista Home Premium 64-bit.
P.S.: Sorry if there is no formatting.
It appears correct in Edit mode on my iPod.

A: Exactly what happens when you try to boot normally?
Run a chkdsk from Recovery Environment.
See this article to get to a command prompt in the Vista recovery environment, once there run this command, be patient it will take some time to complete, do not interrupt the process.
chkdsk /r C:
EDIT:
I may be crashing because the driver is missing, just deleting the problem driver does not work, it has to be taken out of the registry as part of startup. Microsoft has a boot CD with tools to disable drivers properly, it is called ERD commander, a version for each OS, XP, Vista, ect, not publicly available though it can be found.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to configure the neo4j-shell to echo commands I have some ETL code that sometimes takes awhile to run. I'd just like to know what's running. When I run
neo4j-shell -file mycode.cql

Is there a way to see either

*

*An "echo" of the cypher being run as it is loaded, or

*Just some random text, without doing something, er, hacky, e.g.
MATCH () RETURN "Frobnibbles loaded!" LIMIT 1;

A: No echo unfortunately, but you can just use return (you don't need the MATCH or LIMIT bit):
return "Hello, world!";


text:
Q: Traveling between integers- powers of 2
Moderator Note: At the time that this question was posted, it was from an ongoing contest. The relevant deadline has now passed.

Consider the integers. We can only travel directly between two integers with a difference whose absolute value is a power of 2 and every time we do this it is called a step. The distance $d$ between two integers is the minimum number of steps required to get from one to the other. Note however that we can travel backwards. For instance $d(2,17)$ is 2: $2+16=18 \rightarrow 18-1=17$.
How can we prove that for any integer n, we will always have some $d(a,b)=n$ where$b>a$?

If we are only able to take forward steps I know that  the number of 1s in the binary representation of $b-a$ would be $d(a,b)$. However, we are able to take steps leftward on the number line...

A: It is easy to see that the function $s(n):=d(0,n)$ $\ (n\geq1)$ satisfies the following recursion:
$$s(1)=1,\qquad s(2n)\ =\ s(n), \qquad s(2n+1)=\min\{s(n),s(n+1)\}+1 \ .$$
In particular $s(2)=s(4)=1$, $s(3)=2$.
Consider now the numbers $$a_r:={1\over6}(4^r+2)\qquad (r\geq2)$$ satisfying the recursion
$$a_2=3,\qquad a_{r+1}=4 a_r-1\quad (r\geq2).$$
The first few of these are $3$, $11$, $43$, $171$. I claim that
$$s(a_r-1)=s(a_r+1)=r-1,\quad s(a_r)=r\qquad (r\geq2)\ .$$
The claim is true for $r=2$. Assume that it is true for $r$.
 Then
$$s(2a_r-1)=\min\{s(a_r),s(a_r-1)\}+1=r,\qquad s(2a_r)=r$$
and therefore
$$s(4a_r-2)=s(4a_r)=r,\quad s(4a_r-1)=\min\{s(2a_r),s(2a_r-1)\}+1=r+1\ .$$
The last line can be read as
$$s(a_{r+1}-1)=s(a_{r+1}+1)=r, \qquad s(a_{r+1})=r+1\ .$$

A: Presumably you mean every natural number $n$, not every integer $n$. We can simplify things by taking $a=0$ without loss of generality and then writing $d(b):=d(0,b)$. Also, it's enough to show that for every $n$ there is $b$ with $d(b)\ge n$, since that means that for all $n$ there are numbers not reachable in $n$ steps, and it then follows by induction that for all $n$ there are numbers reachable in exactly $n$ steps, since at each stage of the induction there are adjacent numbers of which one is reachable in $n$ steps and the other isn't, and the latter can be reached in an $(n+1)$-th step of $1$.
Now represent the integers in "infinite two's complement", that is, a non-negative integer is represented by its binary representation and a negative integer $k$ is represented by inverting the binary representation of $-(k+1)$, considered as a leftward infinite string with leading zeros. This puts the integers into bijection with the set of all leftward infinite binary strings with finitely many transitions between $0$ and $1$.
In this representation, adding a positive integer to a number works as expected, with carrying carried out until the infinite stretch of $0$s or $1$s is reached, and the $1$s flipped to $0$s by a carry.
Now in each step, we can add a positive power of two to the number we've reached, and then we can optionally flip its sign. (This is equivalent to adding or subtracting powers of two at each step.) Since flipping the sign means inverting the string and then adding $1$, in each step we can invert the string and add a power of two up to twice.
Inverting the string doesn't change the number of transitions between $0$ and $1$. Adding a power of two increases the number of transitions between $0$ and $1$ by at most $2$. Thus in each step we can increase the number of transitions by at most $4$. Since there are integers whose representations have arbitrary numbers of transitions, for every $n$ there are integers we can't reach in $n$ steps.

A: Consider $ a(n) = \sum_0^n 2^{2i} $. Then $ d(0,a(n)) = n + 1 $.
Proof: First, note that in any minimal series of steps, you can only use each power of 2 once at most. If you add it twice at any point, you could get the same result by adding the next higher power once (and if that one was used, iteratively until the first unused one), same for substraction, and obviously adding it once and substracting it once would cancel out entirely, each leading to the same result with less steps.
Also, we can do the steps in arbitrary order, so we can assume we do all additions first.
Consider the binary representation of $ a(n) = 10101...1 $ with $ n+1 $ $1$s. A "step" is equivalent to addition or substraction of a power of $ 2 $, and we start at $ 0 $.
We start with the additions, so we can set any number of bits to $1$, each one being a step. Then we do the substractions, and those in order of magnitude, smallest first.
Any substraction of a power of $ 2 $ will flip all $0$ to $1$ starting at its position and then moving up in significance until the first $1$ is encountered which then is flipped to $0$ (note that this is guaranteed to happen because our target number is positive and so the sum of added powers must be greater than the sum of substracted powers).
Now consider the bits in $a(n)$ starting at lowest significiance. Each $01$ pair in the final sum can only have resulted from one of three situations:

*

*Having the power corresponding to the $1$ in the addition steps.

*By resulting from $10$ and substraction of the power of $2$ corresponding to the $01$ bit pair or a lower power of $2$. But in that case, that $10$ must result from addition or substraction of that power of $2$.

*Or, lastly, as a result of a substraction of a lower power of $2$ from $00$. But in that case, the result of the substraction would have been $11$ and thus, the power of two corresponding to the $0$ in that pair must also be substracted.
In 2. and 3. we made use of the fact that we can only use each power of $2$ once at most, so once a $1$ occurs at a point, substractions from below cannot go beyond it (as $ \sum_{i \lt n} 2^i \lt 2^n $).
Thus, we require at least one step for each $01$ pair and the claim is proven.
Additionally, any number $ b $ with $ d(0,b) = n+1 $ must at least have $ 2n $ digits: Assume $ b $ had less than $ 2n $ digits in binary representation. If $b$ contains $n$ or less 1s, we are done. And if there are at least $n+1$ $1$s  and thus at most $ n-2 $ $0$s, then we have a procedure to generate $ b $ in $n$ steps: Start with $2^{2n}-1$ in two steps resulting in $1...1$, and then in an additional $n-2$ substractions we substract all powers of $2$ that correspond to a $0$ in the binary representation of $b$. As $d(0,1011_b)=3$ shows, there are numbers with just $2n$ digits, though, so $a(n)$ is not optimal.

A: Hint:  If you represent the integers in binary, one way to build up a number from zero is to add the powers of $2$ that are one bits in the representation.  As you have shown, there may be a faster way.  See if you can find a set of numbers where the $1$'s are far enough apart that this is the fastest way to get there.

A: I think joriki's argument can be simplified a bit :
with $n$ steps, supposing you don't do stupid things like using the same power of $2$ twice or more, the number of integers you can reach using $n$ powers up to $2^k$ is at most $2^n \binom{k}{n} = P_n(k)$ where $P_n$ is a polynomial (of degree $n$).
Meanwhile, if you can reach a number $x < 2^l$ in $n$ steps, then you can't use arbitrarily high powers of two : if you use $2^k \ge 2^{l+n}$ then you can't substract enough smaller powers from it to get down to $x$.
The number of integers in $]-2^l, 2^l[$ is $2^{l+1}-1$, which is exponential in $l$, but the number of those you can reach in $n$ steps is less than $P_n(l+n) = Q_n(l)$, which is polynomial of degree $n$ in $l$. Therefore for $l$ big enough you will necessarily miss some of those numbers, so the number of steps needed to reach all the integers is unbounded.


text:
Q: How to make an array of pointer to NULL in C? I had similar code in my project
typedef struct
{
int a;
int b;
int c;
}TEST;

TEST test[2] =
{
  {1,2.3}
, {3,4,5}
};

TEST *test_ptr[2] =
{
 test,
 test
};

and I had a condition in source code like this
if ( test_ptr != NULL )
{
    do_something();
}

I want to test the FALSE decision of the above condition  ( ie test_ptr == NULL )
For this I had tried different methods but not succeeded yet, please help me to resolve this

A: As defined, test_ptr can't ever be NULL. test_ptr is an array, not a pointer. It does degenerate into a pointer (which is to say it's implicitly converted into a pointer) when treated as a pointer, but not one that is NULL.
I think you want
TEST* test_ptr = NULL;

You can still use the [] indexing notation because
p[i]

is just another way of saying
*(p+i)

which actually expects a pointer.
Demonstration:
#include <stdio.h>

typedef struct {
   int a;
   int b;
   int c;
} Test;

static Test tests_arr[] = {
   { 1, 2, 3 },
   { 3, 4, 5 },
};

int main(void) {
   printf("%d\n", tests_arr[1].b);                           // 4
   printf("%d\n", (tests_arr+1)->b);                         // 4
   printf("%d\n", (&(tests_arr[0])+1)->b);                   // 4

   Test* tests_ptr = NULL;
   printf("%s\n", tests_ptr == NULL ? "NULL" : "Not NULL");  // NULL

   tests_ptr = test_arr;
   printf("%s\n", tests_ptr == NULL ? "NULL" : "Not NULL");  // Not NULL
   printf("%d\n", tests_ptr[1].b);                           // 4
   printf("%d\n", (tests_ptr+1)->b);                         // 4

   tests_ptr = &(test_arr[0]);
   printf("%s\n", tests_ptr == NULL ? "NULL" : "Not NULL");  // Not NULL
   printf("%d\n", tests_ptr[1].b);                           // 4
   printf("%d\n", (tests_ptr+1)->b);                         // 4

   return 0;
}


text:
Q: Open file found using Where-Object I search for a file, e.g. the hosts file:
cd c:\Windows\System32
gci -Recurse | ? {$_.Name -eq 'hosts'}

Now I want to open the file in notepad, so I tried:
gci -Recurse | ? {$_.Name -eq 'hosts'} | notepad.exe $_.FullName

This errors. Is there a way to do this, as a one-liner?

A: notepad.exe does not accept pipeline output input
Get-ChildItem -Recurse -ErrorAction SilentlyContinue |
    Where-Object -FilterScript { $_.Name -eq 'hosts' } |
        Foreach-Object -Process { notepad.exe $_.FullName }

I would recommend using -Filter on get-childitem for this. It would greatly improve performance on the scriptlet.
  -@matt

Get-ChildItem -Filter Hosts -Recurse -ErrorAction SilentlyContinue |
    ForEach-Object -Process { notepad.exe $_.FullName }


text:
Q: Regex parser step by step Java This is my data and its pattern:
// _23.02_ANTALYA____________FRANKFURT___________DE_7461_18:20-21:00________________
public static final String FLIGHT_DEFAULT_PATTERN = "\\s+\\d{2}.\\d{2}\\s[A-Z]+\\s+[A-Z]+\\s+[A-Z\\s]{3}[\\d\\s]{5}\\d{2}:\\d{2}-\\d{2}:\\d{2}\\s+";

Underscores are space character. Now I need a class that divides every regex term to data. For example
\\s+ = " "
\\d{2} = "23"
. = "."
\\d{2} = "02"
\\s = " "
[A-Z]+ = "ANTALYA"

etc... That must be ordered by pattern.
How can I do this or is there a library for this?

A: As @devnull mentioned, you should use capturing groups:
(\s+)(\d{2})(.)(\d{2})(\s)([A-Z]+)(\s+)([A-Z]+)(\s+)([A-Z\s]{3})([\d\s]{5})(\d{2}:\d{2})(-)(\d{2}:\d{2})(\s+)

See the full explanation of this regular expression on Regex101.
You would then use something like the following to match the text and extract the individual values:
String text = " 23.02 ANTALYA            FRANKFURT            DE 7461 18:20-21:00                 ";
Pattern pattern = Pattern.compile("(\\s+)(\\d{2})(.)(\\d{2})(\\s)([A-Z]+)(\\s+)([A-Z]+)(\\s+)([A-Z\\s]{3})([\\d\\s]{5})(\\d{2}:\\d{2})(-)(\\d{2}:\\d{2})(\\s+)");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
    for (int i = 1; i < matcher.groupCount(); i++) {
        System.out.println(matcher.group(i));
    }
}

To make it easier to extract specific fields, you could (in Java 7 and later) use named capturing groups:
(?<LeadSpace>\s+)(?<Day>\d{2})(.)(?<Month>\d{2})...

You could then use something like the following to get each named group:
...
if (matcher.find()) {
    System.out.println(matcher.group("LeadSpace"));
    System.out.println(matcher.group("Day"));
    System.out.println(matcher.group("Month"));
    ...
}

A: I found a different way. I divided pieces with my hand.
// _24.02_MAURITIUS_________HAMBURG________________via:FRA_DE/LH____08:30-20:05_____
public static final List<String> FLIGHT_VIA_PATTERN = Arrays.asList( "\\s+", "\\d{2}", "\\.", "\\d{2}", "\\s+", "[A-Z]+", "\\s+", "[A-Z]+", "\\s+", "via:", "[A-Z\\s]{4}", "[A-Z]{2,3}", "/",
        "[A-Z]{2,3}", "\\s+", "\\d{2}", ":", "\\d{2}", "\\-", "\\d{2}", ":", "\\d{2}", "\\s+" );

After this I used a loop and everything is fine. This question can close.


text:
Q: jquery/javascript perform function on checkbox click or adjacent text click I have an unordered list of text items with checkboxes beside each of them. I want to perform the same function both when a checkbox is checked/unchecked and when the text is clicked.
Here's what I have right now:
The HTML

<input type="checkbox" class="cbox" name="adwords_list[]" value="shave club" >
 shave club

The JS
$(function() {
    $('ol.phrases li .term').click(function() {
        $cboxStatus = $(this).parent().find('.cbox').prop('checked');

        if ($cboxStatus) {
            $(this).parent().find('.cbox').prop('checked', false);
        } else {
            $(this).parent().find('.cbox').prop('checked', true);
        }
    });
});

$(':checkbox, .term').on('change', function() {
    console.log($(this).prop('checked'));
});

The on.change function isn't calling when the term is clicked. What can I do to get an accurate representation of the checked state no matter what element is clicked/changed?

A: If you change the p.term elements to label, with appropriate for attributes matching the associated checkboxes, clicking the text is just the same as checking the box.  You then only need to watch the checkbox events.
<input type="checkbox" class="cbox" name="adwords_list[]" value="shave club" id="cb1" />
 shave club

You can add
.term {
  display: block;
}

etc. to your CSS if you need to match the styling of the p tag.


text:
Q: How to change my url to user friendly url
Possible Duplicate:
mod_rewrite - how to rewrite an URL?

Hi can anyone of you suggest me on how to redirect my page http://testsite.com/about.php to http://testsite.com/about/ by using ht access rewrite rules,without using any query string in the page url I need to rewrite it.

A: It's not really clear what you want to achieve.
The following will serve about.php for all requests to http://example.com/about/. The user won't notice anything. Is this what you want to do?
RewriteEngine On
RewriteRule ^about/$ about.php

A: You could very simply use MultiViews to achieve such a result
Options MultiViews


text:
Q: How to choose subsets of factor groups to complete a statistical test in R I have a dataset containing several variables and I wish to statistically test the variances (Kruskal-test) for each variable seperately.
My data (df) looks like that: (carbon and nitrogen content for diffrent agricultural managements (see name)).
I have 16 groups (to simplify it, I´d say, I have got 8 groups):
extract of the data
1. List item
name    N_cont  C_cont  agriculture
C_ero   1,064   8,380   1
C_ero   0,961   8,086   1
C_ero   0,977   8,331   1
Ds_ero  1,767   17,443  2
Ds_ero  1,802   18,264  2
Ds_ero  2,083   20,112  2
Ms_ero  1,547   14,380  3
Ms_ero  1,566   15,313  3
Ms_ero  1,505   14,760  3
Md_ero  1,512   14,303  4
Md_ero  1,656   15,331  4
Md_ero  1,500   13,788  4
C_upsl  1,121   10,581  5
C_upsl  1,159   10,460  5
C_upsl  1,223   10,171  5
Ds_upsl 1,962   20,656  6
Ds_upsl 1,784   16,780  6
Ds_upsl 1,720   17,482  6
Ms_upsl 1,578   16,228  7
Ms_upsl 1,634   15,331  7
Ms_upsl 1,394   13,419  7
Md_upsl 1,286   11,824  8
Md_upsl 1,241   11,452  8
Md_upsl 1,317   11,932  8

I already put a factor for the agriculture
df$agriculture<-factor(df$agriculture)

I can do statistical tests compairing all of the 16 groups.
e.g. kruskal.test(df$C,df$agriculture)
But now I would like to do statistic tests just for specific groups out of the 8 groups, e.g. those which contain e.g. an C (Conventional) or rather DS (Direct seeding) in the name column
or e.g. ero (eroding site) or upsl (upper slope)
It did try grep or split, but it did not work, because the dimension of x and y should be the same.
Do you have any clue?

A: You can try to subset with grepl. Assuming you want rows whose name contains either DS, upsl or C then
df[grepl("(DS)|(upsl)|(C)", df$name), ]

#     name  N_cont C_cont   agriculture
#1    C_ero  1,064  8,380           1
#2    C_ero  0,961  8,086           1
#3    C_ero  0,977  8,331           1
#13  C_upsl  1,121 10,581           5
#14  C_upsl  1,159 10,460           5
#15  C_upsl  1,223 10,171           5
#16 Ds_upsl  1,962 20,656           6
#17 Ds_upsl  1,784 16,780           6
#18 Ds_upsl  1,720 17,482           6
#19 Ms_upsl  1,578 16,228           7
#20 Ms_upsl  1,634 15,331           7
#21 Ms_upsl  1,394 13,419           7
#22 Md_upsl  1,286 11,824           8
#23 Md_upsl  1,241 11,452           8
#24 Md_upsl  1,317 11,932           8

If you do not want to hard code the name values , you can also try,
x <- c("C", "DS", "upsl")
df[grepl(paste0(x, collapse = "|"), df$name), ]

which would also yield the same result.

A: Load the data.table package.
library(data.table)
Create a subset of the group you want to do your stats on:
if your dataframe is df, then
DT<-data.table(df)
DT[like(name,"C_")]

.. OR use the sqldf package:
library(sqldf)
sqldf("select * from df where name like 'C_'")


text:
Q: Create a matrix from a dataframe and fill it with the count of a column according to rows Suppose I have the following dataframe:
df <- data.frame(teams=c("A", "A", "C", "C", "D", "D"),
             country=c("Italy","Italy","Italy","Italy", "India","India"),
             players=c("ac","bd","fg","ji","ki","yr"),
             stringsAsFactors = FALSE)

I want to create a matrix as follows:

Basically, "teams" and "country" should be the rows and columns of the matrix respectively and the values should be the count of the names of the players.
Can anyone tell me how can I do it in R?
Thanks

A: Using dplyr and tidyr:
library(dplyr)
library(tidyr)

df %>%
  count(teams, country) %>%
  pivot_wider(names_from = country,
              values_from = n,
              values_fill = list(n = 0))

# A tibble: 3 x 3
  teams Italy India
  <chr> <int> <int>
1 A         2     0
2 C         2     0
3 D         0     2

A: as.matrix(table(df$teams, df$country))
  #   India Italy
  # A     0     2
  # C     0     2
  # D     2     0

# If order matters
df$country <- factor(df$country, levels=c("Italy", "India"))
as.matrix(table(df$teams, df$country))
  #   Italy India
  # A     2     0
  # C     2     0
  # D     0     2


text:
Q: Testing class that retrieves unpredictable data I have a task to write .net wrapper around native activex component, which loads realtime data on stock prices.
The question is how to test it correctly?
It seems reasonable to me to make the following test cases:

*

*Test it works in general: Start loading prices on some ticker, make sure loading starts

*Test data is flowing: Start loading prices on some ticker, make sure I have recieved some amount of updates

*Test that I have reasonable prices: Start loading prices on some ticker, make sure I have recieved expected price (or al least price in some reasonable range)

Unfortunately:

*

*I cannot be sure that some stock ticker will exist forever.

*I cannot be sure that some stock price will update for specified number of times per period

*or will have some exact value (or even value in given range with 100% probability)

Of course, I can mock the data source, and it would make some sense. But in this case I will test my wrapper to be fool-proof against myself, not agains those guys who wrote the native loader

A: Non-determinism and unit testing don't go together that well. However, I would argue that the only non-determinism you're facing is the data and its format you receive from native loader. Why?

Test it works in general: Start loading prices on some ticker, make sure loading starts

This should be controlled by .NET code entirely; either by some sort of job or manual method invocation. No non-determinism.

Test data is flowing: Start loading prices on some ticker, make sure I have received some amount of updates

Again, .NET code. You either need yet another job that would periodically query native loader for data, or something that observes events from native loader and responds to them.

Test that I have reasonable prices: Start loading prices on some ticker, make sure I have received expected price (or at least price in some reasonable range)

What is a reasonable price? A range from 0 to Int32.Max? Don't try to test native loader. Make assumptions about how it works and build your code around those assumptions. You can of course verify data formats, ranges (like, prices shouldn't be negative values) but that's about it. This brings us to the actual code you might want to unit test - class that maps their data to your data (domain objects - a simple POCO - StockQuotation or TickerData). Builder/mapper/converter of some sorts.
Now, you want to have two sets of tests - one for builder/mapper code to ensure your later code works around assumptions you made. The second set would be traditional system/integration test - entire process from loading data to building results with actual components (you shouldn't care about tickers ceasing to exists here as that's again something beyond your control).
In such setup, if something stops working it usually may mean one of two things:

*

*Assumptions you made about loader's data changed (or you overlooked something)

*Your builder/mapper/converter is implemented incorrectly around valid assumptions

At this point tracking issue should be easy. Don't try to write fool-proof code because you won't. Code having bugs is normal state of things. You find them and fix them. It's much easier to prepare for errors/exceptions than try to write code not containing them in first place. Not to mention, you cannot really control bugs in 3rd party code (your native loader) - it's better to prepare for them coming.


text:
Q: HTML text goes long and creates Horizontal scroll bar I have to add a text value dynamically in a div tag of a HTML page. but if this text is too long then it doesn't stay in its div width which I have assigned as 500px, but goes straight long in a single row and this makes the Web page to have a horizontal scroll. What should I do to fix the length of this text. I don't mind if it increases number or rows.
Here is the Css:
.question
{
    width: 500px;
    height: auto;
    float: left;
    overflow: auto;

}
.answer
{
    width: auto;
    height: auto;
    float:left;
    overflow: auto;

}
#main
{
    width: 1000px;
    height: auto;
    overflow: auto;

}

Here is the JS code:
function create_div_dynamic(answer){

     var dynDiv = document.createElement("div");
     dynDiv.id = "divDyna"+counter;

     var question_data = question();
     var answer_data= answer();
     dynDiv.innerHTML="

 "+question_data+"

 "+answer_data+"

"
     dynDiv.style.height = "auto";
     dynDiv.style.width = "auto";
     dynDiv.style.backgroundColor = 'gray';
     document.body.appendChild(dynDiv);
     counter=counter+1;

    }

A: You could use the rule word-wrap in css:
ie:
word-wrap:break-word;

Although this is CSS3 and may not be supported in all browsers.

A: you just need to use style="width:20px;" that will size your div to 20px. If no spaces exist though, the div will automatically size to the length of the largest work. If you want to hide(make div exactly the size you need it) words longer  than the size of your dive you can use width:20px;overflow:hidden;

A: hy add this style in your div.

 text

A: You need to analyze the content of the text, as well as style sheets being applied, to see what prevents normal word wrapping, and remove the cause or deal with the consequences.


text:
Q: Receiving data from BLE in linux I am working with bluetooth low-energy and am sending a characteristics with >70 bytes of data.
I am facing problem in receiving >20 bytes of data in Linux.
Is it possible to increase the MTU size in Linux?


text:
Q: How to capture the id of a div on click and pass it to the function to make the code dynamic? I have a coffeescript based code which has all the definitions (IDs and Classes) are called locally. Now I want it to refactor it based on a dynamic view i.e, on click by the user in the site, that should send the corresponding ID to the function. How do I deal with this?
HTML -

  <div id="target1" data-key="<%= @aws_url1[:key] if !@aws_url1.nil? %>">
  <% if !@aws_url1.nil? %>
   <img id="user_dl1" src="<%= @aws_url1[:url] %>">
  <% end %>

  <button id="closebtn1" class="closebtn">X</button>

  <button  id="deletebtn1" class="deletebtn">

Delete

  </button>
  <button id="cancelbtn1" class="cancelbtn">

Cancel

  </button>

   

 Upload Here

<form id="user_id1_form" action="">
  <input type="hidden" name="user_id1_key" value="<%= @aws_urls[0][:key] %>"/>
  <input id="file_upload1" type="file" accept="image/*" name="user_id1"/>
 </form>

CoffeeScript -
if $('#target1 img').length == 1
        $('#file_browser1').addClass 'none'
        $('#close1').addClass 'delete'
        $('#closebtn1').on 'click', (e) ->
                $('#closemsg1').addClass 'msg'
        $('#cancelbtn1').click ->
                $('#closemsg1').removeClass 'msg'
        $('#deletebtn1').click ->
                $('#close1').removeClass 'delete'
                $('#closemsg1').removeClass 'msg'
                $('#target1 > img').hide()
                $('#file_browser1').removeClass 'none'
                $('#file-upload1').val('')
                return

    $('#file_upload1').on 'change', (event) ->
        files = event.target.files
        image = files[0]
        old_key = $("#target1").data("key");
        new_key = null
        $user_id1 = $('#file_upload1')[0].files[0];
        console.log image.size
        reader = new FileReader
        $.ajax({
            type: "GET",
            url: "http://localhost:3000/users/get_url/13",
            success :(data) ->
                new_key = data[0].key
                processfile $user_id1,(result)->
                    console.log data[0].url
                    $user_id1 = dataURItoBlob(result)
                    reader1 = new FileReader()
                    reader1.readAsArrayBuffer($user_id1)
                    reader1.onload = (e) ->
                        rawData1 = reader1.result;
                        $.ajax({
                            url: data[0].url,
                            type: 'PUT',
                            xhr: ->
                                myXhr = $.ajaxSettings.xhr();
                                if (myXhr.upload)
                                    myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
                                return myXhr;
                            ,
                            success: completeHandler,
                            error: errorHandler,
                            data: rawData1,
                            cache: $.param(false),
                            contentType: "binary/octet-stream",
                            processData: $.param(false)
                        }, 'json');
        })

        completeHandler = (data) ->
            $.ajax({
                type: "POST",
                url: "http://localhost:3000/users/user_documents/13",
                data: {
                    aws_key_new: new_key,
                    aws_key_old: old_key,
                    dl_id: "dl",
                },
                success: ->
                    a = $('#target1')
                    console.log a.data("key")
                    console.log new_key
                    a.attr('data-key', new_key);
            })

            success :(data) ->
                alert "complete"
                return

            error :(data) ->
                alert "failed"
                return

        errorHandler = (data) ->
            console.log data
            alert "failed"

        progressHandlingFunction = (data) ->

        reader.onload = (file) ->
            img = new Image
            img.src = file.target.result
            $('#target1').html img
            $('#file_browser1').addClass 'none'
            $('#close1').addClass 'delete'
            $('#closebtn1').on 'click', (e) ->
                    $('#closemsg1').addClass 'msg'
            $('#cancelbtn1').click ->
                    $('#closemsg1').removeClass 'msg'
            $('#deletebtn1').click ->
                    $('#close1').removeClass 'delete'
                    $('#closemsg1').removeClass 'msg'
                    $('#target1 > img').hide()
                    $('#file_browser1').removeClass 'none'
                    $('#file-upload1').val('')
                    return
            return

        reader.readAsDataURL image
        console.log files
        return

How to pass the IDs to the coffeescript on click?

A: If I understood from your question, you want to adding click events to a group of elements and be able to get their respective values when trigged.
One way to do it would be to adding click event to the attribute class:
For example (using jquery):

// Add click event to the class .drill_cursor
$(".drill_cursor").click(function(){
  console.log(this.id);
});

// Used to display console.log
var consoleLine = "

";
console = {
    log: function (text) {
        $("#console-log").append($(consoleLine).html(text));
    }
};
.console-line {
  font-family: monospace;
  color: red;
  margin: 2px;
}
.drill_cursor {
  margin: 50px;
  color: blue;
}

div-1-click-on-me

div-2-click-on-me

div-3-click-on-me

div-4-click-on-me

Another way to do it would be delegating the event to another element tag:
You can find more information about delegate events here:
api.jquery.com/delegate
For some cases, delegate events is a better way to add events dynamically!
I hope it helps you!
Good luck!


text:
Q: Any identical replacement for zoom property? Inherited a web project which frontend's desing heavily relies on css zoom property
body { zoom: 90%;}

Now, this is causing all kinds of problems on major browsers (except for chrome).
transform: scale(0.9, 0.9) doesn't do the trick as they work in different ways. Zoom property acts like browser's zoom in/zoom out functionality, while scale just, well, scales the content (and leaves empty space around the scaled element (and in the project zoom is put on body tag, thus entire page is zoomed out)).
Any identical replacement available for zoom property (supported by modern browsers) or I'm better off just adjusting each element's width/height and text size and removing zoom property entirely?


text:
Q: Prevent form "on submit" loading blank page I've seen a few similar questions but couldn't find anything relevant..
I have a basic form capturing user email all I want is that when form submits it does not load a blank page, instead just re-directs back to the empty form again.
<?php
if ($thanks === false) {
    echo form::open('', array('id'=>'footer_email'));
    echo '
';

    echo '
';
    echo form::input('form[email]', $val, array('class'=>'required', 'id'=>'email', 'placeholder'=>'Enter email address'));
    echo '
';

    echo form::submit('btnSubmit', 'Sign Up', array('id'=>'btnSubmit', 'class'=>'footer_box_submit'));
    echo '
';

    echo form::close();

    }
?>

$(document).ready(function () {

var validator = $("#footer_email").validate({
    errorLabelContainer: $("#footer_email div.error"),
    meta: "validate",
    invalidHandler: function (form, validator) {
        alert("Please enter your email address first.");
    },
    submitHandler: function (form) { // on submit
        if ($(form).valid())
        form.submit();
        alert("Thank you for sharing your email address. \nKarina");
        return false;
      }
   });

});

Can anybody show me where I'm going wrong/would I be better to use ajax to achieve this?

A: You can do this:
<?php
if ($thanks === false) {
   echo form::open('', array('id'=>'footer_email'));
   echo '
';

   echo '
';
   echo form::input('form[email]', $val, array('class'=>'required', 'id'=>'email', 'placeholder'=>'Enter email address'));
   echo '
';

   echo form::submit('btnSubmit', 'Sign Up', array('id'=>'btnSubmit', 'class'=>'footer_box_submit'));
   echo '
';

   echo form::close();
} else {
   echo '';
   echo form::open('', array('id'=>'footer_email'));
   echo '
';

   echo '
';
   echo form::input('form[email]', $val, array('class'=>'required', 'id'=>'email', 'placeholder'=>'Enter email address'));
   echo '
';

   echo form::submit('btnSubmit', 'Sign Up', array('id'=>'btnSubmit', 'class'=>'footer_box_submit'));
   echo '
';

   echo form::close();

}
?>

A: Since you are using
form.submit();

It makes the usual form submit like you were hitting the 'Send' button. What you want to do here is send the form serialized through Ajax,
var formData = $(form).serialize();

$.post('[HERE YOUR SUBMIT TARGET URL]', formData, function (success){
  ///Redirect to empty form, or clear actual form
});

A: Use Ajax to keep it fast and no many refresh
$(document).ready(function () {

    var validator = $("#footer_email").validate({
        errorLabelContainer: $("#footer_email div.error"),
        meta: "validate",
        invalidHandler: function (form, validator) {
            alert("Please enter your email address first.");
        },
        submitHandler: function (form) { // on submit
            if ($(form).valid()) {
     $.ajax({
                type: "POST",
                url: url,
                data: $(form).serialize()
            }).done(function (data) {
               alert("Thank you for sharing your email address. \nKarina");
 $(form).reset();

            }).fail(function () {
                 alert("Sorry Try again. \nKarina");
            });
    }

            return false;
          }
       });

    });


text:
Q: Encrypt - Decrypt OpenSSL in PHP with only letters I would like to store email addresses in a database but as it is a shared one, I would like to store them crypted and decrypted when needed.
I thought of Encrypting the first part of it (before the @) so i come up with something like this:
Real email: myemail@gmail.com
Encrypted desired : 4n095tOA8PpRq5Nw2tIEp8l47@gmail.com
The proble is that when I use a function like this :
function EncryptVar($sVar){

return  openssl_encrypt($sVar, $this->encryptionMethod, $this->secretHash);

}

with some secret hash and this following method
$this->secretHash = "25c6c7ff35b9979b151f2136cd1sdftrez";
$this->encryptionMethod = "AES-256-CBC";

I may come up with special characters in the encrypted part, therefore an invalid email address format.
Is there a way to use this method so I have only letters and digits?

A: The common way to address this is to encode/decode using base64_encode / base64_decode. That will convert your binary data to an ASCII string.

A:
Is there a way to use this method so I have only letters and digits?

This is a great place to use base32-encoding.
A good implementation of this is available in this library.
An example that uses a secure encryption method:
<?php
use ParagonIE\ConstantTime\Base32;

class EmailEncryption
{
    protected $key;

    public function __construct($key)
    {
        if (mb_strlen($key, '8bit') !== 32) {
            throw new Exception('Keys should be 32 bytes generated from /dev/urandom');
        }
    }

    /**
     * @param string $sVar
     * @return string
     */
    public function encryptVar($sVar)
    {
        $nonce = random_bytes(12);
        $tag = '';
        $encrypted = openssl_encrypt(
            $sVar,
            'aes-256-gcm',
            $this->key,
            OPENSSL_RAW_DATA,
            $nonce,
            $tag
        );
        return Base32::encode($tag . $nonce . $encrypted);
    }

    /**
     * @param string $sVar
     * @return string
     */
    public function decryptVar($sVar)
    {
        $decoded = Base32::decode($sVar);
        $tag = mb_substr($decoded, 0, 16, '8bit');
        $nonce = mb_substr($decoded, 16, 12, '8bit');
        $ciphertext = mb_substr($decoded, 28, null, '8bit');
        $plaintext = openssl_decrypt(
            $ciphertext,
            'aes-256-gcm',
            $this->key,
            OPENSSL_RAW_DATA,
            $nonce,
            $tag
        );
        if (is_bool($plaintext)) {
            throw new Exception('Invalid ciphertext');
        }
        return $plaintext;
    }
}

Usage:
$key = random_bytes(32);
$encrypter = new EmailEncryption($key);

$message = 'test123456789';
$ciphertext = $encrypter->encryptVar($message);
var_dump($ciphertext);
$plaintext = $encrypter->decryptVar($ciphertext);
var_dump($plaintext, $message);

Note: This requires PHP 7.1+, but gives you authenticated encryption.


text:
Q: extract all the information from nested dictionary on Python I am learning the nested dictionary on Python. I want to know how I can extract specific information from the nested dictionary.
My data is the following:
data = {
    "1": {'area': 'Administration', 'expenditure': '315'},
    "2": {'area': 'Administration', 'expenditure': '120'},
    "3": {'area': None, 'expenditure': '314'},
    "4": {'area': 'Aids and appliances', 'expenditure': None},
    "5": {'area': 'Aids and appliances', 'expenditure': '12'},
    "6": {'area': 'Administration', 'expenditure': '110'},
    "7": {'area': 'Administration', 'expenditure': '300'},
}

How can I extract all the information on expenditure in each area?
Any help is appreciated.

A: To find values for key of expenditure:
for findvals in data.values():
   for k, v in findvals.items():
      if k == "expenditure":
         print(v)

### this prints all the values for key equal to "expenditure"

A: Use collections.defaultdict. Create a dictionary with area as keys and expenditure as values in a list.

from collections import defaultdict

data = {
"1": {'area': 'Administration',  'expenditure': '315'},
"2": {'area': 'Administration', 'expenditure': '120'},
"3": {'area': None, 'expenditure':'314'},
"4":{'area': 'Aids and appliances', 'expenditure': None} ,
"5":{'area': 'Aids and appliances', 'expenditure': '12'},
"6":{'area': 'Administration', 'expenditure': '110'},
"7":{'area': 'Administration', 'expenditure': '300'}
}

storage = defaultdict(list)

# defaultdict allows to define keys on fly
{storage[d['area']].append(d['expenditure']) for _, d in data.items() if d['area']}

# we have append all expenditure to all areas where the area is not None.

print(storage)

# to go back to normal dictionary with list of expenditures
results = dict(storage)

print(results)
# outcome: {'Administration': ['315', '120', '110', '300'], 'Aids and appliances': [None, '12']}

If you are not familiar with list comprehension, you can use normal for-loop:
# we can re-write this:
{storage[d['area']].append(d['expenditure']) for _, d in data.items() if d['area']}

# to
for _, d in data.items():
    if d['area']:
        storage[d['area']].append(d['expenditure'])
# get all items, and add them to storage if area is not False.

I prefer the first for efficiency but you can take second for readability.

A: Try
[val['expenditure'] for val in data.values() if val['area'] in ['Administration', 'Aids and appliances']]

A: You wrote your dictionary all wrong (no comments and typos !)
data =
{'1': {'area': 'Administration', 'expenditure': '315'},
 '2': {'area': 'Administration', 'expenditure': '120'},
 '3': {'area': None, 'expenditure': '314'},
 '4': {'area': 'Aids and appliances', 'expenditure': None},
 '5': {'area': 'Aids and appliances', 'expenditure': '12'}}

Just do something like this:
[[(v.get("area", None),y) for x,y in v.items() if x=='expenditure'] for k,v in data.items()]

A: I think you want a specific expenditure on specific areas. if you want all areas then just remove a condition from my code or else you can refer all other answers.
I do this as per user input any area name and he'll get expenditures of that particular area.
    def findExpense(data):
        a = input("Enter area to find expenditure : ")
        ex_dict = {}
        # create expenditure list as values to ex_dict
        ex_dict[a] = []
        for _,vals in data.items():
            if vals['area'] == a:
                ex_dict[a].append(vals['expenditure'])
        return ex_dict

    print(findExpense({
        "1": {'area': 'Administration', 'expenditure': '315'},
        "2": {'area': 'Administration', 'expenditure': '120'},
        "3": {'area': None, 'expenditure': '314'},
        "4": {'area': 'Aids and appliances', 'expenditure': None},
        "5": {'area': 'Aids and appliances', 'expenditure': '12'},
        "6": {'area': 'Administration', 'expenditure': '110'},
        "7": {'area': 'Administration', 'expenditure': '300'}
    }))

If you are familiar with list comprehension then you can replace for loop with the below code.
    ex_dict[a] = [vals['expenditure'] for _, vals in data.items() if vals['area'] == a]
    return ex_dict


text:
Q: Sending Email Attachement Through Outlook in R with RDCOMClient I'm Running a daily analysis that spits out a file I would like sent through my outlook Email. The code I used is featured here, and works wonderfully but the attachment part of it never works...
library(RDCOMClient)

OutApp <- COMCreate("Outlook.Application")

outMail = OutApp$CreateItem(0)

outMail[["To"]] = "gkinne@horizonmedia.com"
outMail[["subject"]] = "Bruh"
outMail[["body"]] = "Tester"
outMail[["Attachments"]]$Add("L:/Document.csv")

outMail$Send()

The original is here:
Sending email in R via outlook
The code works until the attachment part, and the email even sends, just with no Attachment. It spits this error out:
<checkErrorInfo> 80020009
No support for InterfaceSupportsErrorInfo
checkErrorInfo -2147352567
Error: Exception occurred.

Any Ideas?

A: Reverse the slashes and escape them.
The problem is that the path is being created in R, which prefers forward slashes (since the backslash is the escape character), but it's being interpreted by Outlook, which only takes backslashes.
For example, try adding an attachment to an Outlook email by pasting a path into the insert file dialogue, but change the backslashes to forward slashes. It doesn't accept it. And that's essentially what you're trying to do.
So reverse to make them backslashes, then add extra backslashes to each one to escape them. For example:
C:\\Users\\MyFiles\\Documents\\document.txt

R will strip out the escape characters and and pass a clean path to Outlook.

A: The answer that helped me was provided by David Arenburg in comments:

You need to specify a full path. Is L:/Document.csv a full path? Is L
  a local driver or you mapped a network driver? If later is the case
  you need to specify the actual network path.

Example: \\dfwcot\Home$\lando\bb8\2015-12-24 Daily Report.xlsx

A: The Add method of the Attachments class accepts four arguments. I'd suggest specifying them explicitly.
The source of the attachment can be a file (represented by the full file system path with a file name) or an Outlook item that constitutes the attachment. Make sure the file is accessible.

A: You need to do it like this
L:\\Document.csv
Worked for me.  Use two backslashes.

A: I was also facing the same issue of "Error: Exception occurred".
But, in my case i was missing the naming convention of file. So, make sure that the file name must not be separated by SPACE and use delimiter as "-".

A: You can use the gsub() function to change "/" to double back slashes "\" in your path
Use this:
outMail[["Attachments"]]$Add(gsub("/","\\" ,"L:/Document.csv", fixed = TRUE))

A: The problem that our customer was facing was that they executed this operation one too many times.
In your example you are using the filename "L:/Document.csv" over and over again.
Outlook will create that attachment in one of the cache folders each time you try to generate this mail. The first one will be "Document.csv", the second one "Document (002).csv" etc...
We saw it running up to (799) and apparently that is the hard limit.
We had to clean out the temp folder in C:\Users<username>\AppData\Local\Microsoft\Windows\INetCache\Content.Outlook<random hex value> to make it work again.
Just double click an attachment in any mail and see where that temporary file shows up and check that directory.


text:
Q: 2 date input validation php with condition i want to validate 2 date input in codeigniter, with the conditions, if the end date is greater than the start date, will appear warning [javascript warning or something] or data can't be input
my form like this,

<?php echo $title; ?>

<form action="<?= base_url(); ?>index.php/admin/kalender/buat" method="post" enctype="multipart/form-data" name="form" id="form">
<?php
echo "
Tingkatan Pimpinan :
";
echo form_dropdown('IDKategori', $kategori) . "
";

echo "Kegiatan / Lokasi :
";
$data = array('class' => 'validate[required] text-input', 'name' => 'judul', 'id' => 'ptitle', 'size' => 80);
echo form_input($data);

echo "
Uraian Kegiatan / Keterangan / Catatan :
";
$data = array('class' => 'validate[required] text-input', 'name' => 'konten', 'rows' => '13', 'cols' => '60', 'style' => 'width: 60%');
echo form_textarea($data) . "
";

echo "
Waktu Mulai :
";
$data = array('class' => 'validate[required] text-input', 'name' => 'TanggalMulai', 'id' => 'basic_example_1');
echo form_input($data) . "
";

echo "
Waktu Akhir :
";
$data = array('class' => 'validate[required] text-input', 'name' => 'TanggalAkhir', 'id' => 'basic_example_2');
echo form_input($data) . "
";

echo form_submit('submit', 'Tambah Even');
?>
  <input type="button" value="Kembali" onClick="javascript: history.go(-1)" />

how to validate in form "Waktu Akhir & Waktu Mulai" ?

A: Try this. It is by using CI validation library.
It uses callback type of validation.
Put this in if(isset($_POST['submit_button_name'])) {} section.
First, load validation array,
$validation = array(
  array('field' => 'startDate', 'label' => 'StartDate', 'rules' => 'required|callback_compareDate'),
  array('field' => 'endDate', 'label' => 'endDate', 'rules' => 'required|callback_compareDate'),
);

Then load CI validation library as,
$this->form_validation->set_rules($validation);
$this->form_validation->set_message('required', '%s is required.');

This is the called back function.
function compareDate() {
  $startDate = strtotime($_POST['startDate']);
  $endDate = strtotime($_POST['endDate']);

  if ($endDate >= $startDate)
    return True;
  else {
    $this->form_validation->set_message('compareDate', '%s should be greater than Contract Start Date.');
    return False;
  }
}

The "required" validation makes the fields mandatory to be filled with something.
The callback function, in this case, compares the dates, and further processes the form if start date is less than from date OR flags error otherwise.

A: Meanwhile, if you want in Jquery you can use this.
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());

if (startDate > endDate){
       alert("Start Date should be less than End Date");
       return false;
}

A: This is working code
$params['toDate'] = $this->input->post('toDate', TRUE);
$params['fromDate'] = $this->input->post('fromDate', TRUE);$this->load->model('your_model');
$this->load->library('form_validation');
$this->form_validation->set_data($params);

$startDate = strtotime($params['fromDate']);
$endDate = strtotime($params['toDate']);

if ($endDate >= $startDate):
    $this->form_validation->set_rules('fromDate', 'From Date', 'required|trim');
    $this->form_validation->set_rules('branchCode', 'Branch Code', 'required|trim');
else:
    $json = array(
        "success" => false,
        "msg" => "Start date must be greater than end date"
    );

    echo json_encode($json);
    die();
endif;


text:
Q: How to make conclusion about non planar graph Suppose $G$ is a non planar graph such that $G/e$ is planar for every edge. then want to show that at most six vertices of $G$ have degree 3 or more.
Well I know that a G is non planar iff it contains a subdivision of $K_{5}$ or $K_{3,3}$ as a subgraph, also G itself must be this subgraph because if not it would contradict that $G/e$ is planar.
So is that enough of to make the conclusion?

A: Following your reasoning, $G$ must contain a subgraph $G'$ that is (a subdivision of) $K_{3,3}$ or $K_5$. If $G$ also contains an edge $e$ not in $G'$, then $G/e$ is not planar, that is an absurd.
This means that the edges of $G$ concide with the edges of $G'$, but the same is not true for the nodes. In fact $G$ may contain nodes of degree 0 that are not included in $G'$.
In any case, $G$ contains only 5 or 6 nodes with degree greater or equal than 3, that are the nodes in $G'$ (without conunting the ones in the subdivision that have degree 2), so the thesis is true.


text:
Q: How do RGB numbers work? I have a grey color of 222,222,222
What is the rule so I don't do try and error, For example if I know I want to make the grey a bit darker, how should I know which number should I change and should I go higher or lower?

A: Quoting from the StackOverflow Documentation:


text:
Q: Create HDCluster using powershell I am trying to create cluster using powershell. Here is script I am executing:
$containerName = "hdfiles"
$location = "Southeast Asia"
$clusterNodes = 2
$userName = "HDUser"

#Generate random password
$rand = New-Object System.Random
$pass = ""
$pass = $pass + [char]$rand.next(97,121) #lower case
$pass = $pass + [char]$rand.next(48,57) #number
$pass = $pass + [char]$rand.next(65,90) #upper case
$pass = $pass + [char]$rand.next(58,62) #special character
1..6 | ForEach { $pass = $pass + [char]$rand.next(97,121) } #6 lower-case characters
$password = ConvertTo-SecureString $pass -AsPlainText -Force

# generate unique random cluster and storage account names
do
{
  $clusterName = "hd"
  1..6 | ForEach { $clusterName = $clusterName + [char]$rand.next(48,57) }
  $storageAccountName = $clusterName + "store"
}
while ((Test-AzureName -Name $storageAccountName -Storage) -and (Test-AzureName -Name $clusterName -Service))

# Create a storage account
Write-Host "Creating storage account..."
New-AzureStorageAccount -StorageAccountName $storageAccountName -Location $location

# Create a Blob storage container
Write-Host "Creating container..."
$storageAccountKey = Get-AzureStorageKey $storageAccountName | %{ $_.Primary }
$destContext = New-AzureStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey
New-AzureStorageContainer -Name $containerName -Context $destContext

# Create a cluster
Write-Host "Creating HDInsight cluster..."
$credential = New-Object System.Management.Automation.PSCredential ($userName, $password)
New-AzureHDInsightCluster -Name $clusterName -Location $location -DefaultStorageAccountName "$storageAccountName.blob.core.windows.net" -DefaultStorageAccountKey $storageAccountKey -DefaultStorageContainerName $containerName -ClusterSizeInNodes $clusterNodes -Credential $credential -Version 3.2

But on last line I am getting exception:
New-AzureHDInsightCluster : Validating connection to 'hd662173store.blob.core.windows.net' failed. Inner exception:Could not load file or assembly 'Microsoft.WindowsAzure.Storage, Version=3.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
At D:\ProgrammingWorkspace\Edx\Processing BigData with HDInsight\HDILabs\Lab02A\Provision HDInsight.ps1:38 char:1 + New-AzureHDInsightCluster -Name $clusterName -Location $location -Def ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [New-AzureHDInsightCluster], ConfigurationErrorsException
+ FullyQualifiedErrorId : System.Configuration.ConfigurationErrorsException,Microsoft.WindowsAzure.Management.HDInsight.Cmdlet.PSCmdlets.NewAzureHDInsightClusterCmdlet

I am using Azure Powershell release 0.9.7 and Azure SDK 2.7

A: Looking back on this, the issue you encountered is likely now fixed with the latest version of Azure PowerShell.
To install the latest version of Azure PowerShell, see here:
Installing Azure PowerShell
For samples of how to use HDInsight PowerShell cmdlets (e.g., New-AzureRmHDInsightCluster), see here: Using HDInsight Azure PowerShell cmdlets
I hope this helps!


text:
Q: Dim outFileCTL As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(filename,False) equivalent in C# Anyone help me VB.net code C# code.
Dim outFileCTL As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(filename,False)
equivalent in C#

A: vb.net has that built in "server" object - saves you have to define a stream writer.
So, this code would be the same in vb.net
    Dim fStream As StreamWriter

    fStream = My.Computer.FileSystem.OpenTextFileWriter("c:\test2\test.txt", False)

    fStream.WriteLine("First line of text")
    fStream.Close()

    ' above could also be

    Dim fStream2 As New StreamWriter("c:\test2\test.txt")

    fStream2.WriteLine("First line of text 22")
    fStream2.Close()

Thus in c#, use the 2nd approach, and thus we get this:
using System.IO;
.... etc.

And then
    StreamWriter fStream2 = New StreamWriter(@"c:\test2\test.txt");

    fStream2.WriteLine("First line of text 22");
    fStream2.Close();

Note that we placed a "@" in front of the string. We normal don't have to do this, but for strings with a "" in them, that has special meaning in c#, and thus the @ in front ignores that special meaning.


text:
Q: pipeline operator in Scala I want to know if it's possible to define a pipeline operator like %>% in magrittr package of R language. I found several similar implementations that look like:
implicit class PipelineContainer[F](val value: F) {
  def |>[G] (f: F => G) = f(value)
}

so that x |> f |> g works like g(f(x))
Now I want this operator works even when functions takes more than 1 parameter, in this case value on left side of pipeline parameter becomes the first parameter of function on the right side. For example, x |> f(2) |> g(3) becomes g(f(x, 2), 3). How can I implement this in scala? It doesn't have to be the same syntax as I show here, but the simpler the better.

A: There are a few options.
One is to just create the functions inline.  It's only slightly messy.
x |> (z=>f(z,2)) |> (z=>g(z,3))

Another is to create shortcut methods that can collapse the arity of an existing function.  In general it's a lot of boilerplate, but the first one is easy enough:
implicit class RichPipes[Y](y: Y) {
  def |>[Z](f: Y => Z) = f(y)
  def &>[X, Z](f: (X, Y) => Z): (X => Z) = (x: X) => f(x, y)
}

Then you can inject the other arguments inline (taking advantage of the fact that & is higher precedence than |):
x |> 2 &> f |> 3 &> g

Personally, I find this style confusing, but the compiler's fine with it.
Another option is to convert the methods to functions to start with (if necessary) and then enrich those functions to have a partial application helper method:
implicit class RichFunction2[A,B,Z](f: (A,B) => Z) {
  def %(b: B): (A => Z) = (a: A) => f(a,b)
}

Now you can
x |> f _ % 2 |> g _ % 3

Finally, if you happen to be able to write the functions differently, you can make it work without any extra machinery save a trailing _ to let the compiler know what you're up to; the difference is just that the application goes through the last of multiple parameter blocks:
def h(y: Int)(x: Int) = x + y
def i(y: Int)(x: Int) = x * y

x |> h(2) _ |> i(3) _

As a final thought, though, injecting parameters mid-stream may not be the easiest thing to follow for the uninitiated.  You might consider whether it's good programming practice as opposed to adopting a different workflow.


text:
Q: Difference between a range of dates to dates already registered I need an way of to calculate the difference of a range of dates to other dates already persisted in database, i.e.:
As arguments I would like to inform something like:
from 15/JAN/2013 to 27/JAN/2013

In database/collection I have:
START_DATE, END_DATE
-------------------------------------------
01/JAN/2013 00:00:00, 17/JAN/2013 22:30:00
23/JAN/2013 17:00:00, 31/JAN/2013 23:59:00

And the return must be:
17/JAN/2013 22:30:01, 23/JAN/2013 16:59:59

REASON:
I have files that contains up to 40 thousand rows in range of dates. Files that intersect between dates contains the same data. This is why I need to insert only data in date range gaps.
Thanks to everyone that could help me!

A: select start_gap, end_gap
from(
  select
     end_date start_gap,
     lead(start_date) over (order by start_date) as end_gap
  from your_table
)
where end_gap is not null; --last line is not interesting

A: The question is unclear. Use Between operator: where dates between 15/JAN/2013 and 27/JAN/2013. And you will get exactly what is in your return.

A: Try this:
select START_DATE,END_DATE from tablename where START_DATE>max(START_DATE) and END_DATE<max(END_DATE)


text: Q: methods of aggregating data into a single collection I am currently researching which Database to use for a software, and I have selected MongoDB however I cannot find any ways of aggregating data into a single collection. The two products and reviews collections can be aggregated together into a single collection, but what are the methods in aggregating data?


text:
Q: iOS 7 - Dynamically resize the height of the label and scrollview Sooo... I'm having problems using the scrollview and the fit text label on iOS7/xcode5, and I'm getting frustrated with this problem because it is easy to handle this on iOS6/xcode4...
Here is the preview of my code...
ViewController.h
#import <UIKit/UIKit.h>
#import "ViewControllerOther.h"

@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>

@end

ViewController.m
#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITableView *tableview;

@property (strong, nonatomic) NSArray *meepo;
@property (strong, nonatomic) NSArray *icon;

@property (strong, nonatomic) NSArray *taunt;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.tableview setDataSource:self];
    [self.tableview setDelegate:self];

    self.meepo = [[NSArray alloc] initWithObjects:
                    @"Meepo No. 1",
                    @"Meepo No. 2",
                    @"Meepo No. 3",
                    @"Meepo No. 4",
                    @"Meepo No. 5",
                    nil];
    self.icon = [[NSArray alloc] initWithObjects:
                   [UIImage imageNamed:@"meepo.jpg"],
                   [UIImage imageNamed:@"meepo.jpg"],
                   [UIImage imageNamed:@"meepo.jpg"],
                   [UIImage imageNamed:@"meepo.jpg"],
                   [UIImage imageNamed:@"meepo.jpg"],
                   nil];

    self.taunt = [[NSArray alloc] initWithObjects:
                 @"Meepo No. 1 reporting, Meepo No. 1 reporting, Meepo No. 1 reporting, Meepo No. 1 reporting, Meepo No. 1 reporting, Meepo No. 1 reporting, Meepo No. 1 reporting, Meepo No. 1 reporting, Meepo No. 1 reporting, Meepo No. 1 reporting, Meepo No. 1 reporting, Meepo No. 1 reporting, Meepo No. 1 reporting, ",
                 @"Meepo No. 2 reporting, Meepo No. 2 reporting, Meepo No. 2 reporting, Meepo No. 2 reporting, Meepo No. 2 reporting, Meepo No. 2 reporting, Meepo No. 2 reporting, Meepo No. 2 reporting, Meepo No. 2 reporting, Meepo No. 2 reporting, Meepo No. 2 reporting, Meepo No. 2 reporting, ",
                 @"Meepo No. 3 reporting, Meepo No. 3 reporting, Meepo No. 3 reporting, Meepo No. 3 reporting, Meepo No. 3 reporting, Meepo No. 3 reporting, Meepo No. 3 reporting, Meepo No. 3 reporting, Meepo No. 3 reporting, Meepo No. 3 reporting, Meepo No. 3 reporting, ",
                 @"Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, Meepo No. 4 reporting, ",
                 @"Meepo No. 5 reporting, Meepo No. 5 reporting, Meepo No. 5 reporting, Meepo No. 5 reporting, Meepo No. 5 reporting, Meepo No. 5 reporting, Meepo No. 5 reporting, Meepo No. 5 reporting, Meepo No. 5 reporting, Meepo No. 5 reporting, Meepo No. 5 reporting, ",
                 nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.meepo count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }

    NSString *meepos = [self.meepo objectAtIndex:indexPath.row];
    UIImage *icon = [self.icon objectAtIndex:indexPath.row];
    [cell.textLabel setText:meepos];
    cell.imageView.image = icon;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ViewControllerOther *other = [self.storyboard instantiateViewControllerWithIdentifier:@"Delegate"];
    other.meepono = [self.meepo objectAtIndex:indexPath.row];
    other.index = [self.taunt objectAtIndex:indexPath.row];

    [self.navigationController pushViewController:other animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

ViewControllerOther.h
#import <UIKit/UIKit.h>

@interface ViewControllerOther : UIViewController

@property (weak, nonatomic) IBOutlet UILabel *meepo;
@property (weak, nonatomic) IBOutlet UILabel *taunt;
@property (weak, nonatomic) IBOutlet UIScrollView *scroller;

@property (nonatomic, strong) NSString *meepono;
@property (nonatomic, strong) NSString *index;

@end

ViewControllerOther.m (*)
#import "ViewControllerOther.h"

@interface ViewControllerOther ()

@end

static CGRect size;
static CGSize maxSize;
static CGRect labelRect;

@implementation ViewControllerOther

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.meepo setText:self.meepono];

    [self.scroller setScrollEnabled:YES];

    labelRect = [self.taunt frame];
}

- (void)viewWillAppear:(BOOL)animated
{

}

-(void)viewWillLayoutSubviews
{
    [self.taunt setNumberOfLines:0];
    [self.taunt setText:self.index];
    maxSize = CGSizeMake(self.taunt.frame.size.width, MAXFLOAT);
    size = [self.taunt.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.taunt.font} context:nil];

    labelRect.size.height = size.size.height;

    [self.taunt setFrame:labelRect];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (IBAction)sample:(id)sender {
    [self.scroller setContentSize:CGSizeMake(320, 1000)];
}
@end

And here's the output
1st - http://i.imagefra.me/b52js8zk
2nd - http://i.imagefra.me/313js8zl
My target on the the 2nd view is to dynamically resize the height of the label depending on how long the text is, and also, at the same time, resize the height of the scrollview and make it scrollable...
Note:
This is just a sample project that I made so I can ask these kind of questions.
Update 1:
Okay, so I manage to make the resize label work by transferring the code from viewDidLoad method to viewWillLayoutSubviews method, but unfortunately, when I put the [self.scroller setContentSize:CGSizeMake(320, 1000)]; the label return to its normal size. Am I missing something?

A: To make a UILabel to fit it's content use sizeToFit
1) set number of lines to zero   yourLabel.numberOfLines = 0; // Important to do
2) after setting the text call sizeToFit  [YourLabel sizeToFit];
3) This will dynamically resize the height of your label according to its content.
UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,0,320,100)];
testLabel.numberOfLines = 0;
testLabel.text = @"add your string here";
[testLabel sizeToFit];

Now you can use the height of label to set the ContentSize of scrollview dynamically.
[self.scroller setContentSize:CGSizeMake(self.scroller.frame.size.width,testLabel.frame.size.height)];

Hope this will help you..


text:
Q: jq: Insert values according to mappings from external file I was wondering how I can complete this task by command line jq. I make up a file with similar nested structure as follows:
{
    "item": "item1",
    "features": [
        {
            "feature": "feature_a",
            "value": ""
        },
        {
            "feature": "feature_b",
            "value": ""
        }
     ]
}

Now I have another file that maps the feature to value:
feature_a value_1
feature_b value_2

So I would like to insert the value into the first json file, according to the maps, resulting the following output:
{
    "item": "item1";
    "features": [
        {
            "feature": "feature_a",
            "value": "value_1"
        },
        {
            "feature": "feature_b",
            "value": "value_2"
        }
     ]
}

How I can achieve above operation by jq?
Thanks in advance!

A: Assuming the text file is in dict.txt and the JSON file is in source.json, the invocation
jq -Rs --argfile target source.json dict.txt '
  ([ split("\n")[]
     | select(length>0)
     | split(" ")
     | { (.[0]): .[1]} ]
   | add) as $dict
  | $target
  | .features |= map(.value = $dict[.feature])'

would yield the desired output.
The main reason for including select(length>0) is to skip any empty strings that might result from using split("\n") to split an entire file.


text:
Q: data-frame melting issue and bubble plot This is my dataframe
a <- dput(df)
structure(list(Category = c("KEGG Pathway", "KEGG Pathway", "KEGG Pathway",
"KEGG Pathway", "KEGG Pathway", "KEGG Pathway", "KEGG Pathway",
"KEGG Pathway", "KEGG Pathway", "KEGG Pathway", "KEGG Pathway",
"KEGG Pathway", "KEGG Pathway", "KEGG Pathway", "KEGG Pathway",
"KEGG Pathway", "Reactome Gene Sets", "Reactome Gene Sets", "Reactome Gene Sets",
"Reactome Gene Sets", "Reactome Gene Sets", "Reactome Gene Sets",
"Reactome Gene Sets", "Reactome Gene Sets", "Reactome Gene Sets",
"Reactome Gene Sets", "Reactome Gene Sets"), Description = c("Cytokine-cytokine receptor interaction",
"Cytokine-cytokine receptor interaction", "Salmonella infection",
"Rheumatoid arthritis", "Salmonella infection", "Rheumatoid arthritis",
"Toll-like receptor signaling pathway", "Toll-like receptor signaling pathway",
"Chemokine signaling pathway", "Chemokine signaling pathway",
"PI3K-Akt signaling pathway", "PI3K-Akt signaling pathway", "Rap1 signaling pathway",
"Rap1 signaling pathway", "TNF signaling pathway", "TNF signaling pathway",
"Interleukin-10 signaling", "Cytokine Signaling in Immune system",
"Chemokine receptors bind chemokines", "Signaling by GPCR", "Signaling by Interleukins",
"Peptide ligand-binding receptors", "GPCR ligand binding", "GPCR downstream signalling",
"Class A/1 (Rhodopsin-like receptors)", "Signaling by Receptor Tyrosine Kinases",
"Metabolism of nucleotides"), LogP = c(-6.6272284368, -6.6272284368,
-2.9316614282, -2.8584315312, -2.7718494704, -2.7061868255, -2.6281915791,
-2.6281915791, -2.5273777647, -2.5273777647, -3.6762135505, -3.2880356369,
-2.2646576514, -2.117278626, -3.5410827773, -3.4151337331, -8.2548924333,
-6.5328526991, -4.7978866035, -3.9736787567, -3.7112985062, -3.1255339841,
-3.0317801957, -2.6859542446, -2.6603292838, -3.2998550411, -2.690237169
)), row.names = c(NA, -27L), class = c("data.table", "data.frame"
), .internal.selfref = <pointer: 0x5642e14a3420>)

This is like this
head(a)
       Category                            Description      LogP
1: KEGG Pathway Cytokine-cytokine receptor interaction -6.627228
2: KEGG Pathway Cytokine-cytokine receptor interaction -6.627228
3: KEGG Pathway                   Salmonella infection -2.931661
4: KEGG Pathway                   Rheumatoid arthritis -2.858432
5: KEGG Pathway                   Salmonella infection -2.771849
6: KEGG Pathway                   Rheumatoid arthritis -2.706187

So i have two unique group in this Category column
KEGG and Reactome.
So I tried to melt to long format like this
pcm = melt(df, id = c("Description"))

pcm$Description <- factor(pcm$Description,levels=unique(pcm$Description))

colours = c( "#A54657",  "#582630", "#F7EE7F", "#4DAA57","#F1A66A","#F26157", "#F9ECCC", "#679289", "#33658A",
             "#F6AE2D","#86BBD8")

xx = ggplot(pcm, aes(x = variable, y = Description)) +
  geom_point(aes(size = value, fill = variable), alpha = 0.75, shape = 21) +
  #scale_size_continuous(limits = c(-6, -1), range = c(1,17), breaks = c(1,10,50,75)) +
  labs( x= "", y = "", size = "p value (%)", fill = "")  +
  theme(legend.key=element_blank(),
        axis.text.x = element_text(colour = "black", size = 12, face = "bold", angle = 90, vjust = 0.3, hjust = 1),
        axis.text.y = element_text(colour = "black", face = "bold", size = 11),
        legend.text = element_text(size = 10, face ="bold", colour ="black"),
        legend.title = element_text(size = 12, face = "bold"),
        panel.background = element_blank(), panel.border = element_rect(colour = "black", fill = NA, size = 1.2),
        legend.position = "right") +
  scale_fill_manual(values = colours, guide = FALSE) +
  scale_y_discrete(limits = rev(levels(pcm$Description)))

xx

But this I'm messing up something
What i require is in my x axis I want only my two categories and on my y axis Description labelled im not sure if two legends for pvalue can go inside.
Any suggestion or help would be really appreciated
UPDATED
d <- unique_GO %>% group_by(Category) %>% slice_min(order_by = LogP, n = 10)

df$Description <- factor(d$Description,levels=unique(df$Description))

colours = c( "#A54657",  "#582630", "#F7EE7F", "#4DAA57","#F1A66A","#F26157", "#F9ECCC", "#679289", "#33658A",
             "#F6AE2D","#86BBD8")

ggplot(df, aes(x = Category, y = Description)) +
  geom_point(aes(size = LogP, fill = Category), alpha = 0.75, shape = 21) +
scale_y_discrete(limits = rev(levels(df$Description)))

A: Your data in a was already in the long format ggplot works well with.
a$Description <- factor(a$Description,levels=unique(a$Description))

colours = c( "#A54657",  "#582630", "#F7EE7F", "#4DAA57","#F1A66A","#F26157", "#F9ECCC", "#679289", "#33658A",
             "#F6AE2D","#86BBD8")

ggplot(a, aes(x = Category, y = Description)) +
   geom_point(aes(size = LogP, fill = Category), alpha = 0.75, shape = 21) +
   ...
   scale_y_discrete(limits = rev(levels(a$Description)))

EDIT
Lots of ways to fiddle with the text spacing. Here's one approach that uses the white space:
library(ggplot2); library(dplyr)
ggplot(a, aes(x = Category, y = Description)) +
   geom_point(aes(size = LogP, fill = Category), alpha = 0.75, shape = 21) +
   #scale_size_continuous(limits = c(-6, -1), range = c(1,17), breaks = c(1,10,50,75)) +
   geom_text(data = a %>% filter(Category != "KEGG Pathway"),
             aes(label = Description), hjust = 1, nudge_x = -0.1) +
   geom_text(data = a %>% filter(Category == "KEGG Pathway"),
             aes(label = Description), hjust = 0, nudge_x = 0.1) +
   coord_cartesian(clip = "off") +

   labs( x= "", y = "", size = "p value (%)", fill = "")  +
   theme(legend.key=element_blank(),

         axis.text.x = element_text(colour = "black", size = 12, face = "bold", angle = 90, vjust = 0.3, hjust = 1),
         axis.text.y = element_blank(),
         legend.text = element_text(size = 10, face ="bold", colour ="black"),
         legend.title = element_text(size = 12, face = "bold"),
         panel.background = element_blank(), panel.border = element_rect(colour = "black", fill = NA, size = 1.2),
         legend.position = "right") +
   scale_fill_manual(values = colours, guide = FALSE) +
   scale_y_discrete(limits = rev(levels(a$Description)))


text:
Q: Python Lxml - Append a existing xml with new data I am new to python/lxml After reading the lxml site and dive into python I could not find the solution to my n00b troubles. I have the below xml sample:
---------------
<addressbook>
    <person>
        <name>Eric Idle</name>
        <phone type='fix'>999-999-999</phone>
        <phone type='mobile'>555-555-555</phone>
        <address>
            <street>12, spam road</street>
            <city>London</city>
            <zip>H4B 1X3</zip>
        </address>
    </person>
</addressbook>
-------------------------------

I am trying to append one child to the root element and write the entire file back out as a new xml or over write the existing xml. Currently all I am writing is one line.
from lxml import etree
tree = etree.parse('addressbook.xml')
root = tree.getroot()
oSetroot = etree.Element(root.tag)
NewSub = etree.SubElement ( oSetroot, 'CREATE_NEW_SUB' )
doc = etree.ElementTree (oSetroot)
doc.write ( 'addressbook1.xml' )

TIA

A: You could make a new tree by copying over all of the old one (not just the root tag!-), but it's much simpler to edit the existing tree in-place (and, why not?-)...:
tree = etree.parse('addressbook.xml')
root = tree.getroot()
NewSub = etree.SubElement ( root, 'CREATE_NEW_SUB' )
tree.write ( 'addressbook1.xml' )

which puts in addressbook1.xml:
<addressbook>
    <person>
        <name>Eric Idle</name>
        <phone type="fix">999-999-999</phone>
        <phone type="mobile">555-555-555</phone>
        <address>
            <street>12, spam road</street>
            <city>London</city>
            <zip>H4B 1X3</zip>
        </address>
    </person>
<CREATE_NEW_SUB /></addressbook>

(which I hope is the effect you're looking for...?-)


text:
Q: How to protect/encrypt a python module?
*

*My project is open sourced, except for a single module where I don't want people to know the implementation. Actually, I don't mind one or two people cracking the thing open if they are determined enough, but I want most to give up at the first sight.

*I only want the implementation of that single module to be hidden, the interface still fully usable if people want to contribute to the project. That is to say, I want people to be able to do things like:

import my_hidden_module

my_hidden_module.do_stuff()

*

*My project mostly runs on Windows so Windows-exclusive suggestions are ok.

*I'm totally new to this hiding code thing so I don't know where to start. It would be appreciated if someone could give me a direction to look into.

A: 1) You can use classes and private variables or
2) use name =='main', but that will not implement the code on interface
3) looks dumb but you can comment on top of that function to not to be CHANGED
else you can see - How do I protect Python code?


text:
Q: Wordpress Custom Columns I have created a custom post type called Members.
I then wanted to customise the display for this custom post type to display some custom meta which has been entered in the columns.
The columns are displaying but the data isn't showing up and I can't work out why.
add_filter( 'manage_edit-members_columns', 'my_columns_filter', 10, 1 );

function my_columns_filter( $columns ) {
$column_phone = array( 'phone' => 'Phone Number' );
$column_email = array( 'email' => 'Email Address' );
$column_membertype = array( 'member_type' => 'Member Type' );
$columns = array_slice( $columns, 0, 2, true ) + $column_phone + array_slice( $columns, 2, NULL, true );
$columns = array_slice( $columns, 0, 3, true ) + $column_email + array_slice( $columns, 3, NULL, true );
$columns = array_slice( $columns, 0, 4, true ) + $column_membertype + array_slice( $columns, 4, NULL, true );
return $columns;
}

add_action( 'manage_members_custom_column', 'my_column_action', 10, 2 );

function my_column_action( $column, $post_id ) {
global $post;
switch ( $column ) {
    case 'phone':
        echo get_post_meta($post_id, '_cricketss_phone', TRUE);
        break;
    case 'email':
        echo get_post_meta($post_id, '_cricketss_email', TRUE);
        break;
    case 'member_type':
        echo get_post_meta($post_id, '_cricketss_phone', TRUE);
        break;
}
}

Any heads up would be appreciated.

A: I'll take a shot in the absence of the register_post_type code. Here are the things to try

*

*Add 'hierarchical' => false  to your  register_post_type if you haven't already

*Change
add_action( 'manage_members_custom_column', 'my_column_action', 10, 2 );

to
add_action( 'manage_posts_custom_column', 'my_column_action', 10, 2 );

I have a strong feeling that your problem lies in the point 2 I mentioned.
The Codex states:
Combined with the manage_edit-${post_type}_columns filter, this allows you to add custom columns to the list post/page/custom post type pages. The filter described in here works both for built in post types as well as custom post types. Note that if the custom post type has 'hierarchical' => true, then the correct action hook to use is manage_pages_custom_column.


text:
Q: SQL - Multiple Values comma separated when using GROUP BY I have data that looks like

CUSTOMER,  CUSTOMER_ID, PRODUCT
ABC INC    1            XYX
ABC INC    1            ZZZ
DEF CO     2            XYX
DEF CO     2            ZZZ
DEF CO     2            WWW
GHI LLC    3            ZYX

I'd like to write a query that'd make the data look like this:

CUSTOMER, CUSTOMER_ID, PRODUCTS
ABC INC   1            XYX, ZZZ
DEF CO    2            XYX, ZZZ, WWW
GHI LLC   3            ZYX

Using Oracle 10g if helps.  I saw something that would work using MYSQL, but I need a plain SQL or ORACLE equivalent.   I've also seen examples of stored procs that could be made, however, I cannot use a stored proc with the product i'm using.
Here's how'd it work in MySQL if I were using it
SELECT CUSTOMER,
       CUSTOMER_ID,
       GROUP_CONCAT( PRODUCT )
FROM MAGIC_TABLE
GROUP BY CUSTOMER, CUSTOMER_ID

Thank you.

A: This link refers to a number of examples of different ways to do this on Oracle.  See if there's something there that you have permissions on your database to do.

A: The oracle user function 'wm_concat' works the same way as LISTAGG except you cannot specify a delimiter ',' by default or a sort order. It is however compatible with 10g.

A: I think LISTAGG is the best aggregate group by function to use in this situation:
  SELECT CUSTOMER, CUSTOMER_ID,
         LISTAGG(PRODUCT, ', ') WITHIN GROUP (ORDER BY PRODUCT)
    FROM SOME_TABLE
GROUP BY CUSTOMER, CUSTOMER_ID
ORDER BY 1, 2

A: Thanks Nigel,
My SQL is not as elegant as could be, but I needed a solution that required SQL only, not PLSQL or TSQL, so it ended up looking like this:
SELECT   CUSTOMER, CUSTOMER_ID, COUNT(PRODUCT) PROD_COUNT,
         RTRIM(
            XMLAGG( XMLELEMENT (C, PRODUCT || ',') ORDER BY PRODUCT
).EXTRACT ('//text()'), ','
         ) AS PRODUCTS FROM     (
         SELECT   DISTINCT CUSTOMER, CUSTOMER_ID, PRODUCT
         FROM     MAGIC_TABLE
         ) GROUP BY CUSTOMER, CUSTOMER_ID ORDER BY 1 , 2

Still not exactly sure what the XML functions do exactly, but I'll dig in when the need arrises.


text:
Q: How to solve this probability distribution? A document containing 160 pages has 200 errors.
Find the probability that on page 102 and 103 will contain exactly three errors.
Is it using binomial distribution?
I have assigned p = 3/200 and q = 197/200
Is it correct ?
Please help me

A: There are $200$ errors and each of them "chooses" a page to stand on.
For every error the $160$ pages have equal chances to be chosen, so that the probability that it becomes one of the pages $102,103$ (a succes) equals $\frac2{160}=\frac1{80}$.
To be found is now $\Pr(X=3)$ where $X$ denotes the number of errors that chooses one of the pages $102,103$.
The distribution is binomial  with parameters $n=200$ and $p=\frac1{80}$.

A: As you try to solve this problem you soon realize that you must make some assumptions in order for it to be tractable. You tagged your question with two distribution tags. I gave up with one, so perhaps we can make hay with the Poisson distribution model.
OK here goes. You have 200 errors per 160 pages, or, on average, 200/80 = 2.5 errors per 2 pages. This feel promising since the question was asking for the probability of exactly 3 error per a given two page look-see.
Using the discrete Poisson model,
$ P(k{\text{ errors on two pages}})=e^{-\lambda }{\frac {\lambda ^{k}}{k!}} $, where $\lambda = 2.5$
So plug in $3$ for your answer.
Great, we got an answer. Now you have to justify why using this distribution makes sense.
The question starts off saying the document HAS 200 errors. What would make more sense is if we said that past experience with our typist leads us to estimate $\lambda$ as follows,...blah...blah...Poisson...blah...blah...blah...


text:
Q: filter the_title problem in nav Hi I have a problem with the_title filter:
I have this code at my constructor:
add_filter( 'the_title', array($this, 'change_title') );

and this as callback (for testing purposes)
 public function change_title($title)
 {
    return 'title';
 }

But is filtering my navigation items!
instead of show home, pages, etc all changed to 'title'

Any Ideas how to fix it?

A: You can try the in_the_loop() conditional to check if the context of the_title is within the loop.


text:
Q: Is there a difference between a for loop without increment vs. one with a non incremented variable? In JS, is there any difference between the following two types of loops?

*

*A for loop without an increment such as:
for (i = 0; i < 1000;) { // i will be changed inside the block

vs

*A for loop with a variable defined, but one that is not being incremented? Like this:
for (i = 0; i < 1000; i) { // i changed inside block

I saw this strange construct in several Stack Overflow questions.
i meant to note the i variable changes, not that i myself changed something or that i have been changed in some way.

A: Under normal circumstances: no, there is no difference.

The for statement creates a loop that consists of three optional
expressions, enclosed in parentheses and separated by semicolons,
followed by a statement (usually a block statement) to be
executed in the loop.

The three expressions (initialization, condition and final-expression) are all optional (unlike the semicolons themselves), so if you omit the final-expression (which is most commonly used to increment the i/index/counter) that part simply will not be used.
If you use an isolated i as the final-expression, then this will be evaluated after every iteration of the for-loop. But an isolated variable on its own usually doesn't have any side effects. The value wont change and the value that is returned by the i expression (the value of i) is ignored in case of the final-expression.

console.log('For loop without final-expression:');
for (let i = 0; i < 10;) {
  console.log(i++);
}

console.log('For loop with final-expression:');
for (let i = 0; i < 10; i) {
  console.log(i++);
}

But that is all under normal circumstances. There are cases where it does make a difference, but you really should never encounter this in production-ready code.

const target = {
  i: null,
};

const proxy = new Proxy(target, {
  get(target, prop) {
    if (prop === 'i') {
      return target._i++;
    }
    return Reflect.get(...arguments)
  },
  set(target, prop, value) {
    if (prop === 'i') {
      target._i = value;
    } else {
      return Reflect.set(...arguments);
    }
  }
});

with(proxy) {
  console.log('For loop without final-expression:');
  for (i = 0; i < 10;) {
    console.log("loop");
  }

  console.log('For loop with final-expression:');
  for (i = 0; i < 10; i) {
    console.log("loop");
  }
}

In the above example I used a Proxy to be able to intercept all access to the properties of an object and I used a with statement so that every variable is treated as a property of this proxied object. As a result, when i is read, the getter of the proxy is called, and I increment the value of i every time this happens.
In for (i = 0; i < 10; i), i is set once at i = 0 and read twice in i < 10 and the final-expression i. Because it is read twice, the i will be incremented twice, so the loop will only iterate 5 times. In the other for (i = 0; i < 10;) loop i is only read once, so the loop will iterate 10 times.
There are likely more ways to achieve a similar effect, but again you should really never encounter this in production ready code, so it shouldn't be taken into account when deciding if you want to keep the i in the final-expression or not.
Personally I would say that if you don't use an optional expression, then you should leave it out. Especially because when glancing over the code, i can be misread as i++ which might confuse the reader. But in the end it is a matter of taste.


text:
Q: How come a numpy array created from list can be 10x faster than that from np.zeros for incrementation? I am using python 3.8 and numpy 1.17.4.
The output of the following piece of code
import time
import sys
import numpy as np

if __name__ == '__main__':
  li = np.zeros(5000000,dtype=int)
  sys.stdout.write("%s %s\n" % (type(li),type(li[0])))
  start = time.process_time()
  li += 5
  sys.stdout.write("%.6fs\n" % (time.process_time()-start))
  li = np.zeros(5000000,dtype=int)
  li = list(li)
  li = np.array(li)
  sys.stdout.write("%s %s\n" % (type(li),type(li[0])))
  start = time.process_time()
  li += 5
  sys.stdout.write("%.6fs\n" % (time.process_time()-start))

looks like
<class 'numpy.ndarray'> <class 'numpy.int64'>
0.037046s
<class 'numpy.ndarray'> <class 'numpy.int64'>
0.003537s

How come the latter is 10x faster to increment?

A: It seems to me that the explanation is the same as here.
Indeed, numpy.zeros() seems to be a "lazy" operation. I modified your sample twice:

*

*I removed the two statements implying lists before the second measure => the two measures became identical

*I added a dummy operation in order to force numpy.zero() to really allocate the memory => the two measures become different again:

import time
import sys
import numpy as np

if __name__ == '__main__':
  li = np.zeros(5000000,dtype=int)
  sys.stdout.write("%s %s\n" % (type(li),type(li[0])))
  start = time.process_time()
  li += 5
  sys.stdout.write("%.6fs\n" % (time.process_time()-start))
  li = np.zeros(5000000,dtype=int)
  li += 0 #dummy operation
  sys.stdout.write("%s %s\n" % (type(li),type(li[0])))
  start = time.process_time()
  li += 5
  sys.stdout.write("%.6fs\n" % (time.process_time()-start))

A: Your time estimate may not be accurate. It uses a single iteration of the command which may be influenced by other factors. Using %timeit shows somewhat more consistent results even though the second method has a much higher standard deviation.
First method:
li = np.zeros(5000000,dtype=int)

%timeit zi = li + 5
12 ms ± 179 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Second method:
li = np.zeros(5000000,dtype=int)
li = list(li)
li = np.array(li)

%timeit zi = li + 5
13.3 ms ± 1.05 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)


text:
Q: New line character as part of the String I've got the problem creating String looking as follows:
"SSR LANG SA  HK1/EN;S7;P1\n"+

Code that does that should append \n as part of the string + quote + append string literal + actual new line literal:
javaFormattedText.append("   \""+ tokenizer.nextElement() + "\\n\"+\n");

The output String should look:
"SSR LANG SA  HK1/EN;S7;P1\n"+

But it looks:
"SSR LANG SA  HK1/EN;S7;P1
\n"+

Therefore java complains about unclosed string literal.
The purpose of doing it is generating test classes dynamically and those contain a lot of text information that needs to be java formatted strings.
How can achieve the target?
UPD
Solved the problem by doing this:
String line = (String) AIR_textTokenizer.nextElement();

line = line.replace("\n", "").replace("\r", "");

A: Your tokenizer.nextElement() is probably returning a trailing new line. To remove that:
String str = tokenizer.nextElement();
if (str.endsWith('\n')) {
    str = str.substring(0, str.length - 1);
}
javaFormattedText.append("   \""+ str +"\\n\"+\n");

A: If you watn to add line separator use: System.lineSeparator();


text:
Q: number of derangements In the normal derangement problem we have to count the number of derangement when each counter has just one correct house,what if some counters have shared houses.
A derangement of n numbers is a permutation of those numbers in which none of the numbers appears in its original place. For example, the numbers {1,2,3} can be deranged into {2,3,1} and {3,1,2}
But in our modified version no number in the derangement can be in the place that a number of the same value was in in the original ordering. So the numbers {1,1,2,2,3} could be deranged into {2,2,1,3,1}, {2,2,3,1,1}, {2,3,1,1,2}, and {3,2,1,1,2}.
How to go about it! any hints?

A: This is a permutation with forbidden positions.  Your specific problem corresponds to the board below, where $X$ in square $(i,j)$ denotes that element $i$ is not allowed to go to position $j$.
XXOOO
XXOOO
OOXXO
OOXXO
OOOOX
Let $r_i$ denote the number of ways to place $i$ rooks on the $X$ squares, such that none attack each other.
$r_1=9$,  because there are $9$ squares marked $X$.
$r_2=4^2+4+4+2+2$, because there are $4^2$ ways to pick one square from each of the $2\times 2$ grids, there are $4+4$ ways to pick one square from one of the $2\times 2$ grids plus the lower-right square, and there are $2+2$ ways to pick two squares from each of the $2\times 2$ grids.
You still need to find $r_3, r_4, r_5$.  It's fairly tedious but possible.  Then, the answer is $$5!-r_14!+r_23!-r_32!+r_41!-r_50!$$


text:
Q: How to sort the index of a xarray Dataset/DataArray? I am creating a DataArray from multiple slices along the time dimension and stumbled across the 'index must be monotonic for resampling' error when trying to resample which I guess says that my time index is not sorted. I did not pay attention to the order in when I concat()inated them.
# TODO: sort instead of raising an error
is to be found in the code where the error is raised.
My question: How would I sort the indices of my DataArrays within a DataSet? I could not find anything like sort_index().

A: There is now a sortby() method which can be used.
da = da.sortby('time')

A: You could reindex on the sorted index - .reindex(time=sorted(dataset.time))
Not as elegant as sort_index() but it should work
EDIT: @scottclowe points out that xarray since added .sortby(), so use that! http://xarray.pydata.org/en/stable/generated/xarray.DataArray.sortby.html

A: I had to add .values to get sorted to work correctly. Where my time.values is a datetime64[ns]. Xarray v0.10.0.
.reindex(time=sorted(dataset.time.values))