text:
Q: accessory button not working I have the following code which tries to add a accessory view, but I can't see anything
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    }

    //add a button to set to accessory view
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"addsource.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(changeButton:) forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundColor:[UIColor clearColor]];
    cell.accessoryView = button;

A: You created your button programmatically, not in the IB (where you would place it somewhere on the view of cell), so you have to assign a frame position/size as well.
E.g., for just a test try something like this:
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(200, 20, 20, 20);
[button addTarget:self action:@selector(changeButton:) forControlEvents:UIControlEventTouchUpInside];
[button setBackgroundColor:[UIColor blackColor]];
cell.accessoryView = button;


text:
Q: Problem with Tapestry palette's arrow icons in IE8 I'm using Tapestry to create pages for a web app, and have been using the palette component to add/delete items to/from a group.
The page looks great in Firefox (Tapestry seems biased towards Firefox), but my customers will all be using Internet Explorer (any versions from 6, 7, & 8) and in IE8, the disabled arrow buttons look awful.  In Firefox, they are faded, using an opacity setting of 25%, but this doesn't work in IE8 and instead you get a faded image with an ugly black border around the image.
In tapestry-core's stylesheet (default.css), you have the following for a disabled arrow button.
DIV.t-palette-controls BUTTON[disabled] IMG {
    filter: alpha(opacity = 25);
    -moz-opacity: .25;
}

These are clearly out of date, as -moz-opacity is no longer supported by Firefox (use opacity: 25 instead).  The problem is with filter: "alpha(opacity = 25);".  If I remove this, the arrows look fine in IE8, but they are not faded.
I got the magic instruction:
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=25)";

from various websites, but putting this in does not work either - the arrow icons are ugly again.
The icon itself (distributed with Tapestry) just seems to be a regular PNG, but I'm not an expert on image formats, so maybe there's a problem there?
Anyone else had this problem?

A: I'm not entirely sure, but could be that -ms-filter needs to be in the correct order and also have the other properties (like the hasLayout hack) set:
try this:
DIV.t-palette-controls BUTTON[disabled] IMG {
    opacity:0.25; /* firefox, opera, safari, chrome */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(opacity=25)"; /* IE 8 */
    filter:alpha(opacity=25); /* IE 4, 5, 6 and 7 */
    zoom:1 /* so the element "hasLayout"
    /* or, to trigger "hasLayout" set a width or height */
}

Source and Explanation

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is particular meaning of the verb "pitch" here? What is particular meaning of the verb "pitch" here? Are there any appropriate synonyms of it?

In the process of writing this article I came across one email from 11
  years ago. It turns out I pitched this exact piece— the one you are
  reading right now — as a commentary to NPR, under the title "Mining My
  Own Data".

It has a very wide definition: www.thefreedictionary.com/pitch.

A: From your dictionary.com link, this meaning is correct:
35. (Marketing) slang: a persuasive sales talk, esp. one routinely repeated
The term is used in sales, business, or marketing to describe when someone has an idea she is selling. Another person hearing the pitch may make the decision to buy or fund that idea. The term is used widely across industries.
For further clarification, there's an entire show where people pitch products and ideas: http://www.scienceofpeople.com/2014/01/pitch-idea-shark-tank/

A: Pitch (Flip, Toss) Verb
throw or toss with a light motion
Example
flip me the beachball.
Pitch (Lurch, Shift) Verb
move abruptly
Example
The ship suddenly lurched to the left.
Pitch Verb
fall or plunge forward
Example
She pitched over the railing of the balcony.
Source http://hindi.wordinn.com/pitch


text:
Q: IE select visible although its parent is hidden I have a dynamic HTML document, and in a particular point of time it has a markup similar to this (but, of course, a lot more complex):

    <select><option>some text</option></select>

    Some text

and my problem is that in IE 6, the select is still visible even though its parent is set as display: none. Has anyone else encountered this issue? I think I recall seeing this issue with checkboxes as well a long time ago. Other browsers work (of course), including IE8.
Of course, if you try just looking at this snippet in IE6, there will be no problem. It's a bug that is just triggered by doing things in the right order.

A: I can't reproduce the problem, tried on ie6 and it is not showing the select.
Can you place more of the code, to include the js you're using.
Also, ie6 tends to throw a hissy fit when it encounters little things.
Try adding a ";" to the end of your css. As per below:
Haven't seen your code but this could be all it takes to make ie behave.

A: Althoug I'm not sure, I think I hit this issue

A: I ran into a problem like this as well. For me invisible select boxes would suddenedly become visible when I emptied them like this:
select.empty();

I found that emptying the select box without jQuery resolved the problem:
select[0].options.length = 0;

However, this introduced a new problem the next time I called select.val() IE6 would throw the error "Could not set the selected property. Unspecified error."
Ironically I found another solution by calling select.show() after the select.empty() call. I am guessing that show() tricks the browser into recalculating the visibility based on the parent. This allows it to realize that the element shouldn't be visible in the first place. So this is what worked for me:
select.empty()

// some code to repopulate the list

select.show();


text:
Q: on_exit and CTRL+C I've got a small program that opens a file and does some operation on it. I subscribed the file closure to the program termination as follows:
static
void exit_handler (int ev, void *arg)
{
    fprintf(stderr, "bye %d\n", WEXITSTATUS(ev));
    fclose((FILE *)arg);
}

int main (int argc, char *argv[])
{
    FILE *out;

    ...

    out = fopen(argv[1], "wt");
    if (out == NULL) {
        perror("Opening output file");
        exit(EXIT_FAILURE);
    }
    on_exit(exit_handler, out);

    ...
}

Trying to execute this I notice that it works properly only if the program terminates normally. In case of CTRL+C (SIGINT) the exit_handler callback is not executed.
Isn't that weird? Should I associate a exit(EXIT_FAILURE) call to the signal handler for SIGTERM? What is the best practice in this case?

A: on_exit will not be invoked for SIGTERM signals. You need to add a handler for it with signal. For example:
void signalHandler(void)
{
  ...
}

int main(void)
{
  signal(SIGTERM, signalHandler);
}

Also note that SIGKILL can not be caught by design.

A: First of all, on_exit isn't specified by POSIX (atexit with the same semantics is). Second , the linux manual says:

The on_exit() function registers the given function  to  be  called
  at normal process termination, whether via exit(3) or via return from
  the program's main().

Getting killed by a signal is not a normal exit for a process so callbacks installed with on_exit and atexit aren't implicitly called.

A: No, and in fact what you want is impossible. The signal generated by Ctrl+C is asynchronous, meaning it could occur between any two machine instructions in your program depending on when Ctrl+C is hit. As such, unless your program is thoroughly avoiding calling async-signal-unsafe functions anywhere in the main program flow, it's illegal to call async-signal-unsafe functions from the signal handler. exit is async-signal-unsafe, as is most of the default cleanup activity it does (like flushing/closing open files). I would expect the atexit function you want to register (atexit, not on_exit, is the correct name for this function) is also going to want to do async-signal-unsafe things.
If you need to perform cleanup when exiting based on a signal, you need to install a signal handler that does not exit itself, but instead sets a global volatile flag that your main program flow will later inspect (and exit if it's true).

A: From man page of on_exit,

The on_exit() function registers the given function to be called at
  normal process termination, whether via exit(3) or via return from the
  program's main().

So you need to explicity hook up a handler for SIGTERM using specific functions from signal.h
Something on the lines of
struct sigaction action;

memset (&action, 0, sizeof(action));
action.sa_handler = sigterm_handler;

if (sigaction(SIGTERM, &action, 0))
{
    perror ("sigaction");
    return 1;
}

/* SIGTERM handler. */
static void sigterm_handler (int sig)
{
...
}


text:
Q: Notation for some simple operator Let $X$ a functional space space (I mean a space whose elements are functions). Let $f \in X$. Say I define these two operator (argument scaling and argument translation as follows)
$S_\alpha$ is a scaling operator means that $$\forall f \in X, S_\alpha f = g, g(x) = f(\alpha x).$$
$T_{x_0}$ is a translation operator means that
$$ \forall f \in X, T_{x_0} f = g, g(x) = f(x - x_0).$$
I think that notation is correct so far. Would be correct to write
$$
\begin{array}{l}
S_{\alpha} f = f(\alpha x) \\
T_{x_0} f = f(x - x_0)
\end{array}
$$
Or shall I write something like
$$
\begin{array}{l}
\left(S_{\alpha} f \right)(x) = f(\alpha x) \\
\left(T_{x_0} f \right)(x) = f(x - x_0)
\end{array}
$$
Also for the derivative
$$
\frac{d}{dx} f = f^{(1)}(x)
$$
or
$$
\left(\frac{d}{dx} f\right)(x) = f^{(1)}(x)
$$
(Maybe the last one can sound silly, but sometimes I'm puzzled in the meanings)

A: $S_\alpha f$ is a function. It is defined by the expression for its values at an arbitrary $x$, namely $(S_\alpha f)(x) = f(\alpha x)$. The function $S_\alpha f$ should not be confused with $(S_\alpha f)(x)$, which is merely its value at $x$. You argue similarly for the correct notation in all the other definitions.
It's no different from the distinction we make with any other function and its values. For example, the exponential function $\exp:\mathbb{R}\to\mathbb{R}$ is not the same as $\exp(x), x\in\mathbb{R}$: the first is a function $\mathbb{R}\to\mathbb{R}$, the second is just an element of $\mathbb{R}$ (provided that $x$ is given). The tendency to identify the function $\exp$ with its values $\exp(x)$ is merely an abuse of notation.


text:
Q: how to map an element in a list to a value from other list in LISP I am new to lisp programming and i am trying to think about the below operation.
(extract '(0 1 0) '(a b c)) give us  '(a b a)
(extract  '(1 1 1 ) '(a b c)) gives us '(b b b)
how can i think about this and how to solve it.

A: As Chris Jester-Young described, it just returns elements from second list at indexes in first list. Writing such a function is very easy:
(defun extract (list-1 list-2)
  (mapcar (lambda (n) (nth n list-2)) list-1))

CL-USER>(extract '(0 1 0) '(a b c))
(A B A)
CL-USER>(extract '(1 1 1 ) '(a b c))
(B B B)

If there no such index, it'll give you NIL in that place.
CL-USER> (extract '(1 100 1 ) '(a b c))
(B NIL B)

But this won't work on nested structures (trees). If you want it to return elements of list-2 shaped in the structure of list-1, you can use a simple maptree helper function, then do the same thing:
(defun maptree (fn tree)
  (cond
    ((null tree) tree)
    ((atom tree) (funcall fn tree))
    (t (cons
     (maptree fn (first tree))
     (maptree fn (rest tree))))))

(defun extract* (list-1 list-2)
  (maptree (lambda (n)
             (nth n list-2)) list-1))

CL-USER> (extract* '(3 (2 1 (0))) '(a b c d))
(D (C B (A)))

A: (extract a b) returns a copy of a where each element is replaced by the element of b in that position.


text:
Q: Fix broken DNSSEC I have transferred a .com domain from Namecheap to EuroDNS.
Since that day I have the problem that the domain does not resolve from all DNS servers, e.g.:
$ host -a flibsy.com 8.8.8.8
Trying "flibsy.com"
Using domain server:
Name: 8.8.8.8
Address: 8.8.8.8#53
Aliases:

Host flibsy.com not found: 2(SERVFAIL)
Received 28 bytes from 8.8.8.8#53 in 77 ms

Someone suggested me that I have "broken DNSSEC", as can be seen here:
http://dnsviz.net/d/lxsky.flibsy.com/dnssec/ and http://dnsviz.net/d/flibsy.com/dnssec/
EuroDNS told me they do not support DNSSEC.
How can I fix this issue?

A: If your DNS service provider doesn't support DNSSEC, you have exactly two options:

*

*Switch to a provider that does support DNSSEC.

*Disable DNSSEC by contacting your registrar.
It seems that EuroDNS is both your dns provider and your registrar. The deactivation process is probably just like their activation process, but instead of adding a key you'll remove it.


text:
Q: Transfer data from html to php page using anchor tag I am trying to figure out a simple way to transfer data from a html to a php page using achor tag.
Code on page1.html:

Code on page 2(product_detail.php):

<?php
if(isset($_GET['var1'])){
$data1 = $_GET['var1'];
 }
?>

I'm getting following error message:
Notice: Undefined index: var1 in C:\xampp\htdocs\gaming\product_detail.php on line 201
UPDATE: Renaming var1 to variable1 and restarting browser solved the problem

A: Use below code
<?php
   if (isset($_REQUEST['var1'])) {
       $data1 = $_REQUEST['var1'];
   }
?>


text:
Q: php link to another page im editing a wordpress theme for my own personal website. The page is for a blog, and what is meant to happen is that when you click on the 'read more' or blog title then it will open that  blog in the seperate page to read. however when i click these 2 things i get the following message:

Server error The website encountered an error while retrieving
  mywebsite/wordpress/?p=20. It may be down for maintenance or
  configured incorrectly. Here are some suggestions: Reload this web
  page later. HTTP Error 500 (Internal Server Error): An unexpected
  condition was encountered while the server was attempting to fulfil
  the request.

it was previously working before so i know the code that came with the theme worked. heres the code:

<?php while ( have_posts() ) : the_post(); ?>

<a href="<?php esc_url( the_permalink() ); ?>"<?php the_title(); ?>" rel="bookmark"><?php the_title(); ?>

            <h7>BY LOUIS MOORE ON</h7> <time datetime="<?php the_time( 'Y-m-d' ); ?>" pubdate><?php the_date(); ?> <?php the_time(); ?></time><?php the_content(); ?>
<a href="<?php esc_url( the_permalink() ); ?>"/><h8>READ MORE</h8>

<?php endwhile; ?>

im not the gretest at php and i havent really changed it from its original form other than the things such as 'read more' 'by louis moore' the second div and the

A: There are several errors in the HTML code. Maybe that's the problem.
You may try this:

  <?php while ( have_posts() ) : the_post(); ?>

<a href="<?php esc_url( the_permalink() ); ?>"> <?php the_title(); ?>" rel="bookmark"><?php the_title(); ?>

    <h7>BY LOUIS MOORE ON</h7>
    <time datetime="<?php the_time( 'Y-m-d' ); ?>"> pubdate><?php the_date(); ?> <?php the_time(); ?></time><?php the_content(); ?>
    <a href="<?php esc_url( the_permalink() ); ?>">
    <h8>READ MORE</h8>

  <?php endwhile; ?>


text:
Q: what is the correct way to clear quartz.net ramjobstore without re-starting app in c# If there is a way to do this , can I also confirm by viewing the ramstore before and after clear. How can we view the contents of the ramstore programmatically ? In my case I am reading all job and trigger info from file. On some custom event I need to stop the scheduler and start all over again without re-starting the app.
thank you

A: The RamJobStore from the Quartz.NET frameworks provides several methods to view it's contents, the easiest is the 'GetJobGroupNames()' and 'GetJobNames()' functions:
public virtual string[] GetJobGroupNames(
  SchedulingContext ctxt
)

public virtual string[] GetJobNames(
  SchedulingContext ctxt,
  string groupName
)

You can use it like this:
foreach(string group in ramstore.GetJobGroupNames(...))
  foreach(string job in ramstore.GetJobNames(..., group))
    MessageBox.Show(String.Format("{0} (Group: {1})", job, group));

Of course this is not what you want, since it will just show a message box for all the jobs you have in your RamJobStore, but it does allow you to view the contents of the entire store. Furthermore you can now use two methods to remove all the jobs. You can either use the function 'RemoveJob()' or 'Shutdown()'.
foreach(string group in ramstore.GetJobGroupNames(...))
  foreach(string job in ramstore.GetJobNames(..., group))
    ramstore.RemoveJob(..., job, group);

This will just remove all the jobs on the object, but might be time consuming on large store(s). Therefore there is also a 'Shutdown()' function, which just removes the entire store from memory (after which you can create a new one).
I put ... in some of the function(s), which is your SchedulingContext you've used to store the jobs in the first place.

A: fyi from the documentation:
Never use a JobStore instance directly in your code.
For some reason many people attempt to do this.
The JobStore is for behind-the-scenes use of Quartz itself.
You have to tell Quartz (through configuration) which JobStore
to use, but then you should only work with the Scheduler interface
in your code.

Found Here: http://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/job-stores.html
In my limited experience with quartz, i would think you could just grab the contents of the scheduler and then shut down the scheduler and start a new one?


text:
Q: InternetExplorerDriver may have died - Selenium issue I am using Selenium Grid to start an InternetExplorerDriver-Instance remotely. Therefore I use the following code:
DesiredCapabilities capability = (DesiredCapabilities) DesiredCapabilities.internetExplorer();
RemoteWebDriver driver = new RemoteWebDriver(new URL(getHubUrl()), capability);

At the second line of code there is a WebDriverException saying

Error communicating with the remote browser. It may have died.

The remote machine is a Windows 7 system. I can't understand why this won't work?!

A: We have the same error on Windows 7 too but it works on Ubuntu.
What version of Selenium do you use, 2.20.0? Have you already tried to upgrade onto 2.21.0?

A: Also, are you setting up the path to the InternetExplorerDriver? See this question here on SO - it helped me a lot launching the Google Chrome

A: Problem
I had the same problem running InternetExplorerDriver locally in Windows 7 - (IEDriverServer_Win32_2.42.0.zip)
org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died.

When I checked the running processes under TaskManager, there were multiple IEDriverServer.exe processes running, that hadn't been cleaned up properly.
Solution
Running the following command, killed all running IEDriverServer.exe processes, and resolved this issue (for me).
taskkill /F /IM IEDriverServer.exe


text:
Q: How to use mousebuttons in pygame? hi im new to pygame and i'm creating virtual version of board game which i created.
so for now im playing arond in pygame and i want to change my code where i use w and d for moving piece to code where i ll use mouse cliclicks to move my pieces
here is code:
if event.type==pygame.KEYDOWN and event.key==pygame.K_w:
    y-=z
if event.type==pygame.KEYDOWN and event.key==pygame.K_d:
    x+=2*z
    y-=2*z
if event.type==pygame.KEYDOWN and event.key==pygame.K_a:
    x-=2*z
    y-=2*z

A:
http://www.pygame.org/docs/ is the main documentation for Pygame
http://www.pygame.org/docs/ref/mouse.html is the mouse documentation
http://www.pygame.org/docs/ref/event.html is the event documentation

I suggest the book "Hello World!" by Carter and Warren Sande to learn the basics of Python and Pygame.
Here is some sample code for pygame mouse and key presses:
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
clock = pygame.time.Clock()

while 1:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            print "A key was pressed!"
        if event.type == pygame.MOUSEBUTTONDOWN:
            print "A button was clicked!"

A: Here is code i came up with:
import pygame,sys
import math
from pygame.locals import*
pygame.init()

black=(0,0,0)
white=(255,255,255)
w=500
h=500
p=0
root=pygame.display.set_mode((w+50,h),0,32)
pygame.display.set_caption('Clash of Hunters')
clock = pygame.time.Clock()

def mainloop():
    global p
    running=False
    marksman=pygame.image.load('resized.png').convert_alpha()
    background=pygame.image.load('board.png').convert()
    dael=pygame.image.load('dael.png').convert_alpha()
    x=14;y=457;z=55;k=10;x1=240;y1=17
    root.blit(marksman,(x,y))
    root.blit(dael,(x1,y1))
    while not running:
        clock.tick(60)
        for event in pygame.event.get():
            mouse=pygame.mouse.get_pos()
            d=math.sqrt(math.pow(mouse[0]-x,2)+ math.pow(mouse[1]-y,2))
            if event.type== pygame.QUIT or event.type==pygame.KEYDOWN and event.key==pygame.K_ESCAPE:
                pygame.quit()
                quit()

            #moving in action

            #elif event.type==pygame.KEYDOWN and event.key==pygame.K_e:
                #x+=2*z
                #y-=2*z
            #elif event.type==pygame.KEYDOWN and event.key==pygame.K_q:
                #x-=2*z
                #y-=2*z
            #elif event.type==pygame.KEYDOWN and event.key==pygame.K_d:
                #x+=2*z
           # elif event.type==pygame.KEYDOWN and event.key==pygame.K_a:
                #x-=2*z
            elif x>w:
                x-=2*z
            elif x<0:
                x+=2*z
            elif  y<=30:
                root.blit(marksman,(514,466))
            else:
                if pygame.mouse.get_pressed()[0]==1:
                    if d<30:
                        x=mouse[0]
                        y=mouse[1]
                root.blit(background,(0,0))
                root.blit(marksman,(x,y))
                root.blit(dael,(x1,y1))

        pygame.display.update()
mainloop()


text:
Q: Is that possible to pass data to different activity using intent but not start that particular activity? I want to pass data to another activity but doesn't want to start the new activity.
Is it possible? If yes then how can i achieve it?

A: One simple solution is that make a static variable in the other activity. You can set the data from previous activity to the new activity by simply setting this variable value.
class NewActivity extends AppCompatActivity{
    public static String variable = null;

}

class OldActivity extends AppCompatActivity{

    public void xxxx(){
        NewActivity.variable = "something";
    }

}

But Note that static variable approach is bad.
If you really need this approach, then make it null when you don't need it anymore.

A: If your question is in term of activity or intent I don't think so it is possible..
if you want to pass data with intent you have to start activity.
1)If you want to do some task without UI then Create service from your first activty.
2)Or you can save that data to some static variable and then use it in you second activity.


text:
Q: Development with Apache Spark I am new with Spark and I wanted to ask some common guidelines about developing and testing my code for Apache Spark framework

*

*What is the most common setup to test my code locally? Is there any
built VM to raise (ready box etc.)? Do I have to setup locally spark? Is there any test library to test my code?

*When going in cluster mode I notice that there are some ways to
setup your cluster; production wise, what is the most common way to
setup a cluster to run Spark? Three options here

*

*Standalone cluster setup

*With YARN

*With MESOS
Thank you

A: 1) Common setup: Just download the Spark version on a local machine. Unzip it and follow these steps to set it up locally.
2) Launching a cluster for production:  The Spark cluster mode overview available here explains the key concepts when running a Spark cluster. Spark can be run both in a standalone way and on several existing cluster managers. Currently, several deployments options are available:

*

*Amazon EC2

*Standalone mode

*Apache Mesos

*Hadoop YARN
EC2 scripts let you launch a cluster in about 5 minutes. In fact, if you are using EC2, the best way to go is using the script provided by spark. The standalone mode is the best for the deployment of Spark on a private cluster.
Normally, we use YARN as cluster manager when we have an existing Hadoop setup with YARN, and the same goes for Mesos. Instead, if you are creating a new cluster from the dust, I would recommend using the Standalone mode, considering you are not using Amazon's EC2 instances. This link shows some steps that help arranging a Standalone Spark cluster.

A: Sandbox from Hortonworks hope will help.
HDP 2.2.4 Sandbox with Apache Spark & Ambari Views
http://hortonworks.com/products/hortonworks-sandbox/#install
Second resource I'm using is http://www.cloudera.com/downloads/quickstart_vms/5-8.html
The image does contain Hadoop, HBase, Impala, Spark and many more features.
Does require 4gb RAM, 1 CPU and 62.5GB disk. Kind large but is free and does fulfill all requirements rather paid versions on cloud.

A: I am using Sandbox from Hortonworks. It has hadoop, java and all the required environment to run the spark examples.
I would suggest you to write simple Java or Scala class in your IDE. Create SparkConf and SparkContext objects in your "SimpleApp.java".
SparkConf conf = new SparkConf().setAppName(appName).setMaster("local[2]");
JavaSparkContext sc = new JavaSparkContext(conf);

Once you run maven clean package or maven package it will create jar file in your project's target folder. If it doesn't then create a JAR file using following command. You can find the SimpleApp.class file in "target/classes" folder. cd to this directory.
jar cfve file.jar SimpleApp.class

Put this JAR file into your project in target directory. This JAR file contains the dependency of your SimpleApp class while submitting your job to Spark. I guess you have project structure like below.
simpleapp
 - src/main/java
  - org.apache.spark.examples
    -SimpleApp.java
 - lib
  - dependent.jars (you can put all dependent jars inside lib directory)
 - target
  - simpleapp.jar (after compiling your source)

cd to your spark directory. I am using spark-1.4.0-bin-hadoop2.6. Your cmd looks like this.
spark-1.4.0-bin-hadoop2.6>

Start the master and worker using following commands.
spark-1.4.0-bin-hadoop2.6> ./sbin/start-all.sh

If this does not work then start master and slaves separately.
spark-1.4.0-bin-hadoop2.6> ./sbin/start-master.sh
spark-1.4.0-bin-hadoop2.6> ./sbin/start-slaves.sh

Submit your spark program using Spark Submit. If you have structure like I explained then pass this argument in class.
--class org.apache.spark.examples.SimpleApp

else
--class SimpleApp

Finally submit your spark program through spark submit.
spark-1.4.0-bin-hadoop2.6>./bin/spark-submit --class SimpleApp --master local[2] /PATH-TO-YOUR-PROJECT-DIRECTORY/target/file.jar

Here I have used local[2] as a master so my program will run on two threads but you can pass your master URL in --master as a --master spark://YOUR-HOSTNAME:7077
Port number 7077 is a default port number for Master URL.

A: For development and testing, I recommend using sbt in local mode so that you can avail yourself of the test suites you will write for your code. The following advice is verbatim from Matei Zaharia regarding Spark development, and it's always worked for me:
"As a tip (and maybe this isn't documented well), I normally use SBT for
 development to avoid the slow build process, and use its interactive
 console to run only specific tests. The nice advantage is that SBT can keep
 the Scala compiler loaded and JITed across builds, making it faster to
 iterate. To use it, you can do the following:

*

*Start the SBT interactive console with sbt/sbt

*Build your assembly by running the "assembly" target in the assembly
project: assembly/assembly

*Run all the tests in one module: core/test

*Run a specific suite: core/test-only org.apache.spark.rdd.RDDSuite (this
also supports tab completion)"

Source:
http://mail-archives.apache.org/mod_mbox/spark-dev/201412.mbox/%3cCAAsvFP=V9FL=KvXNUeWVfFz8q04oj1exdwSaSNiab5Vc9hFkUg@mail.gmail.com%3e


text:
Q: Using clevertap-react-native npm package, iOS push notification not working We are using:

*

*react-native - 0.51.0 and

*clevertap-react-native - 0.2.1

Here https://www.npmjs.com/package/clevertap-react-native we followed all the instructions and SDK integration steps for ios.
Also added Clevertap.registerForPush(); in root file of project. But still Mobile push notification are not getting enabled in Clevertap Dashboard.
Here you can see, Mobile Push Notification in Clevertap Dashboard

A: Can you verify once that you've enabled the support of the push notifications for your application?
You can check the same by following steps:
In Xcode, go to your Targets, under your app's name, select Capabilities and find Push Notifications in the list, switch to ON
Helping Link: https://help.apple.com/xcode/mac/current/#/devdfd3d04a1

A: Hey this issue has resolved. There was firebase configuration code in my appDelegate.m because of that FCM token was getting generated.
After removing firebase code from AppDelegate.m; iOS push notification working.


text:
Q: Possible to add some static data to TreeView within Glade? I have seen the existing question but I am not sure if adding actual data in Glade is possible or not.
I have created a TreeView and added two columns. I created a TreeStore and set it to the TreeView. And how can I add some static data like the following within Glade?
Jane 10
Tom  20
Mike 30
Mary 40

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.40.0 -->
<interface>
  <requires lib="gtk+" version="3.18"/>
  <object class="GtkTreeStore" id="treestore1">
    <columns>
      <!-- column-name name -->
      <column type="string"/>
      <!-- column-name age -->
      <column type="int"/>
    </columns>
  </object>
  <object class="GtkWindow" id="MainWindow">
    <property name="can-focus">False</property>
    <property name="title" translatable="yes">Example Window</property>
    <property name="default-width">480</property>
    <property name="default-height">240</property>
    <child>
      <object class="GtkTreeView">
        <property name="visible">True</property>
        <property name="can-focus">True</property>
        <property name="model">treestore1</property>
        <property name="enable-grid-lines">both</property>
        <child internal-child="selection">
          <object class="GtkTreeSelection"/>
        </child>
        <child>
          <object class="GtkTreeViewColumn" id="1">
            <property name="resizable">True</property>
            <property name="sizing">autosize</property>
            <property name="title" translatable="yes">Name</property>
            <property name="clickable">True</property>
            <property name="reorderable">True</property>
            <property name="sort-indicator">True</property>
            <child>
              <object class="GtkCellRendererText">
                <property name="text">Doge</property>
              </object>
            </child>
          </object>
        </child>
        <child>
          <object class="GtkTreeViewColumn" id="2">
            <property name="resizable">True</property>
            <property name="sizing">autosize</property>
            <property name="title" translatable="yes">Age</property>
            <property name="clickable">True</property>
            <property name="reorderable">True</property>
            <property name="sort-indicator">True</property>
            <child>
              <object class="GtkCellRendererText">
                <property name="text">10</property>
              </object>
            </child>
          </object>
        </child>
      </object>
    </child>
  </object>
</interface>

A: Data are stored in a store, such as GtkListStore, not in the view. To add them, click the store the widget on the glade.
At the bottom right corner of the image below, there are options to Add and remove rows.

Moreover, to associate the view with the store, the Text option in the cell renderer must be set to the corresponding store column.


text:
Q: middleware performing on all functions instead of ones just specified I have this middleware function:
 function authCheck (req, res, next) {
    if (req.session.loggedin) {

        next();

    } else {

        req.session.destroy();
        res.redirect('/login')

   }

}

module.exports = { authCheck }

I then retrieve it on my index.js page, in my root dir
const { authCheck } = require('./middleware/auth')
app.use(authCheck)

it works a little to good to say the least. Basically, I have a routes folder, and in there I have a file called payments.js. Inside that file, I have this:
 const {
    response
} = require("express");
var express = require("express");
const session = require('express-session');
var ibmdb = require("ibm_db");
var alert = require("alert");
const {
    render
} = require("ejs");
var nodemailer = require("nodemailer");
const bcrypt = require("bcrypt");
const http = require('http').Server(express);
const io = require('socket.io')(http);
const saltRounds = 10;
var crypto = require("crypto");

const app = express();

//initialize session
app.use(session({
    secret: 'secret-key',
    resave: false,
    saveUninitialized: false,
    maxage: 10
}))

app.get('/payment', (req, res) => {
    res.render('paymentCode.ejs')
})

app.post('/paymentsPage', (req, res) => {
    var userCode = req.body.code;

    var code = "select * from testclients"
        ibmdb.open(ibmdbconnMaster, function(err, conn) {
            if (err) return console.log(err);
            conn.query(code, function(err, rows) {
                if (err) {
                    console.log(err);
                }

                for(var i = 0; i < rows.length; i++) {
                    if (rows[i]["CODE"] != userCode) {
                        console.log("unsuccessful")
                    } else {
                        res.render("makePayment", {
                            page_title: "makePayment",
                            data: rows,
                        })
                    }
                }

                conn.close(function() {
                    // console.log("closed the function /index");
                });
            });
        });
})
module.exports = app

standard stuff. by no means do I have authCheck anywhere to be found there, but for some strange reason, it is performing the authCheck functionality on this function, although I don't need it to. is this normal, or am I missing something? I can share index.js page if needed

A: The problem here is you are using the same app instance you exported from payments.js. So when you do a app.use(authCheck) in your index.js it is applying that middleware to entire application not to specific routes.
In order to achieve what you want you can use express.Router.
See this link https://expressjs.com/en/guide/routing.html
Here is some example code from the link above.
This is your payments.js (Ignore the routes)
var express = require('express')
var router = express.Router()

// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
  console.log('Time: ', Date.now())
  next()
})
// define the home page route
router.get('/', function (req, res) {
  res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
  res.send('About birds')
})

module.exports = router

And in your index.js use it like this:
var payments = require('./payments.js')

// ...

app.use('/payments', payments)

Edit: I have just pasted this sample code from documentation just to demonstrate how you can use express.Router to apply middlewares for specific routes. Please refer to documentation for clearer understanding.

A: Since you have added middleware as
app.use(authCheck)

of course, it should be called for all endpoints in your service.
If you need to specify a middleware for specific routes, you can do it by
router.get('/user', authCheck, function (req, res) {
  res.send('Profile')
})

Or, you can specify the logic in you're middleware, to ignore the routes, which don't need authentication, You can do it by regex, or by checking specific routes and use app.use(authCheck) in the root.
For instance
 function authCheck(req, res, next) {
    const nonSecurePaths = ['/user', '/example'];
    if (req.session.loggedin || nonSecurePaths.includes(req.path)) {
        next();
    } else {
        req.session.destroy();
        res.redirect('/login');
    }
}


text:
Q: Passing arguments through an abstract class to the grandparent class's constructor I have a class Grandparent which is provided by a library. I'd like to define an interface for subclasses of Grandparent, so I created an abstract subclass called Parent:
class Grandparent {
    public:
        Grandparent(const char*, const char*);
};

class Parent : public Grandparent {
    public:
        virtual int DoSomething() = 0;
};

The constructor for Grandparent takes two arguments. I'd like my child class, Child, to also have a constructor with two arguments, and just pass these to the constructor for Grandparent… something like
class Child : public Parent {
    public:
        Child(const char *string1, const char *string2)
        : Grandparent(string1, string2)
        {}

        virtual int DoSomething() { return 5; }
};

Of course, Child's constructor can't call its grandparent class's constructor, only its parent class's constructor. But since Parent can't have a constructor, how can I pass these values to the grandparent's constructor?

A: Parent can certainly have a constructor. It must, if it's going to call the Grandparent constructor with any parameters.
There's nothing forbidding abstract classes from having constructors, destructors, or any other kind of member function. It can even have member variables.
Simply add the constructor to Parent. In Child, you'll call the Parent constructor; you can't "skip a generation" with constructor calls.
class Parent: public Grandparent
{
public:
  Parent(char const* string1, char const* string2):
    Grandparent(string1, string2)
  { }
  virtual int DoSomething() = 0;
};

A: If you want something else than the default constructor for Parent, you need to provide it.
Check out this question about inheriting constructors
Also, see this example of an abstract class


text:
Q: Installing a package from source? I'm trying to install an older version of the phylogenetics package "geiger" on R.  I'm on a Windows XP machine. I've tried the following construction:
install.packages(C:\geiger_1.3-1.tar.gz, repos = NULL, type = "source")

And every permutation I can think of for it.
Does anyone have any ideas?
Edit: the error returned is:
Error: unexpected input in "install.packages(C:\"

A: shouldn't you pass the file name as a string (or better yet w/ file.path)? e.g. install.packages(file.path("geiger_1.3-1.tar.gz"), repos = NULL, type = "source") Remember that installing packages you need to pass a string where loading libraries you can pass an unquoted name (or a string).
Responding to your comment here so I can have formatting
So you wrote install.packages(C:\Rfiles("geiger_1.3-1.tar.gz"), repos = NULL, type = "source"). Remember that the first argument to install.packages has to be a character vector. What you've passed in is C:\Rfiles("geiger_1.3-1.tar.gz") which isn't really anything. Take a look at help(file.path) and help(install.packages) to see some examples of how to specify the file path. In this specific case you should try:
g.path <- file.path("C:", "Rfiles", "geiger_1.3-1.tar.gz")
install.packages(g.path, repos = NULL, type = "source")

That's (as best as I can tell) the absolute path to your package, with no worrying about the backslash/forwardslash issue.

A: Thanks very much for your suggestions.  I finally solved it through the use of another package: "repmis".  This package includes a command called "InstallOldPackages", which does just that.  You can specify the package name and the version number you need.

A: On Windows, you typically need to switch backslashes \ to forwardslashes / or you will have an error.  I suspect:
install.packages("C:/geiger_1.3-1.tar.gz", repos = NULL, type = "source")

will work for you.  This is probably the simplest way.


text:
Q: Find surface edge from signed distance function & derivative I have a signed distance function that describes a mesh in 3D space. I have a few points given in space that mark the exact location of a sign change. Additionally, to each of those points I have the normal vector of the function at that point.
Now my question is: it possible with the given data (& if so how) to calculate the underlying surface edge ?
What I am basically looking for is nothing but a directional vector. The problem is really easy to solve in 2D. Since I have the normal, all I gotta do is to calculate a vector that is perpendicular to that normal.
But there's an infinite amount of perpendicular vectors to a vector in 3D, so that doesn't seem to work here...
Here is a visualtion of what I might have. In 2D just to keep it simple. Again, I am looking for a solution in 3D space.
Example image:

A: No, you do need an additional vector. It can be global, one single vector that is used for all points.
Let's say you have point $\vec{p}_i$ on the surface, $\vec{n}_i$ is the normal vector at that point, and $\vec{a}$ is your global direction vector.
For each point $\vec{p}_i$ on the surface, you want to find the two tangent vectors $\vec{u}_i$ and $\vec{v}_i$. We can do this by picking $\vec{u}_i$ as perpendicular to normal $\vec{n}_i$ and $\vec{a}$, and $\vec{v}_i$ as perpendicular to normal $\vec{n}_i$ and $\vec{u}_i$:
$$\begin{aligned}
\vec{u}_i &= \vec{n}_i \times \vec{a} \\
\vec{v}_i &= \vec{n}_i \times \vec{u}_i \\
\end{aligned}$$
Unfortunately, this breaks down in the case where the normal $\vec{n}_i$ is parallel to $\vec{a}$ ($\vec{n}_i \parallel \vec{a}$): then, $\vec{u}_i = \vec{u}_i = 0$. This is trivial to solve, however, since you can simply choose $\vec{u}_i$ and $\vec{v}_i$ to be any vector pair perpendicular to each other and $\vec{a}$.)
If we consider a sphere, and pick $\vec{a}$ from pole to pole, then $\vec{u}_i$ are along latitudes, and $\vec{v}_i$ longitudes.

Note that if the surface is a polygon mesh (say, a triangle mesh), this will not find the edges of the surface. To do that, you find the discontinuities in the normal vector: at an edge or vertex, the normal vector changes discontinuously.


text:
Q: Suggestions for graph ui library for showing analytical graph I want to make analytical graphs of tweets, something like the following website link
Website-Link
I wanted to know what are the best option available in open source ?
I have heard Raphael.js is good. Other suggestions ?

A: The site you listed uses http://www.flotcharts.org. I've used it before with success.
Edit 5/25
Flot has some excellent documentation included, as well as many many examples (examples can be found here http://www.flotcharts.org/flot/examples/). For the sake of simplicity, however, I have taken their simplest example and removed some of the un-needed code (example from http://www.flotcharts.org/flot/examples/basic-usage/index.html).
Code Example

    <title>Flot Example</title>

Now, you are going to want to get your data from PHP, .NET (or any other server side language - or- connect to an API with ajax) (which will probably be pulling it from Twitter or from another aggregate data source). But that would have to be another question!


text:
Q: Reading a CSV or Pipe delimited file I am trying to read a csv file that is using a  | delimiter instead of ,.
I am using
<cffunction name="loadCSVfile" access="public" returntype="string">
    <cfargument name="filename" required="yes" default="">

    <cffile action="read" file="#filename#" variable="csvData">

    <cfreturn csvData>
</cffunction>

which works fine with files that are , delimiter but does not work with |. Is there anything else that I need to do for this function to work?
This is how I'm calling the function:
    <cfscript>
       csvloaderCFC = CreateObject("component","AlscCSVloader");
    </cfscript>

    <cfset csvfilename = DataDirectory&q_DataDirectory.name>

    <!---  backup CSV file ---->
    <cffile action= "copy" source = "#csvfilename#"
                destination = "#DataDirectorybackup#">

    <!---  Load CSV data ---->
    <cfscript>
        csvData = csvloaderCFC.loadCSVfile(csvfilename);
    </cfscript>

    <cfdump var="#csvData#">

The cfdump in the end it doesn't show at all
Pipe-delimitted sample
Location|patient_ID|First Name|Last Name|
111|468454|Eric |Gallegos |
111|468457|kelsey|anderson|
10|468459|Rivenda|Kaur|

Comma-delimitted sample
Location,patient_ID,First Name,Last Name,
111,468454,Eric ,Gallegos ,
111,468457,kelsey,anderson,
10,468459,Rivenda,Kaur,

A: There is quite a bit more you have do do than just a CFFile call to get a CSV as a struct of some kind. CFFile foes not do this on it's own. (although strangely CFHttp does) Honestly your best bet may be to be to use a Java library. There are several available from Apache: http://commons.apache.org/csv/
These should give you back something fairly easy to deal with.
If you want a "pure" coldfusion CSV option you can look at this blog post for a specific impl:
http://www.bennadel.com/blog/483-Parsing-CSV-Data-Using-ColdFusion.htm
basically you need to read the entire content and then parse it.


text:
Q: What is the difference between packet and payload I got this defitiniton below is it true and what is the difference between packet and payload?
The ESP (Encapsulation Security Payload) protocol is a member of IPSec suite. Its
    purpose is to guarantee payload's (message) integrity, data origin authentication of IP
    packets and confidentially of the payload.
    It does provide protection for the entire packet, not only to the payload.

A: A payload is the part of the packet with the actual info (the good stuff!) There are other parts of a packet, the packet headers, that describe the payload, like how big it is.
The description is telling you that protection is provided for everything in the packet, including it's headers. Hope that helps!

A: The answer is:
In tunnel mode it secures whole packet in transport mode does not.


text:
Q: Two variables with the same list have different IDs.....why is that? Trying to understand the following
Why is it that the ID's assigned by Python are different for the same lists?
x = [1, 2, 3]
y = [1, 2, 3]

id(x) != id(y)
True

id(x)
11428848

id(y)
12943768

A: The why to that is that if you do that:
l = [1, 2, 3]
m = [1, 2, 3]
l.append(4)

Ids should not be the same and ids must not change for any objects since they identify them.
All mutable objects works this way. But it is also the case for tuples (which are unmutable).
Edit:
As commented below, the ids may refer to memory address in some python implementation but not in all.

A: Every distinct object in Python has its own ID. It's not related to the contents -- it's related to the location where the information that describes the object is stored. Any distinct object stored in a distinct place will have a distinct id. (It's sometimes, but not always, the memory address of the object.)
This is especially important to understand for mutable objects -- that is, objects that can be changed, like lists. If an object can be changed, then you can create two different objects with the same contents. They will have different IDs, and if you change one later, the second will not change.
For immutable objects like integers and strings, this is less important, because the contents can never change. Even if two immutable objects have different IDs, they are essentially identical if they have identical contents.
This set of ideas goes pretty deep. You can think of a variable name as a tag assigned to an ID number, which in turn uniquely identifies an object. Multiple variable names can be used to tag the same object. Observe:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> id(a)
4532949432
>>> id(b)
4533024888

That, you've already discovered. Now let's create a new variable name:
>>> c = b
>>> id(c)
4533024888

No new object has been created. The object tagged with b is now tagged with c as well. What happens when we change a?
>>> a[1] = 1000
>>> a
[1, 1000, 3]
>>> b
[1, 2, 3]

a and b are different, as we know because they have different IDs. So a change to one doesn't affect the other. But b and c are the same object -- remember? So...
>>> b[1] = 2000
>>> b
[1, 2000, 3]
>>> c
[1, 2000, 3]

Now, if I assign a new value to b, it doesn't change anything about the objects themselves -- just the way they're tagged:
>>> b = a
>>> a
[1, 1000, 3]
>>> b
[1, 1000, 3]
>>> c
[1, 2000, 3]

A: Those aren't the same lists. They may contain identical information, but they are not the same. If you made y = x, you'd find that actually the id is the same.

A: Python keep the mutable variables with different IDs, that's why.
You can check it with immutable object ids too; a tuple, for example.


text:
Q: Apache Airflow get execution time difference between two DAG runs I'm currently trying to figure out how to use two dag runs' execution time to get their time difference to prevent from the DAG processing the same file multiple times. Any idea how could I check this?

A: You could use croniter, a library packaged with Airflow to do this:
>>> from airflow import DAG
>>> from datetime import timedelta, datetime
>>> from croniter import croniter
>>>
>>> dag_a = DAG(
...     dag_id="A",
...     schedule_interval="00 10 * * *",
... )
>>>
>>> dag_b = DAG(
...     dag_id="B",
...     schedule_interval="00 14 * * *",
... )
>>>
>>> now = datetime.now()
>>> cron_a = croniter(dag_a.schedule_interval, now)
>>> cron_b = croniter(dag_b.schedule_interval, now)
>>> time_difference = cron_b.get_prev(datetime) - cron_a.get_prev(datetime)
>>> time_difference
datetime.timedelta(0, 14400)
>>> time_difference.seconds
14400 # 4 hours


text:
Q: How do I drag and drop something into a Static control? How would I drag and drop something into a static control?  It looks like I need to create a sub class of COleDropTarget and include that as a member variable in a custom CStatic.  That doesn't appear to be working though.  When I try and drag something onto the Static control I get the drop denied cursor.

A: The static control's m_hWnd must be valid when you call COleDropTarget::Register, which is why it doesn't work from within your CMyStatic constructor. What you can do is override CWnd::PreSubclassWindow within your CMyStatic class:
class CMyStatic : public CStatic {
    ...
    virtual void PreSubclassWindow();
};

void CMyStatic::PreSubclassWindow()
{
    CStatic::PreSubclassWindow();

    m_MyDropTarget.Register(this);
}

There's a really good article here on CodeProject that you may find helpful.

A: In addition to the PreSubClassWindow() addition, you also have to set your CStatic control to have the Notify flag set in its resource parameters.  Otherwise the control won't let the app know about mouse movements and hence not trigger the OnDragEnter() method.


text:
Q: How to Generate a dataset based on mean, median, 1st & 9th decile values? I have the following values that describe a dataset:
Number of Samples: 5388
Mean: 4173
Median: 4072
1st Decile: 2720
9th Decile: 5676

I need to generate any datasets that will fit these values.
All the examples I found require you to have the standard deviation which I don't.
How this can be done?
Thanks!

A: Interesting question!
Based on Scott's suggestions I gave it a quick try.
Inputs:
import random
import pandas as pd
import numpy as np

# fixing the random seed
random.seed(a=1, version=2)
# formating floats
pd.options.display.float_format = '{:.1f}'.format

# given inputs
count = 5388
mean = 4173
median = 4072

lower_percentile = 10
lower_percentile_value = 2720

upper_percentile = 90
upper_percentile_value = 5676

max_value = 6325
min_value = 2101

The Function:
def generate_dataset(count, mean, median, lower_percentile, upper_percentile,
    lower_percentile_value, upper_percentile_value,
    min_value, max_value
    ):

    # Calculate the number of values that fall within each percentile
    p_1_size = int(float(lower_percentile) * float(count) / 100)
    p_4_size = int(count - (float(upper_percentile) * float(count) / 100))
    p_2_size = int((count / 2) - p_1_size)
    p_3_size = int((count / 2) - p_4_size)

    # can be used to adjust the mean
    mean_adjuster = 5790

    # randomly pick values of right size from a range
    p_1 = random.choices(range(min_value, lower_percentile_value), k=p_1_size)
    p_2 = random.choices(range(lower_percentile_value, median), k=p_2_size)
    p_3 = random.choices(range(median, mean_adjuster), k=p_3_size)
    p_4 = random.choices(range(upper_percentile_value, max_value), k=p_4_size)

    return p_1 + p_2 + p_3 + p_4

dataset = generate_dataset(
    count, mean, median, lower_percentile, upper_percentile,
    lower_percentile_value, upper_percentile_value, min_value, max_value
    )

Comparaison:
# converting into DataFrame
df = pd.DataFrame({"x": dataset})

new_count = len(df)
new_mean = np.mean(df.x)
new_median = np.quantile(df.x, 0.5)
new_lower_percentile = np.quantile(df.x, lower_percentile/100)
new_upper_percentile = np.quantile(df.x, upper_percentile/100)

compare = pd.DataFrame(
    {
        "value": ["count", "mean", "median", "low_p", "high_p"],
        "original": [count, mean, median, lower_percentile_value, upper_percentile_value],
        "new":[new_count, new_mean, new_median, new_lower_percentile, new_upper_percentile]
    }
)

print(compare)

Output:
   value  original    new
0   count      5388 5388.0
1    mean      4173 4173.4
2  median      4072 4072.5
3   low_p      2720 2720.4
4  high_p      5676 5743.0

Getting the values to be exactly equal is a bit tricky when all your values are integers and not floats..
You can add another variable to control the mean with two numbers or change the random seed and see if you can get a closer values. Alternatively, you can write a function that changes the seed until the values are equal. (might take couple of minutes or couple of centuries:)
Cheers!

A: The median fixes the 5388/2 ~ 2694th and 5388/2 + 1 ~ 2695th values (the middle values).  So, let's just make those both 4072.  The 1st and 9th decile fix the 5388/10 ~ 538.8th and 9*5388/10 ~ 4849.2th values.  There are multiple formulae in vogue for deciles, but it would be safe to set the 538th and 539th values both to 2720.  We can similarly obtain the correct 9th decile by fixing the 4849th and 4850th values to 5676.  The mean provides one less degree of freedom, but computing the mean involves the actual values from the entire dataset, so we'll put it off till later.  First, what we need to do is to make 537 values lower than 2719.  (almost) Doesn't matter how, but it might be good to make them quite low (to be explained later).  Then, we need to make 2693-539 (the number of values between our fixed first decile values and the fixed median values) values between 2720 (the first decile) and 4072 (the median).  Then make 4848-2695 values between 4072 and 5676. We now need 5388-4850 (the total number of values minus the 9th decile and lower values) values greater than 5676, but recall that we also need to set the mean.  There are literally an infinite number of ways to do this, but one way is to simply make all of the values above the 9th decile identical.  To do this, we can compute the mean of the lower 4850 values (which we already have), and realize that (5388 - 4850) * X + 4850 * M = 4173, where M is the mean of the lower 4850 values.  Solve for X to obtain the value that you need.  Since X must be greater than 5676, it is helpful if you set the values below the first decile to be small, because this gives us some leeway.  Another way to do this is to pick random numbers above 5676 for all but one of these values, then pick the last value in such a way to fix the mean (again, it would be wise to pick the random values to not be much above 5676, since the last remaining value can be made arbitrarily large to drag the mean up to the correct value).
In any case, in numpy, you'll just be generating a bunch of random numbers.  np.random.randint should get the job done.

A: General comment:
If you have specified a quantile function Q(p), then sampling U according to a uniform distribution and plugging in Q(U) gives a draw from the desired distribution.


text:
Q: Pass information from div to javascript I am a newbie and I am trying my hand at javascript for the first time. I have a div that calls a javascript. I have a timezone controller, a show.html which renders the timezone.
<%= render @user.timezones.paginate(page: params[:page]) %>

My partial file for each timzone, _timezone.html,erb :

<%= timezone.name %>
<%= timezone.city %>
<%= (timezone.positive ? '+ ' : '- ') + timezone.hours.to_s + ':' + timezone.minutes.to_s %>
<div class="time-rect-container" data-positive="<%= timezone.positive %>" data-hours="<%= timezone.hours %>" data-minutes="<%= timezone.minutes%>">

<%= link_to "edit", edit_timezone_path(timezone) %>
<%= link_to "delete", timezone, method: :delete,
                                   data: { confirm: "You sure?" } %>

This partial will be called for every timezone that I have in my database for each user.
And I have the javascript as:
$(document).ready(function () {
setInterval(function () {
 time_div = $('.time-rect-container');
 var dt = new Date();

 var x = time_div.data('hours');
 var y = time_div.data('minutes');
 z = time_div.data('positive')
 utchours = dt.getUTCHours();
 utcminutes = dt.getUTCMinutes();
 utcseconds = dt.getUTCSeconds();
 if (z == true)
    var time = parseInt( utchours + x + (utcminutes + y) / 60) % 24 + ":" + (utcminutes + y) % 60 + ":" + dt.getUTCSeconds();
 time_div.html(time)
}, 1000);
});

I want the javascript to return different time each time, depending on the hours, minutes of timezone. However for every timezone, the data I am getting in the javascript is the same, i.e, the hours and minutes from the data I am retrieving remainse same for each timezone.
Can somebody help fix this?

A: You can use Html Data Attributes for sending info to javascript.
you can generate divs with attribute data-url and pass it timezone-id url. Your divs should look like this.
<div class="time-rect-container" data-url="/timezones/<%= <timezone id> %>/give_time">

Javascript:
$(document).ready(function () {
    setInterval(function () {
     time_div = $('.time-rect-container');
     time_div.load(time_div.data('url'));
}, 1000);


text:
Q: Hovering over a popup nav menu and have a separate popup display based on which element in menu is being hovered over? I'm working on a site that has hovering popup nav menu that works exactly the way I want. What I want in addition to the menu is to have another popup somewhere else on the page that contains specific information about the element that the user is currently hovering over. If no elements in the nav menu are being hovered over, I want the popups to be hidden.
I have a jsFiddle that has everything I want except the additional popup field.
I've tried everything I can think of except a JavaScript solution (as I'm not fluent in JS), however, I don't mind a JS solution. I can fumble my way through JS and make occasional changes - I just can't create it.
This hovering popup menu works (full HTML and CSS in the jsFiddle):

Nav menu here

Sub menu items

More nav menu items

How do I get an additional popup field with specific-to-the-hovering-element relevant information, when hovering over one of the top-level menu items?

A: Here is something you can start with.
You can use JavaScript to hide and unhide the information.
Check this JSFiddle : http://jsfiddle.net/apD26/17/
Sample JS :
    $(document).ready(function(){
        $('.info').hide();
        $('.parent').mouseover(function(){
            $('.info').show();
            $('.info').text($(this).attr('data-desc'));
        });
        $('.parent').mouseout(function(){
            $('.info').hide();
        });
    });

Instead of $(this).text() which i have used to show the text, you may store your description in a data attribute in each menu item and display that.
EDIT
Updated the JSFiddle and answer


text:
Q: How to extract info from TXT using node Student no. - Class no.
123123 - 123123123
Class date: abc 123
Year number: 123124
Class Period:
May 12, 2020 to Aug 31, 2020
Class address:
blah blah blah

How do I extract these info individually and store it in a variable where users can call it from a text file using node and javascript?

A: const fs = require('fs');
const path = require('path');

fs.readFile(path.join(__dirname, './text.txt'), { encoding: 'utf-8' }, (err, data) => {
  if (err) {
    console.log(err);
  }
  // split to lines, remove white space
  const result = data.split(/\n/g).map((line) => {
    return line.split(/\s+/).filter(Boolean);
  });
  console.log(result);

  // result content:
  // [
  //   ['Student', 'no.', '-', 'Class', 'no.'],
  //   ['123123', '-', '123123123'],
  //   ['Class', 'date:', 'abc', '123'],
  //   ['Year', 'number:', '123124'],
  //   [],
  //   ['Class', 'Period', 'period:'],
  // ];
});


text:
Q: How can replace the eval function with other method in the ajax? I have read some material ,it says that eval is evil ,eval can be replaced wit some method.
The code snippet below can call sinajs stock price api,when you type some company's ticker in input ,its price will show in console.log's window,for example to input 600020.

function stock(){
    ticker = $("#code").val();
    $.ajax({
        type : "GET",
        url : "http://hq.sinajs.cn/list=sh" + ticker,
        dataType : "script",
        cache : "false",
        timeout : 2000,
        success : function(data) {
            sname = eval("hq_str_sh" + ticker);
            console.log(sname);},
        error : function() {alert("wrong");}
    });
}

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    tiker:
    <input id="code" type="text" size="10">
    <input id="Search" type="button" onclick="stock()" value="query">

How to replace the eval function with some method for the below code snippet?
success : function(data) {
    sname = eval("hq_str_sh" + ticker);
    console.log(sname);},

It's my try:
success : function(data) {
    window["myTicker"] = "hq_str_sh" + ticker;
    console.log(myTicker);},

Failed.

A: You can parse the response.
data.substring(4, c.length - 1).split("=")[1];

That will be the response past the var part without the trailing ;, split it on the = sign and the data is the second element of the array.

A: console.log(window["hq_str_sh" + ticker])


text:
Q: how to retrieve data into text area based on selected option using foreach loop? I am having trouble retrieving data from database into text area based on dropdown list option that is selected, I've tried foreach but it didn't help.  All items will pop not only the one I want.
here is my php code:
vispage.php
<?php
session_start();
$title = "hadeeth";
include_once ("header.php");
include 'connect.php';

//STEP 1: CREATE THE QUERY

$query = "SELECT * FROM `search`";

//STEP 2: RUN THE QUERY
$result = mysqli_query($con,$query);
$hadeeth = array();

//STEP 3: RETRIEVE VALUES FROM RESULT
while($row = mysqli_fetch_assoc($result))
{

$hadeeth[$row['name']] = array(
 'name'=>$row['name'],
 'short'=>$row['short']
 );

}
?>

html code:

<form name="det" action="vispage.php" method="POST">

Select Title of the Hadeath
<select name="header">

                <?php foreach($hadeeth as $i) {?>
<option value="1"><?php echo $i['name']; ?></option>
    <?php } ?>
</select>

det

tree :

<textarea name="tree" rows="15" cols="30"></textarea>

</form>

<?php include 'footer.php' ?>

A: You need to do few steps:

*

*HTML Form : add event of onchange in drop down box

*Get selected value on event and send to PHP file via jQuery request

*PHP file : receive variable and get related data from database using Query

*send back in json encoded

*In jQuery, receive that output and decode in json and show in textarea

You need to use jQuery for onchange event
$('select[name=header]').change(function(){
    var value = $(this).val();
    $.ajax({
        type : 'POST',
        url  : 'file-name.php',
        data : {selectedValue:value},
        dataType : 'json',
        success:function(response){
            $('textarea[name=tree]').html(tree);
        }
    });
});

Now you need to update your PHP file according.


text:
Q: SQL WHERE condition depending on form input I have a form where the user can enter multiple months and my SQL query returns the data for those months.
For example, if the user enters January the SQL should be:
SELECT * FROM table WHERE month = 'January'

If the user enters March, August, October the SQL should be:
SELECT * FROM table WHERE (month = 'March' OR month = 'August' OR month = 'October')

How would I go about making the WHERE conditions dynamic like that because the user can enter however many months we wants? Its like an ad-hoc query. Thanks!

A: Create a comma-separated string from the array of months that are submitted and store it into variable $months. For example:
$form_months = array('September','November','December');
$months = join(',', $form_months);

Resulting in...
'September','November','December'
You can then use:
$sql = "SELECT * FROM table WHERE month IN (" . $months . ")";

Oh yeah.. and somebody said "beware SQL injections, blah, blah" - but that's you're call, not for me to wrap you in a user-safe cocoon for you to feel warm and cozy.

A: I would recommend using placeholders. Still.
What? Whoa, heck yeah! Still no worry about SQL injection (yay!) and the problem can be approached in nice little pieces - building the dynamic SQL and then binding the relevant value(s).
Imagine that we start with an array of data:
$stuff = array("January", "February");

Then we just need to create the appropriate template with placeholders dynamically, say:
.. WHERE (month = ? OR month = ?)
.. WHERE month IN (?, ?)           -- or

(The only thing we needed here was to know how many elements were in the array. These can be generated using a simple loop without actually caring about the values in the array! Should be simple to work out :-)
And then bind the values from the array as shown in the (mysqli_stmt_bind) examples (e.g. use call_user_func_array). Also see Can I bind an array to an IN() condition? which provides a specific walk-through for this use case (note the named parameters).

A: For PL/SQL, you can try the IN clause.
SELECT * FROM table WHERE month IN (/*list of months from user input*/);

I hope you're protecting against SQL Injection!

A: You may need pass the months as an array through $_POST or $_GET
For example consider that this is the part of the month in your html Form and you will submit it via POST
<input type="checkbox" name="month[]" value="January">January

<input type="checkbox" name="month[]" value="February">February

[...]

In your php processor you have this
$moth = isset($_POST['month']) ? $_POST['month'] : NULL;//get the array

if(!empty($month)){
 foreach ($month as $month_val) {
    $months_val[] = "'" . mysqli_real_escape_string($dbcon,$month_val). "'";
    //using mysqli
  //$dbcon is the conection parameter
 }
  $months_val_insert = implode(',', $months_val);

  $month_values = $months_val_insert;

$query = "SELECT * FROM table WHERE month IN ($month_values )";
 }

This is the idea
Thanks to @user2246674 who point me out with this reference


text:
Q: Xcode не компилирует проект: clang failed with exit code 255
clang: error: unable to execute command: posix_spawn failed: Argument list too long
clang: error: clang frontend command failed due to signal (use -v to see invocation)
Apple clang version 4.1 (tags/Apple/clang-421.11.66) (based on LLVM 3.1svn)
Target: i386-apple-darwin11.4.2
Thread model: posix

A: с 99% вероятностью проблема в #import, где то ушло в рекурсию.


text:
Q: Find IP to Country Code in php code hi i want get country code data from ip address
this site give free services like this link for example
http://freegeoip.net/json/23.94.30.210
this link show all data but i need only "country_code":"US" from it.
Please tell me how to implement this link in php get only "country_code":"US" from this.

A: Use function file_get_contents.
$jsonData = file_get_contents("http://freegeoip.net/json/23.94.30.210");
$countryInfo = json_decode($jsonData,true);

DEMO.

A: First, see related question Getting visitors country from their IP. You can use Geo IP Location.

A: It looks like the data has been JSON encoded. You will need to use the JSON functions available in PHP to decode this, and retrieve the country code (assuming you've already managed to retrieve the information using cURL).
Here is a sample bit of code:
// $data contains the information shown at http://freegeoip.net/json/23.94.30.210.
$decoded = json_decode($data);
$country_code = $decoded['country_code'];


text:
Q: Servlet filters not invoked for _am/api/discovery/* URLs? I'm updating a GAE application to the Java8 Cloud SDK environment; I'm also updating it to use Cloud Endpoints version 2.
My app registers some servlet filters in its web.xml file, one for Objectify and one to do some initialisations such as creating singleton instances of some utility classes the app uses.
This is an excerpt of web.xml:
  <servlet>
    <servlet-name>EndpointsServlet</servlet-name>
    <servlet-class>com.google.api.server.spi.EndpointsServlet</servlet-class>
    <init-param>
      <param-name>services</param-name>
      <param-value>com.myapp.service.Service</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>EndpointsServlet</servlet-name>
    <url-pattern>/_ah/api/*</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>InitializerFilter</filter-name>
    <filter-class>com.myapp.InitializerFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>InitializerFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <filter>
    <filter-name>ObjectifyFilter</filter-name>
    <filter-class>com.googlecode.objectify.ObjectifyFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>ObjectifyFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

<!-- Add a filter that fetches the service config from service management. -->
<filter>
    <filter-name>endpoints-api-configuration</filter-name>
    <filter-class>com.google.api.control.ServiceManagementConfigFilter</filter-class>
</filter>

<!-- Add a filter that performs Endpoints logging and monitoring. -->
<filter>
    <filter-name>endpoints-api-controller</filter-name>
    <filter-class>com.google.api.control.extensions.appengine.GoogleAppEngineControlFilter</filter-class>
    <init-param>
        <param-name>endpoints.projectId</param-name>
        <param-value>${appId}</param-value>
    </init-param>
    <init-param>
        <param-name>endpoints.serviceName</param-name>
        <param-value>${service}-dot-${appId}.appspot.com</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>endpoints-api-configuration</filter-name>
    <servlet-name>EndpointsServlet</servlet-name>
</filter-mapping>

<filter-mapping>
    <filter-name>endpoints-api-controller</filter-name>
    <servlet-name>EndpointsServlet</servlet-name>
</filter-mapping>

It looks like filters correctly kick for all URLs (for example, URLs handled by some other servlet that I instantiate but are not shown here), but not the _ah/api/discovery/* URLs that implement Google's nifty APIs Explorer tool.
No exceptions are thrown at deployment.
Note that I already tried changing the <url-pattern>/*</url-pattern> to <url-pattern>/_ah/api/*</url-pattern>, to <url-pattern>/_ah/api/discovery/*</url-pattern> and mapping using <servlet-name>EndpointsServlet</servlet-name> rather than a URL pattern, to no avail.
Awkwardly enough, the very same configuration did work on Friday morning, then after a redeployment made later in the afternoon it stopped. And I'm pretty positive I did not change anything.
Is this known behaviour? For example, this may be because the API Explorer is "stitched on" the endpoints URL externally rather than being part of EndpointServlet itself?
Otherwise, what am I doing wrong?
=========
I fixed this problem by moving the logic that was in the filter to a ServletContextListener, and this made the app stable. This is only viable for once-for-servlet-lifetime initialisations, of course, so the question still stands: is the cloud API Explorer expected to trigger the servlet filters registered on EndpointsServlet?


text:
Q: How to get buttons to size full width, responsively I'm having an issue trying to get the green buttons underneath the header to lay properly across devices. Full desktop is fine, but as the screen gets smaller, the buttons will break between words and go the next line. And on mobile, I'd like them to stack, but they overlap, and I'm trying to add a bottom/top margin, but nothing helps.
http://www.cooldownjuice.com/collections/menu
How can I get this to lay properly?
Here's my code. (added max/min width as suggested on another topic here)
.catbtn {
    padding: 10px;
    margin-right: 4px;
    margin-left: 7px;
    background-color: #319E15;
    color: #fff!important;
    text-decoration: none!important;
    font-family: Lato;
    font-size: 100%;
    text-transform: uppercase;
    border-radius: 5px;
    border: 2px solid #319E15;
    width: 100%;
    min-width: 50px;
    max-width: 300px;
}

A: You'll need to use float, like so
.catbn {
    display: block;
    float: left;
    margin-top: 10px;
}

Also I personally believe the behavior is better when you remove width: 100% but that's a matter of personal preference.

A: Use
display: -webkit-inline-box;
display: inline-block;
margin: 10px,

And voilà! And you can maintain your center buttons. If you wish, you can float:left/right to align

A: To avoid breaking of words and overlapping buttons, add following rules in your css
.catbn{
    white-space:nowrap;
    display:inline-block;
    /*Rest of the css*/
 }

A: The best way to do that is to set the a to block. You may use float or display:inline-block
Here is your modified code for button.
.catbtn {
padding: 10px;
margin-right: 4px;
margin-left: 7px;
background-color: #319E15;
color: #fff!important;
text-decoration: none!important;
font-family: Lato;
font-size: 100%;
text-transform: uppercase;
border-radius: 5px;
border: 2px solid #319E15;
width: 100%;
min-width: 50px;
display: inline-block;/* a as block and inline*/
max-width: 174px; /* Set the width*/
}

Hope this help you.!


text:
Q: iFrame functionality with Ajax/jQuery I need to include a small form from a reservation PHP module that I downloaded to my website. Its documentation says that it has to be included with iFrame. However the place is restricted, so the iFrame overflows when the date picker is opened and scrolling bars are shown.
To solve this, I tried using jQuery so that the div would be overflowed.
<div id="siteloader">
            <script>
                    $(function(){
                    $('#siteloader').load('<?php echo base_url('booking/form_homepage.php')?>');
                    });
                </script>
</div>

However, it results that it loads only the HTML. This is not necessary for me, since the page I want to load comes from a complete module, so I need it to be loaded complete, basically what the iFrame would do.
Is there any way to achieve this with Ajax/jQuery?
Thanks in advance


text:
Q: Use of System date and user-input date in Windows VS Mac I have been using this piece of code on my PC running windows and Excel 2013 to return a date.
As shown in the code, the systems prompts for the use of current system date VS use of user-input date.
Function GetRegDate() As Date
Dim RegToday As String

RegToday = MsgBox("Are the transaction(s) of today (System time)?",vbYesNo)

If RegToday = vbYes Then
        ' Use Current System Date
        GetRegDate = Date
    Else
        ' Use user-input date
        Dim RegYear, RegMonth, RegDay As Long
            RegYear = InputBox("Please enter the year of the transaction.")
            RegMonth = InputBox("Please enter the month of the transaction (in number).")
            RegDay = InputBox("Please enter the day of the transaction.")
            GetRegDate = RegDay & "/" & RegMonth & "/" & RegYear
End If

' Some other codes
End Function

The piece of code has been consistently successful on my PC. But it isn't the case when my friend uses it on his Mac running Excel 2011.
Taking 26 Mar 2016 As an example, on my PC, by using the current system date or the user-input date method, the value "#26/3/2016#" is stored in the variable 'GetRegDate', as reflected from the local variable windows.
But as my friend told me, when using current system date, the value "##" is stored. When using the user-input date method, an error occurs at the line
GetRegDate = RegDay & "/" & RegMonth & "/" & RegYear

with the runtime error 13 type mismatch
I have no idea why this happened. Any help is appreciated!

A: This is a known bug.  From Microsoft Communities:

This is known bug with some of the region settings, working OK when
  you use the Dutch region but not for example when you use the French
  settings
Got one user that fix it by running this in the Terminal window
defaults write NSGlobalDomain AppleICUDateFormatStrings -dict 1
  dd/MM/yy
I hope they fix it soon

That said, you shouldn't implicitly cast to a Date with GetRegDate = RegDay & "/" & RegMonth & "/" & RegYear. Use DateSerial to avoid region issues:
GetRegDate = DateSerial(RegYear, RegMonth, RegDay)


text:
Q: how do I debug an error in module.ngfactory.ts I have an app built with Angular 2, the Angular CLI and ngrx, it works fine with ng serve and ng build but ng build --prod fails with:
ERROR in /webapp/src/$$_gendir/app/app.module.ngfactory.ts (229,102): Property 'stateReducer' does not exist on type 'typeof "/webapp/src/app/app.module"'.

My understanding is that app.module.ngfactory.ts is a file that is generated by Angular from my file app.module.ts and I'm a bit mystified about how to go about debugging this, other than doing a binary search to find what commit introduced the failure...
app.module.ts looks like this:
@NgModule({
  declarations: [
    AppComponent,
    AuthComponent
  ],
  imports: [
    StoreModule.provideStore({stateReducer}),
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [MyService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Can anyone provide some tips for debugging this kind of error?


text:
Q: How can I compare range of values in case statement in java? I want to use same case statement when i is less than 5. But it's not working. Giving me an error that incompatible types: boolean cannot be converted to int
class temp{
  public static void main(String args[]){
    int i=1;
    switch(i){
       case i < 5 :
       System.out.println("Works");
    }
  }
}

Please help me solving this.

A: You can't use boolean values for case. The statement i < 5 returns either True or False. You should use if instead.
class temp{
  public static void main(String args){
    int i=1;
    if (i < 5)
       System.out.println("Works");
  }
}

A: case i < 5  It produce boolean result. which is not compatible with integer

If you want to compare multiple conditions then use switch case.
switch(i){

  case 1 :
  case 2 :
  case 3 :
  case 4 : System.out.println("Works");
  break;

}

In you code you are handling only one condition so, use if condition instead of switch.
public static void main(String args){
    int i=1;

    if(i < 5)
    System.out.println("Works");

  }

A: You can't use conditional statements in case,they can have constants only
you can write like this
case 5:

or
case 6:

in particular,hence case <5 is something not acceptable here according to the syntax

A: What you want is not a switch-case block, which is used as a lookup table to specific values. You want an if-then-else block:
if(i<5)
{
  \\do stuff
}
else if(\* Some other condition *\)
{
 \\ do other stuff
}
else
{
 \\ default case
}


text:
Q: Can bootstrap modal dialog overlay another dialog? <button class="btn" onClick="$('#firstModal').modal('show');">First</button>

        <button class="btn" onClick="$('#secondModal').modal('show');">Second</button>

        Some error message goes here.

Everything works fine; the only problem is that first dialog is displayed over the overlay of the second dialog. How can I fix this?
This is how it looks now:

And I want it to look like this:

A: I wrote a blog post about how to solve this stacking problem programatically: http://gurde.com/stacked-bootstrap-modals/
$(document)
  .on('show.bs.modal', '.modal', function(event) {
    $(this).appendTo($('body'));
  })
  .on('shown.bs.modal', '.modal.in', function(event) {
    setModalsAndBackdropsOrder();
  })
  .on('hidden.bs.modal', '.modal', function(event) {
    setModalsAndBackdropsOrder();
  });

function setModalsAndBackdropsOrder() {
  var modalZIndex = 1040;
  $('.modal.in').each(function(index) {
    var $modal = $(this);
    modalZIndex++;
    $modal.css('zIndex', modalZIndex);
    $modal.next('.modal-backdrop.in').addClass('hidden').css('zIndex', modalZIndex - 1);
});
  $('.modal.in:visible:last').focus().next('.modal-backdrop.in').removeClass('hidden');
}

A: I think the modal backdrop (overlay) is shared by all modals in the BODY.
But, you can use the 'show' event from the second modal to change the opacity on the first modal -- giving the effect of the overlay over the first modal:
$('#myModal2').on('show', function() {
    $('#myModal').css('opacity', .5);
});

Demo: http://bootply.com/61322
EDIT:
If you want to disable modal 1 while modal 2 is open, you can unbind modal 1 when modal 2 opens, and then restore modal 1 when modal 1 closes. I updated the Bootply for this.
$('#myModal2').on('show', function() {
    $('#myModal').css('opacity', .5);
    $('#myModal').unbind();
});
$('#myModal2').on('hidden', function() {
    $('#myModal').css('opacity', 1);
    $('#myModal').removeData("modal").modal({});
});

A: You could add an attribute to "secondModal"
style="z-index:100000;"

A: I have found out that I can change z-index of the second "shadow" using this css rule:
.modal-backdrop.fade.in:nth-child(2){
    z-index: 1060 !important;
}

than I just need to set z-index of the second dialog to for example 1070 and that's it, although I am not sure about compatibility with older browsers.

A: Just in case someone stumbles across this.

*

*Add this value to your main script tag on the your page
  var current_zindex = 1049;

  var current_zindex_bg = 1048;

*in your document ready function add
  $('.modal').on('show', function () {
     current_zindex++;//increment z-index for your modals
     current_zindex_bg++;//increment z-index for your modal-backdrops
     $(this).css('z-index',current_zindex); //setting the modal backdrop
 });

*Now in the minifield bootstrap file itself find this bit of code:
  '
' //just search for "modal-backdrop" without the quotes

  change to:

  '
'

That's it. You can find the same bit of code in the unminified boostrap.js by searching for "modal-backdrop" and follow the same process.
Clicking the top most backdrop will hide the top most modal as you would want.

A: To make overlays open other overlays, I added a simple line of JS in the event listener.
Thus any link inside an overlay will first close the overlay it is in.
Search for in the Bootstrap overlay code:
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {

Add to that function:
$this.closest(".modal").modal('hide');

A: Let's say you have modal var modal = $('.some-selector').modal('show');
first you want to change it's zIndex like: modal.css({zIndex: 7760})
you can find reference to its $backdrop in modal.data(), so you can access it and change anything: modal.data()['bs.modal'].$backdrop.css({zIndex: 7750});

A: You can simply do this way: (note : You need bootstrap 3 for this)
<button class="btn" data-target="#firstModal" data-toggle="modal">First</button>

        <button class="btn" onClick="$('#secondModal').modal('show');">Second</button>

        Some error message goes here.

A: Here is the solution that worked for me:
$("#ModalId").appendTo("body");

For the detailed answer. Check this blog post
https://weblog.west-wind.com/posts/2016/sep/14/bootstrap-modal-dialog-showing-under-modal-background


text:
Q: Docker compose install requirements in a shared directory I am having several containers, and each of my containers are having their own Dockerfile. Everytime I am building, using docker-compose build, each container runs its own requirements; either from a requirements.txt file (RUN pip install -r requirements.txt), or directly from the Dockerfile (RUN pip install Django, celery, ...). Many of the requirements are common in some of the containers (almost all).
It is working perfectly, but there is a problem with build time. It takes almost 45 minutes to build every container from scratch. (lets say after I deleted all images and containers)
Is there a way, to install all the requirements in a common directory for all containers, so that we dont install the common requirements each time a new container is building?
Docker-compose I am using is version 2.

A: You can define your own base image. Let's say all your containers need django and boto for instance, you can create your own Dockerfile:
FROM python:3

RUN pip install django boto

# more docker commands

Then you can build this image as arrt_dtu/envbase and publish it somewhere (dockerhub, internal docker environment of your company). Now you can create your specialized images using this one:
FROM arrt_dtu/envbase

RUN pip install ...

That's exactly the same principle we have with the ruby image, for instance. The ruby one uses a linux one. If you want a rails image, you can use the ruby one as well. Docker images are totally reusable!


text:
Q: Server automatic reconnect? I'm trying to setup a Ubuntu hardware firewall (just for fun :D) and I was wondering if Ubuntu's network scripts could automatically reconnect to the wired interface (eth0) when the connection is dropped?
My ISP's modem is pretty bad and requires a reset once in a while. It's annoying to go to basement with a keyboard and blindly login and type /etc/init.d/networking restart.

A: Have a look at cron and crontab. What you need to do is create a script that you can insert into cron that...

*

*checks every x minutes if the connection is down.

*

*if is not down do nothing.

*if it is down reconnect.

Example of such a script:

#!/bin/bash

IP_ADRESS=192.168.1.1
( ! ping -c1 $IP_ADRESS >/dev/null 2>&1 ) && service network restart >/dev/null 2>&1

Put this in a scrip (set the IP adress to what you want to check), make it executable with
chmod +x /usr/local/bin/check_network

and run the script from crontab. You can edit this line into it with the command crontab -e:
*/2 * * * * root /usr/local/bin/check_network

*

**/2 makes it check 30 times an hour.

A: I suggest you to give a look to the following two packages:
ifplugd
Package: ifplugd
Description: configuration daemon for ethernet devices
 ifplugd is a daemon which will automatically configure your ethernet device
 when a cable is plugged in and automatically de-configure it if the cable is
 pulled out. This is useful on laptops with onboard network adapters, since it
 will only configure the interface when a cable is really connected.  Features
 include:
 .
  * syslog support
  * Multiple ethernet interface support
  * Uses Debian's native ifup/ifdown programs
  * Small executable size and memory footprint
  * Option to beep when the cable is unplugged or plugged
  * Option to beep when the interface configuration succeeds or fails
  * Can be configured to ignore short unplugged or plugged periods
  * Configure WLAN devices (on detecting a successful association to an AP)
  * Supports SIOCETHTOOL, SIOCGMIIREG and SIOCDEVPRIVATE for getting link status
  * Compatibility mode for network devices which do not support cable detection

netplug
Package: netplug
Description: network link monitor daemon
 This daemon monitors the link status of network cards and configures
 the network on plug- and un-plug-events.
 .
 It's similar to ifplugd, but uses NETLINK instead of regularly polling
 the link status. This improves power-consumption with laptops, but does
 not work with all network card.

I have used in the past the first of this, and it works well on cable unplug and replug, but I don't know if it work also in your situation that seems a little bit different.


text:
Q: HtmlAgilityPack returning an empty list of child nodes I am trying to scrape some stuff from amazon, and can't get past the login. HtmlAgilityPack is returning an empty list of child nodes. Here's what the HTML of the form looks like (redacted for readability)
<form name="signIn" method="post" novalidate action="https://www.amazon.com/ap/signin/..." class="auth-validate-form auth-real-time-validation a-spacing-none">
    <input type="hidden" name="appActionToken" value="..." />
    <input type="hidden" name="appAction" value="SIGNIN" />
    <input type="hidden" name="openid.pape.max_auth_age" value="ape:MA==">
    <input type="hidden" name="openid.return_to" value="...">
    <input type="hidden" name="prevRID" value="...">

Here's my code
class Program
{
    static void Main(string[] args)
    {
        var amazonHomeUri = new Uri("https://www.amazon.com");
        var amazonHomeDoc = GetHtml(amazonHomeUri);
        var signInNode = amazonHomeDoc.DocumentNode.CssSelect("#nav-link-yourAccount").First();
        var signInUrl = signInNode.Attributes["href"].Value;
        var amazonSignInDoc = GetHtml(new Uri(amazonHomeUri, signInUrl));
        var loginForm = amazonSignInDoc.DocumentNode.CssSelect("form[name='signIn']").First();
        var postUrl = loginForm.Attributes["action"];

        //THIS IS WHERE THE ERROR HAPPENS
        //THERE ARE CERTAINLY INPUTS INSIDE THE FORM
        foreach(var input in loginForm.SelectNodes("input"))
        {
            System.Console.WriteLine(input.Attributes["name"]);
        }
    }
    private static HtmlAgilityPack.HtmlDocument GetHtml(Uri uri)
    {
        string html;
        WebRequest request = WebRequest.Create(uri);
        using (WebResponse response = request.GetResponse())
        {
            Stream dataStream = response.GetResponseStream();
            using (var reader = new StreamReader(dataStream))
            {
                html = reader.ReadToEnd();
            }
        }
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(html);
        return doc;
    }
}


text:
Q: How do I change the dock name in macOS programmatically? This Is Not A Duplicate, As Previous Questions On Stackoverflow Are Extremely Outdated And They Don't Work
I want to change the name of the application in the dock to make it feel more like macos.
I was reading this post and I couldn't get it to work. instead, it just appeared with the name "java"

I would like to do this within the java program itself so that whenever the user double-clicks on the jar file, it should launch with the dock name and icon. I have successfully changed the icon with java.awt.TaskBar and also the menu bar, but I couldn't do it dock name. How do I do this?
Java Details:
$ java --version
openjdk 19.0.1 2022-10-18
OpenJDK Runtime Environment (build 19.0.1+10-21)
OpenJDK 64-Bit Server VM (build 19.0.1+10-21, mixed mode, sharing)
$ javac --version
javac 19.0.1


text:
Q: How to create a full day event in fullcalendar I am really stuck with this.How can i create a full day event in fullcalendar when clicked on a day.
dayClick: function (date, allDay, jsEvent, view) {

  var eventTitle = prompt('Provide Event title');

  if (eventTitle) {
    $('#calendar').fullCalendar('renderEvent', {
      title : eventTitle,
      allDay : true,
      stick : true,
    });
  }
}

A: You haven't actually said what's going wrong with this code, but it seems fairly obvious that you missed out the start and end dates. Otherwise how will the calendar know where you want to place the event? It doesn't take any implication from the fact that you called "renderEvent" from inside the "dayClick" method, that's just a coincidence. "renderEvent" can be called anytime and is independent. It expects you to tell it everything about the event you want to add.
If you'd checked your browser console after you tried to add the event, you'd have noticed an error "Cannot read property 'stripTime' of undefined" which would hopefully have given you a clue about the nature of the error, being related to time. You could also trace it back in the source to see what it was doing and what you had omitted to do.
Anyway, since you want this to be an all-Day event for a single day, you can use the date property supplied by the callback quite easily:
dayClick: function (date, allDay, jsEvent, view) {

  var eventTitle = prompt('Provide Event title');

  if (eventTitle) {
    $('#calendar').fullCalendar('renderEvent', {
      title : eventTitle,
      allDay : true,
      start: date, //specify start date
      stick : true,
    });
  }
}

Note that, as per https://fullcalendar.io/docs/event_data/Event_Object/, only "start" is required. "end" is optional and I haven't used it. If you specify "allDay: true" and only supply a start date, then fullCalendar will assume it's an all-day event for a single day.
For future reference: If you want to allow more flexibility in adding events (e.g. not all-day ones), you should use the "select" callback instead to allow users to specify the exact start and end times for the event by dragging their mouse on the calendar. https://fullcalendar.io/docs/selection/select_callback/


text:
Q: Create X509Certificate from PKCS7 PEM formatted certificate using BouncyCastle in Java I have a PKCS7 certificate chain in PEM format. Basically I'd like to perform following openssl command in Java using BouncyCastle library.
openssl pkcs7 -in client-certificate_pkcs7.pem -out client-certificate_chain.pem

I was following this pdf provided from BouncyCastle (https://www.bouncycastle.org/fips-java/BCFipsIn100.pdf), but couldn't really find anything that works on my need.
I've found that CMSSignedData is used for pkcs7 related operations in BouncyCastle so I tried using it, but I was getting an error and I assume it's because I was using a raw String.
String pkcs7Pem = "-----BEGIN PKCS7-----\nMIIR...WTEA\n-----END PKCS7-----\n";
CMSSignedData data = new CMSSignedData(pkcs7Pem.getBytes());
Store certStore = data.getCertificates();
SignerInformationStore signerInfos = data.getSignerInfos();
Collection<SignerInformation> signers = signerInfos.getSigners();
List<X509Certificate> x509Certificates = new ArrayList<>();
for (SignerInformation signer : signers) {
    Collection<X509CertificateHolder> matches = certStore.getMatches(signer.getSID());
    for (X509CertificateHolder holder : matches) {
        x509Certificates.add(new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder));
    }
}

This is the error I got on new CMSSignedData(pkcs7Pem.getBytes());
org.bouncycastle.cms.CMSException: IOException reading content.

I also have tried using PEMParser, but parser.readObject() below returns null.
String pkcs7Pem = "-----BEGIN PKCS7-----\nMIIR...WTEA\n-----END PKCS7-----\n";
PEMParser parser = new PEMParser(new StringReader(pkcs7Pem));
parser.readObject();

Any help would be appreciated!

A:
openssl pkcs7 -in client-certificate_pkcs7.pem -out client-certificate_chain.pem

That command only copies its input (if it is PKCS7 PEM) to its output without any change. That's not useful, nor do you need BouncyCastle to do the same in Java. I suspect you actually meant
openssl pkcs7 -print_certs -in (pkcs7) -out (chain)
which extracts the individual certificate(s), as a sequence of separate (PEM) objects.

I've found that CMSSignedData is used for pkcs7 related operations in BouncyCastle

Only some -- there are lots of PKCS7/CMS formats and operations that can be done, and lots of different BC classes to do them. But the PKCS7/CMS format used to carry a certificate chain, often labelled p7b or p7c, is the SignedData type and is implemented by the BouncyCastle CMSSignedData class.

I also have tried using PEMParser, but parser.readObject() below returns null.

It shouldn't, if you give it valid PEM input not the mangled version you posted. For me if I give it a valid PEM PKCS7 containing a p7b/c cert chain I get a ContentInfo which can then be decoded as follows (I use file I/O for convenience, but any Java Reader and Writer will work the same):
static void SO70048115PKCS7Certs (String[] args) throws Exception {
    PEMParser p = new PEMParser(new FileReader(args[0]));
    CMSSignedData sd = new CMSSignedData( (ContentInfo)p.readObject() );
    p.close();
    JcaPEMWriter w = new JcaPEMWriter(new FileWriter(args[1]));
    for( X509CertificateHolder ch : sd.getCertificates().getMatches(null) ){
        // optionally put subject,issuer as 'comments' like OpenSSL does
        w.writeObject( new PemObject("CERTIFICATE",ch.getEncoded()) );
    }
    w.close();
}

Note a p7b/c by convention does not contain any signature(s) (in PKCS7/CMS terms, SignerInfo(s)) so the code you posted -- which is designed to find the certificate(s) associated with the signature(s) -- is inappropriate and does not work. You need to simply use the certificate(s) and not expect any SignerInfo(s).


text:
Q: How to set cambria math as math font for pdflatex How can I make pdflatex use cambria for math fonts and uarial for the body font?

A: As Cambria Math is only available as an OpenType font and necessarily depends on its OpenType Math table, it does not work with pdftex and needs luatex or xetex.