text:
Q: Re-arrange a string using every x letter position with PHP I'm trying to figure out how to re-arrange a string using every x position so that an example  input string of "ABCDEFGHI" and the x being 4 would yield DHCIFEGBA. Here's how I got that:
The 1st letter is easy: it's character 4. [A, B, C, D]
The 2nd letter is also easy: it's character 8. [E, F, G, H]
The 3rd letter is mostly easy: it's character 3. This happens because I looped around as I counted, so I used I, A, B, C.
The 4th letter is where things get trickier: It's character 9. Because D and H are already gone, they don't get used in the count, resulting in E, F, G, I.
Letter #5 follows the same pattern, skipping C and D: A, B, E, F
Letter #6 has skips AND a wrap: G, A, B, E.
Letter #7 wraps again: G, A, B, G.
Letter #8 also wraps (technically twice since 'cursor' was behind G before: A, B, A, B
Letter #9 is our remainder: A, A, A, A

It's clearly going to need to loop until output string length matches input string length - it's all of this mess in the middle (Mostly the skips and loops) that I can't for the life of me figure out.
Any help or guidance is appreciated.

A: works perfectly with an unique range but will fail with something like ABCDEAFGHAI
$s = 'ABCDEFGHI';
$_len = strlen($s);
$out = '';
$c = 3;
echo '<pre>';
while ( $_len > 0 ) {
    echo strlen($s) ,  ' :: '.  $s . "\n";
    $term = $s[$c-1];
    list($a,$b) = explode($term, $s);
    $s = $b.$a;
    $x = strlen($s);
    if($x <= $c) {
        for($i=0; $i<($c-$x);$i++)
            $s .= $s;
    }

    $out .= $term;
    $_len--;
}

echo "\n\n\n" , $out;

output:
9 :: ABCDEFGHI
8 :: EFGHIABC
7 :: IABCEFG
6 :: EFGIAB
5 :: ABEFG
4 :: GABE
6 :: GABGAB
4 :: ABAB
4 :: AAAA

DHCIFEGBA

a hopefully better solution
function rearrangeString($string, $step = 4) {
    $output = '';
    $lenght = strlen($string);

    if($step >= $lenght) {
        return strrev($string);
    } elseif($step < 1) {
        return $string;
    } else {
        for($i=0; $i < $lenght; $i++) {
            $_tempLen = strlen($string);

            $output .= $string[$step-1];

            list($a,$b) = explode($string[$step-1], $string);

            $string = $b . $a;

            $_tempLen = strlen($string);
            if($step > $_tempLen) {
                $string = str_repeat($string, $step-$_tempLen+1);
            }
            unset($_tempLen, $a, $b);
        }

        return $output;
    }
}

$rearranged = rearrangeString('ABCDEFGHI');
var_dump($rearranged == 'DHCIFEGBA');

$rearranged = rearrangeString('ABCDEFGHI', 9);
var_dump($rearranged == 'IHGFEDCBA');

$rearranged = rearrangeString('ABCDEFGHI', 1);
var_dump($rearranged == 'ABCDEFGHI');

$rearranged = rearrangeString('ABCDEFGHI', 3);
var_dump($rearranged == 'CFIDHEBGA');

$rearranged = rearrangeString('ABCDEFGHI', 6);
var_dump($rearranged == 'FCAIBEHD');

$rearranged = rearrangeString('FARBE', 2);
var_dump($rearranged == 'ABFER');

A: I would try like this, though I haven't tested the code, yet:
$s = 'ABCDEFGHI';
$out = '';

While strlen($s) > 0 {
    $pos = 4 % strlen($s);
    $out += $s[$pos];
    if (strlen($s) > 3) $end = 3;
    else $end = strlen($s) - 1;
    $s = substr($s, 4, strlen($s)) + substr($s, 0, $end);
}

echo $out;

A: Should work with any $s and $n
  <?php
    $s = "ABCDEFGHI";
    $n = 4;

    for ($i=0,$l=strlen($s) ; $l ; $l--)
    {
       $i = ($i+$n-1) % $l;
       echo $s[$i];
       $s = ($i ? substr($s, 0, $i) : '') . ($i < $l-1 ? substr($s, $i+1) : '');
    }
    echo "\n";
  ?>


text:
Q: Social framework not found I reopen my project that using Social.framework, but the link binary of Social.framework was red. Before that, I was update my ios 7.0 doc set. Is Social.framework was deleted in ios 7.0 doc set ? Thanks

A: Kindly select social framework from explorer & just press delete. Now click your Xcode project file & click target. In the build phase tab, kindly re add the framework by pressing + button in Link Binary With Library section.
Please note, updating doc set will not remove your framework.
If you have accidentally removed your social.framework from library itself then kindly download it from my uploads here & extract file & put the folder Social.framework back in place.
Hope that helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find an element with maximum occurrence in an Array - Javascript Input :
['A', 'B', 'C', 'A', 'D', 'B', 'B', 'A', 'D']
Expected output :
'B'
The output should be the element with higher occurrence. If there are two or more elements which shares the same number of occurrence, then the element which reaches the maximum count earlier in the array should be the expected output. In the above case, 'B' and 'A' has count of 3. Since 'B' reaches the max count earlier than 'A', 'B' should be the output.
I have already found the solution for this.
My Solution

let input = ['A', 'B', 'C', 'A', 'D', 'B', 'B', 'A', 'D']

const findWinner = (arr) => {

  const reduced = arr.reduce((acc, value) => ({ ...acc,
    [value]: (acc[value] || 0) + 1
  }), {})
  let pickLargest = Object.entries(reduced)
  const winner = pickLargest.reduce((acc, [key, value]) => {
    if (value > acc.maxValue) {
      acc.maxValue = value
      acc.winner = key
    } else if (value == acc.maxValue) {
      if (arr.lastIndexOf(key) > arr.lastIndexOf(acc.winner)) {
        acc.winner = acc.winner
      } else {
        acc.winner = key
      }
    }
    return acc
  }, {
    maxValue: 0,
    winner: ''
  })

  return winner.winner
}

console.log(findWinner(input));

Is there any other elegant way to achieve the same result?

A: You could take an object for keeping track of the counts and adjust max, if necessary.

const
    findWinner = array => {
        const counts = {};
        let max;

        for (const value of array) {
            counts[value] = (counts[value] || 0) + 1;
            if (counts[value] <= counts[max]) continue;
            max = value;
        }

        return max;
    };

console.log(findWinner(['A', 'B', 'C', 'A', 'D', 'B', 'B', 'A', 'D']));

A: This should work:
const findWinner = ary => {
  const occurrences = Object.fromEntries(ary.map(e => [e, 0]));
  for(let el of ary){
    occurrences[el]++
  }
  let sorted = Object.entries(occurrences).sort((a, b) => a[1] > b[1]);

  return sorted[0][0];
}


text:
Q: How to adjust the branch length of dendrogram converted from Newick file? Hi I aim to make a heat map of species abundance and also show phylogeny tree in parallel. The phylogeny tree was made in MEGA and input to R as Newick file prior to converting to dendrogram object.
However, the branch length of phylogeny tree in the output figure was not the same length. Can I ask is there any way to make the branch length similar?
I attached the code and the output below. Thank you in advance.
library(DECIPHER)
library(dendextend)
library(ape)

#Input the tree from newick file from Mega and convert into dendrogram
dend <- ReadDendrogram("VPstrainand3-major_ASV_5%_withlength.nwk")

#Make the plot using data from the excel stored in the directory
#load the data
library(openxlsx)
library(dplyr)
heatmap.dataframe <- read.xlsx("Complete.xlsx","Modified", rowNames =TRUE)
heatmap.mat <- as.matrix(heatmap.dataframe)
whitered <- colorRampPalette(c("white", "red"), space = "rgb")(100)

#plot
library(repr)
options (repr.plot.width=20, repr.plot.height=20)
heatmap <- heatmap(as.matrix(heatmap.mat), Rowv = dend, Colv = NA, col = whitered)
print(heatmap)

Output heat map with phylogeny tree

A: We can do this with a combination of dendrapply() and a simple function - named ForceUltrametric in this example. This form can be used for a couple different tasks, the example present in dendrapply's help file is for changing leaf colors, but you could use this for adding points below leaves, or adjusting labels as well.
A reproducible example of your entire process in R, since we don't have access to your newick file:
library(DECIPHER)

# using one of DECIPHER's built in examples:
db <- system.file("extdata",
                  "Bacteria_175seqs.sqlite",
                  package="DECIPHER")
dna <- SearchDB(db,
                remove="all")
alignedDNA <- AlignSeqs(dna)

Dist <- DistanceMatrix(myXStringSet = alignedDNA,
                       includeTerminalGaps = TRUE, # global identity
                       verbose = TRUE)
tree1 <- IdClusters(myDistMatrix = Dist,
                    method = "NJ", # a non-ultrametric tree
                    verbose = TRUE,
                    showPlot = FALSE, # you can return a plot as the function completes, or not
                    type = "dendrogram") # return a dendrogram

ForceUltrametric <- function(n) {
  if (is.leaf(n)) {
    # if object is a leaf, adjust height attribute
    attr(n, "height") <- 0L
  }
  return(n)
}

tree2 <- dendrapply(X = tree1,
                    FUN = function(x) ForceUltrametric(x))

Using some newick file, which we don't have access to, and cannot guarantee working:
library(DECIPHER)

tree1 <- ReadDendrogram("<yourfilehere>")

ForceUltrametric <- function(n) {
  if (is.leaf(n)) {
    # if object is a leaf, adjust height attribute
    attr(n, "height") <- 0L
  }
  return(n)
}

tree2 <- dendrapply(X = tree1,
                    FUN = function(x) ForceUltrametric(x))

It should be noted that while it's pleasant to force dendrograms to be ultrametric in cases where you want to plot data below the leaves, it isn't really an accurate representation of the data if the tree was built with a non-ultrametric method.
tree1
tree2


text:
Q: HttpClient Polly Timeout Policy The get request is waiting longer than the timeoutPolicy to timeout.

*

*Does anyone have any idea why this is happening?

*Why does the request not timeout at 30ms?

var timeoutPolicy = Policy.TimeoutAsync(TimeSpan.FromMilliseconds(30), TimeoutStrategy.Optimistic);
var watch = new Stopwatch();
try
{
    watch.Start();
    var httpResponse = await timeoutPolicy.ExecuteAsync(
        async ct => await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, "https://google.com"), ct),
        CancellationToken.None
    );
    watch.Stop();
    Console.WriteLine("request took " + watch.ElapsedMilliseconds);
}
catch (Exception e)
{
    watch.Stop();
    Console.WriteLine("timeout took " + watch.ElapsedMilliseconds);
    Console.WriteLine(e.Message);
}

A: I think I've played around with it enough that I know what's going on, So I feel confident that I can now answer the question.
When you invoke the async task with TimeoutStrategy.Optimistic Polly strategy, you are passing in a CancellationToken and essentially trusting that the CancellationToken will be invoked to end the task in a timeout scenario.
Unlike the behavior with the TimeoutStrategy.Pesimistic strategy which is designed to be able to terminate a syncronous task which does not callback via the CancellationToken.
While your main execution thread is not blocked by an asyncronous task running on another thread, it's important to remember that the task is indeed able to block it's own thread.
For example, If an async task were to call Thread.Sleep(1000) then it's thread would be blocked for a second. Which in turn means that the CancellationToken cannot be invoked for the duration of the block.
In this scenario I believe that long running operations such as looking up the DNS record for a hostname the first time, or any other blocking operation is occurring which is essentially blocking the thread for 90ms.
As such, even though the task knows that it needs to be aborted at the 30ms mark, it need to wait for the thread to be available before it can actually invoke the cancellation, which doesn't occur until about 90ms or thereabouts.
This delay in returning a timeout only seems to occur the first time for each domain resolution, so I presume this is related to nameserver caching and DNS resolution as subsequent calls seem to honor the timeout more efficiently. Although asserting any direct root cause is largely speculation.


text:
Q: Does Rails.cache.fetch perform better with memoization I've searched and cannot seem to find a good source for whether it could be considered a good practice to combine methods for the following: When using memcached with the dalai gem and have a method that is called more than once for a request is there a performance advantage to using the second block over the first in a model? Is it considered good practice to use 'memoization' like this in conjunction with Rails.cache.fetch?
def total_ham
  Rails.cache.fetch("#{self.cache_key}/total_ham") do
    self.hams.sum(:metric_tons)
  end
end

or
def total_ham
  @total_ham ||= Rails.cache.fetch("#{self.cache_key}/total_ham") do
    self.hams.sum(:metric_tons)
  end
end

A: If the total_ham method is called more than once per request, then you should memoize the result of the total_ham method even if you are fetching it out of the cache. The memoization will be faster than hitting the cache - due to the round-trip latency between your app server and the memcached server.
I can't say whether or not this is a best practice or not, but it's what I would do in your situation.


text:
Q: WordPress database set up with rest api I want use WordPress to develop a e-commerce website. I know basics about Wordpress like how to create blog or website. But I don't know how to create database and relationship between tables, rest api etc. How can I set up my database and performing CRUD using rest api?

A: If you want to make an  ecommerce site, its better not re-invent the wheel, install woocommerce. If you are tryng to use wordpress as a development framework, try https://typerocket.com/ - This requiere not only knowledge of wordpeess, but php and laravel too. Wordpress , out of the box, together with JWT PLugin will give you a way to use it as a RBAC - Typerocket will give you the MVC structure. https://lumberjack.rareloop.com/ is another one. Good luck

A: Consult the Wordpress REST API: https://developer.wordpress.org/rest-api/
Then for features the API doesn't offer you will either have to learn to program and make your own API or hire a developer to do it.


text:
Q: Insert CSS to ASP.NET MVC Layout Page on Build in Visual Studio I have a ASP.NET MVC project in Visual Studio 2013.
I would like to automatically insert the content of a minified CSS stylesheet (minified using Web Essentials VS extension) into a style tag on an MVC layout page when building the project.
EDIT - This is for reducing render blocking effects above the fold for first time load (see Optimize CSS Delivery)
How can I do this?

A: In case anyone is still looking for an answer.
I created a HTML helper like below:
public static class CriticalCssHelper
{
    public static MvcHtmlString CriticalCss(this HtmlHelper html, params string[] paths)
    {
        var style = new TagBuilder("style");

        foreach (var path in paths)
        {
            var filePath = HttpContext.Current.Server.MapPath(path);
            style.InnerHtml = File.ReadAllText(filePath);
        }

        return new MvcHtmlString(style.ToString());
    }
}

And in your *.cshtml file you can just use like this:
@Html.CriticalCss("~/Content/css/CriticalCss/layout.min.css")

PS. This might also help for pagespeed optimisation: Minify HTML output from an ASP.Net MVC Application (a little off topic, however are related as it minifies inline css as well)

A: You could try to use the Minification feature of ASP.NET 4.5
In App_Start folder, add BundleConfig.cs class to specify the location of CSS files:
public class BundleConfig
{
  public static void RegisterBundles(BundleCollection bundles)
  {
     //For Css
     bundles.Add(new StyleBundle("~/Content/BundlesCSS").Include(
                        "~/Content/mycss1.css",
                        "~/Content/mycss2.css"));
  }
}

And in the View, add this line of code to render CSS:
<%:Styles.Render("~/Content/BundlesCSS")%>

You can also disable this feature at development time by setting the value of debug attribute in Web.config file:
<system.web>
    <compilation debug="true" />
</system.web>

See more detail: Bundling and Minification

A:     public static String EmbedCss(this HtmlHelper htmlHelper, string path, string tagId = "")
    {
        // take a path that starts with "~" and map it to the filesystem.
        var cssFilePath = HttpContext.Current.Server.MapPath(path);
        // load the contents of that file
        try
        {
            var cssText = System.IO.File.ReadAllText(cssFilePath);
            var minifier = new Minifier();
            cssText = minifier.MinifyStyleSheet(cssText);
            var styleElement = new TagBuilder("style");
            if (!String.IsNullOrEmpty(tagId))
            {
                styleElement.Attributes.Add("id", tagId);
            }

            styleElement.SetInnerText(cssText);
            return styleElement.ToString();
        }
        catch (Exception ex)
        {
            // return nothing if we can't read the file for any reason
            return null;
        }
    }


text:
Q: PHP, MySQL login skips code section it should be executing I have these two php scripts working side by side:
<?php
session_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="users"; // Database name
$tbl_name="clients"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect to file "login_success.php"
$_SESSION["myusername"] = $myusername;
$_SESSION["mypassword"] = $mypassword;

//set POST variables
$url = '127.0.0.1/login_success.php';
$fields = array(
                      'user'=>urlencode($myusername),

                          'password'=>urlencode($mypassword)
               );
$fields_string = '';

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

}
else {
echo "Wrong Username or Password";
}
?>

This above script registers a session for a user, and then post to the next script using cURLs,
<?php
session_start();

if(isset($_SESSION['myusername'])){

$myusername=$_POST['user'];
$mypassword=$_POST['password'];

//set POST variables
$url = '127.0.0.1//$_SESSION[myusername]/';
$fields = array(
                      'user'=>urlencode($myusername),

                      'password'=>urlencode($mypassword)
               );
$fields_string = '';

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

header("location:../$_SESSION[myusername]/");

}

?>

<html>
<body>
Login Failed
</body>
</html>

This last script is suppose to check if $_SESSION is set. If it is set, it must run the code under if.
But what happens is that, even with the correct credentials, the last script skips the HTML section (Login Failed). Please advice me what am I doing wrong.

A: you are fail at here: header("location:../$_SESSION[myusername]/"); and here: $url = '127.0.0.1//$_SESSION[myusername]/';
replace header("location:../$_SESSION[myusername]/"); with header("location:../".$_SESSION['myusername']."/");
or
$newvar = $_SESSION['myusername'];
header("location:../$newvar/");

and $url = '127.0.0.1//$_SESSION[myusername]/'; with $url = '127.0.0.1/'.$_SESSION['myusername'].'/';
Because your code doesn't have ''(quote marks) for the key of $_SESSION array to get it's value and $url = '127.0.0.1//$_SESSION[myusername]/'; has // (2 slashes) and also using single quote will not get variable's values but it will assign variable name with $ mark to the new variable. Use double quotes if you want to write variables within quotation marks.

A: ok I manage to get it working. I decided to remove the 2nd script above from the mechanism. here are the changes to the 1st code
<?php
session_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="users"; // Database name
$tbl_name="clients"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect to file "login_success.php"
$_SESSION["myusername"] = $myusername;
$_SESSION["mypassword"] = $mypassword;

//set POST variables
$url = '127.0.0.1/'.$myusername .'/';
$fields = array(
                      'user'=>urlencode($myusername),

                      'password'=>urlencode($mypassword)
           );
$fields_string = '';

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

}
else {
echo "Wrong Username or Password";
}
?>

I changed the "$url"  to point straight to my site from the 1st php script.
<?php

session_start();
if(($_SESSION['myusername']=$_POST['user'])){

}
else {header("location:../main_login.php");}

my site uses the above mechanism to compare a session with the details given at login page. If they are not the same, it take you back to the login page. i wanted to do this so that I can prevent session hijacking.
Thanks to everyone who help! @fortune
I don't think anyone else would ever need this, as it seems like a problem I created for myself. but for the sake of having a solution to the question.


text:
Q: python 3d funcanimation not plotting I'm trying to pass a bunch(about 300) of 4 column panda df. each of these 300 df's are a frame in the animation. does anyone know why nothing is plotting? im new to funcanimation and im a little lost
my first function is suppose to be called to make each frame... but i dont know how to use offsets... not sure if im initializing the animation correctly because i used a zeros frame. i keep printing scatters the line after offsets but its always 0
"""
    PIPELINE
    1. MAKE FIGURE WINDOW
    2. CREATE AN INITIALIZATION FUNCTION
    3. CREATE A FUNCTION THAT PLOTS EACH FRAME
    4. USE FUNCANIM to animare

"""

# IMPORTS
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation
import os

def animate_scatters(iteration, data, scatters):
"""
Update the data held by the scatter plot and therefore animates it.

Returns:
    list: List of scatters (One per element) with new coordinates
   !!!!!!!!! ONLY DOES ONE FRAME AT A TIME!!!!!!!!
"""

#now we need to go into the directory and read the files
directory_of_embeddings = sorted([item for item in os.listdir(data) if not os.path.isdir(os.path.join(data,item)) and ".csv" in item])  # make of list of embeddings that excludes any other file type lis .DS_store
#print(directory_of_embeddings)

for file in directory_of_embeddings:
    print(file)
    embedding=pd.read_csv(data+'/'+str(file),delimiter=',')
    print(embedding)
    #embedding.drop(columns=embedding.columns[0], axis=1, inplace=True)
    embedding.columns=["X","Y","Z","JD"]
    print(embedding)
    scatters[iteration]._offsets3d = (embedding.X,embedding.Y,embedding.Z)
"""

def main(data, save=True):
    """
    Creates the 3D figure and animates it with the input data.

    Args:
        data (list): List of the data positions at each iteration.
        save (bool): Whether to save the recording of the animation. (Default to False).
    """

    # Attaching 3D axis to the figure
    fig = plt.figure()
    ax = p3.Axes3D(fig)

    # Initialize scatters
    """make 0's data frame for initialization"""
    scatters=[pd.DataFrame(np.zeros((1000,3)))]

    # Number of iterations/frames
    if os.path.isdir(data)==1:
        print('READY!')

    iterations=290
    # Setting the axes properties
    #ax.set_xlim3d([-50, 50])
    ax.set_xlabel('X')

    #ax.set_ylim3d([-50, 50])
    ax.set_ylabel('Y')

    #ax.set_zlim3d([-50, 50])
    ax.set_zlabel('Z')

    ax.set_title('3D self Example')

    # Provide starting angle for the view.
    #ax.view_init(25, 10)

    ani = animation.FuncAnimation(fig, animate_scatters, iterations, fargs=(data, scatters),interval=5000000000, blit=False, repeat=False)

    if save:
        Writer = animation.writers['ffmpeg']
        writer = Writer(fps=30, metadata=dict(artist='Me'), bitrate=1800, extra_args=['-vcodec', 'libx264'])
        ani.save('3d-iris.mp4', writer=writer)

data = '/Users/melanietu/Desktop/IRIS/3d'
main(data, save=True)


text:
Q: Change react class state between DOM elements I have 2 react DOM elements navbar and content-box. When clicked on an item in navbar, I would like it to change the state of content-box class component, thus, display another content.
class Content extends Component {
constructor(props) {
    super(props);
    this.state = {
        content: "news"
    }
}}

class Navbar extends Component{

render() {
    <button onClick={change state of Content element to "sport"} />
}}

Also, if a have multiple elements in DOM that I would like to be called independently is this the correct way?
In index.js:
ReactDOM.render(
    <React.StrictMode>
        <Navbar />
    </React.StrictMode>,
    document.getElementById('navbar')
);

ReactDOM.render(
    <React.StrictMode>
        <Content />
    </React.StrictMode>,
    document.getElementById('content')
);

these are then in the index.html called in different places.


text:
Q: how to make colors generated via Javascript be stored permanently in CSS file with or without use of PHP I have a js color picker. Now the user picks some colors one by one using it and these are applied to the page using JQuery.
After this the color is applied to the present page using JQuery.
My question is this- how can I store this color permanently into the CSS file with or without PHP code?

A: IMO you'd have to save the variable to your server and would need to write your style-sheet in a language that would be able to pull variables from your Server (eg. PHP).
Something along these lines:
<?php
    header("Content-type: text/css; charset: UTF-8");
    $colour = you_custom_function('colour');
?>
    background-colour: <?= $colour ?>;

For the actual fetch process in PHP I'd use mysqli : http://php.net/manual/en/book.mysqli.php


text:
Q: How to reference a function from within its own implementation? I'm developing a javascript application that consists of many objects and functions (object methods). I want to be able to log many events in the life cycle of the application. My problem is that inside the logger I want to know which function invoked the log entry, so I can save that data along with the log message. This means that every function needs to somehow be able to reference itself, so I can pass that reference to the logger.
I'm using javascript strict mode, so using arguments.callee inside the function is not allowed.
Here's a very simplified code sample you can run. I'm just using here alert instead of my logger for simplicity.
(function(){
"use strict";

window.myObject = {
    id : 'myObject',
    myFunc : function(){
        alert(this.id); // myObject
        alert(this.myFunc.id); // myFunc - I don't want to do this. I want something generic for all functions under any object
        alert('???') // myFunc
        alert(arguments.callee.id); // Will throw an error because arguments.callee in not allowed in strict mode
    }
}
myObject.myFunc.id = 'myFunc';

myObject.myFunc();
})();

*

*In the first alert - this related to myObject and not to myFunc

*In the second I alert - I referenced the function by its name, which I don't want to do, as I'm looking for a generic way to reference a function from within its own implementation.

*The third alert - open for your ideas.

*The fourth alert - would have worked if I didn't "use stict";. I want to keep strict mode since it provides better performance, and constitutes good coding practice.

Any input will be appreciated.
If you're not familiar with "strict mode", this is a good place read about it:
JavaScript Strict Mode

A: Here's a very hacky way of doing it:
(function(){
    "use strict";
    window.myObject = {
        id: 'myObject',
        myFunc: function () {
            // need this if to circumvent 'use strict' since funcId doesn't exist yet
            if (typeof funcId != 'undefined')
                alert(funcId);
        },
        myFunc2: function () {
            // need this if to circumvent 'use strict' since funcId doesn't exist yet
            if (typeof funcId != 'undefined')
                alert(funcId);
        }
    }
    // We're going to programatically find the name of each function and 'inject' that name
    // as the variable 'funcId' into each function by re-writing that function in a wrapper
    for (var i in window.myObject) {
        var func = window.myObject[i];
        if (typeof func === 'function') {
            window.myObject[i] = Function('var funcId = "' + i + '"; return (' + window.myObject[i] + ')()');
        }
    }

    window.myObject.myFunc();
    window.myObject.myFunc2();
})();

Essentially, we are circumventing the 'use strict' declaration by recompiling each function from a string after we've found out that function's name. To do this, we create a wrapper around each function that declares a string variable 'funcId' equal to our target function's name, so that the variable is now exposed to the function within through closure.
Eh, not the best way to do things, but it works.
Alternatively, you can simply call a non-strict function from within:
(function(){
    "use strict";

    window.myObject = {
        id: 'myObject',
        myFunc: function () {
            alert(getFuncName())
        },
        myFunc2: function () {
            alert(getFuncName());
        }
    }
})();

// non-strict function here
function getFuncName(){
    return arguments.callee.caller.id; // Just fyi, IE doesn't have id var I think...so you gotta parse toString or something
}

Hope that helps.

A: myFunc : function _myFunc(){
    alert(_myFunc); // function
}

Name your functions and reference them directly
To solve your logging purpose, use real sensible unique logging messages. If you want line information then throw an exception.

A: I don't think what you want to do (finding the name of the current function) is very easy to do. You might want to look into adding a preprocessing step (like is done for things like __line__ in C) but perhaps just a little OO/currying magic does the trick:
function logger(id){ return function(msg){
    return console.log(id, msg);
};}

window.myObject = {
    id : 'myObject',
    myFunc : function(){
        var log = logger('myFunc');

        log(1);  //prints "Myfunc, 1"
        log(2);  //prints "Myfunc, 2"
    }
};

This is kind of a cop out but is very simple and can be reasonably mantainable if you just remember to keep the ids and function names in track.


text:
Q: Start position of text style by CSS different position of text on PDF file I have a issue when using TCPDF to edit PDF file. This issue happen on Zend PDF also.
Look at attach image.
Position of text
The green text use css style, it stay center of vertical of green rectangle, the foot of "g" character stay in bottom of green rectangle.
But when I write this text using TCPDF(or Zend PDF) at the same position, the foot of "H" character stay in bottom of green rectangle (not foot of "g" character), that mean the text is outside the box(include "g" character).
Can you explain me why the start position of text using PDF library not same CSS style?
Thank you!

A: It takes much time to programmatically generate PDF. Much easier way would be using PDF generator that can take HTML as an input.
I'm involved in the project called pdfapi.io https://pdfapi.io. It can convert regular web pages with CSS styles and JavaScript to PDF documents. It also has nice PHP SDK as well.
And if you are using Zend Framework 2 or 3 you can use it as a module: https://github.com/pdfapi/zf2-pdfapi-module
Service is free of charge.
Hope that helps


text:
Q: Algorithms for eye gaze (eye-direction) in OPENCV I need to implement algorithm for eye gaze to know the direction of eye using opencv ,
i have been struggling for one month to do it using viola-jones algorithm with training classifiers provided by opencv
in a first step i based my research starting with facedetection.cpp with xml's for face and eye , it can detect faces and eye just for < 1m but i haven't found a method to know the eye direction
Now after some research , i've found some algorithms for eye-gaze but i don't wich one to chooose in term of it simplicity (because i'm just a newbie) and efficiency :

Distance-Threshold Algorithm
Mean-Shift Algorithm
Edge detetction ==> Hough Transformation
the Longest Line Scanning Occluded Circular Edge
Matching "one-circle" and "two-circle" algorithm
Neural network based approaches
Principal component analysis (PCA).
Starburst Algorithm
Kalman filter Velocity
Threshold Eye Movement Identification
Active appearence model (AAM)
CCL : Connected component labeling algorithm
CCA : colonial competitive algorithm
Blob detection
Lucas Kanade

So what algorithm you recommended me , and if there is another algorithm algorithms that i haven't mentionned , i need also a comparaison between those algorithms but it must be someone experienced in this field NB : i'm using ubuntu 14.04 and developping with C++
Any help will be much appreciated , thanks :)


text:
Q: Rsnapshot frequently exits with error 12 when processing tar.gz file I have an rsnapshot tool to backup some machines. It's running on a QNAP NAS and backing up several machines.
One of the things I backup is database backups. On one machine I create both plain text backup files, and a tar.gz of said files. Plain text ~4GB, tar.gz ~1GB.
A while ago I decided to rsnapshot only the tar.gz (no need to backup both files). The problem is that 19 out of 20 times the backup script fails with
ERROR: /opt/bin/rsync returned 12.

Upon investigation I see this happens when procesing the tar.gz file.
I don't think the problem happens with the plain text file (even though it is 4GB).
Do you know what could be happening?
Edit:
Here's some of the logs I get when running rsync manually. This first one seems to be error 30, which I also get sometimes:

srv/backup/database/daily/mydb.bak
     51458092 100%    3.96MB/s    0:00:12 (xfer#2, to-check=1007/1036)
[receiver] io timeout after 90 seconds -- exiting rsync error: timeout
  in data send/receive (code 30) at io.c(140) [receiver=3.0.8] rsync:
  connection unexpectedly closed (40 bytes received so far) [generator]
rsync error: error in rsync protocol data stream (code 12) at
  io.c(601) [generator=3.0.8]


text:
Q: A question about verifying the transverse of electric field I came accross a question about verifying the transverse of electric field in Peskin and Schroeder's QFT p179.
Given

$$ \mathcal{A}^{\mu}(\mathbf{k}) = \frac{ -e}{| \mathbf{k} | } \left( \frac{p'^{\mu}}{k \cdot p'}  - \frac{p^{\mu}}{k \cdot p} \right)  \tag{6.7} $$

and

$$ \mathcal{E} = -i \mathbf{k} \mathcal{A}^0 (\mathbf{k}) + i k^0 \mathcal{A}(\mathbf{k}) \tag{6.9} $$

it is said

you can easily check that the electric field is transverse: $\mathbf{k} \cdot \mathcal{E}(\mathbf{k}) =0 $

I tried to vertify this almost trivial relation and I didn't get it...
Here is my attempt
$$ \mathbf{k} \cdot \mathcal{E}(\mathbf{k}) = \left(  \frac{ -e}{| \mathbf{k} | } \right) \left[ - i \mathbf{k} \frac{ \mathbf{k} p'^0 - k^0 \mathbf{p}'}{ k \cdot p'}  +   i \mathbf{k} \frac{ \mathbf{k} p^0 - k^0 \mathbf{p}}{ k \cdot p} \right] \tag{1}$$
I may use $p^{\mu}=(p^0, \mathbf{0})$ (since the particle is initially at rest) and $k^0=|\mathbf{k}|$. It seems that Eq. (1) is still not necessarily zero. Would you provide, at least, any hint how to show Eq. (1) is zero?

A: Hint: You should find something like:
$$
\propto \frac{k_\mu p'^\mu}{k_\mu p'^\mu} - \frac{k_\mu p^\mu}{k_\mu p^\mu} = 0
$$
Spoiler: I omit the $-e/|\vec k|$ factor for brevity. We have
$$
A^\mu = \frac{p'^{\mu}}{k^\mu p'_\mu}  - \frac{p^{\mu}}{k^\mu p_\mu}
$$
and
$$
k^0=|\vec k|.
$$
We can begin by rewritting
$$
\vec \epsilon = -i \vec k A^0 + i k^0 \vec A \\
=-i\vec k \left(\frac{p'^0}{k^\mu p'_\mu}  - \frac{p^0}{k^\mu p_\mu}\right)
+ik^0 \left(\frac{\vec p'}{k^\mu p'_\mu}  - \frac{\vec p}{k^\mu p_\mu}\right)
$$
Now taking the dot product,
$$
\vec k \cdot \vec \epsilon\\
=-i|\vec k|^2 \left(\frac{p'^0}{k^\mu p'_\mu}  - \frac{p^0}{k^\mu p_\mu}\right)
+ik^0 \left(\frac{\vec k \cdot\vec p'}{k^\mu p'_\mu}  - \frac{\vec k \cdot\vec p}{k^\mu p_\mu}\right)
$$
Now utilise $k^0=|\vec k|$;
$$
=-i k_0 \left(\frac{k_0 p'^0}{k^\mu p'_\mu}  - \frac{k_0 p^0}{k^\mu p_\mu}\right)
+ik^0 \left(\frac{\vec k \cdot\vec p'}{k^\mu p'_\mu}  - \frac{\vec k \cdot\vec p}{k^\mu p_\mu}\right)\\
\propto \frac{k_\mu p'^\mu}{k_\mu p'^\mu} - \frac{k_\mu p^\mu}{k_\mu p^\mu} = 0
$$


text:
Q: angular 8 : Why the component is not loading? So I created an app with angular-cli . I have following structure in src dir.
.
├── app
│   ├── app-routing.module.ts
│   ├── app.component.css
│   ├── app.component.html
│   ├── app.component.spec.ts
│   ├── app.component.ts
│   ├── app.module.ts
│   └── notifications
│       ├── notifications.component.css
│       ├── notifications.component.html
│       ├── notifications.component.spec.ts
│       └── notifications.component.ts
├── assets
├── environments
│   ├── environment.prod.ts
│   └── environment.ts
├── favicon.ico
├── index.html
├── main.ts
├── polyfills.ts
├── protocol.js
├── styles.css
└── test.ts

Routes have following.
RouterModule.forRoot([
        { path: '', component: AppComponent },
        { path: 'notifications', component: NotificationsComponent}
    ])

AppComponent has Html for the login page.
Once the form is submitted I redirect to notifications component with [routerLink]="['/notifications']"
Now I am expecting <app_root></app_root> in the index.html to be populated with notifications-component.html.
First of all, is the assumption above right?
I tried to change the selector in notification-component.ts
I tried putting <app-notifications></app-notifications> in <app_root></app_root>
I tried putting <router-outlet></router-outlet> in <app_root>, app.component.html and notifications.component.html. (Only app.component.html worked. but it is showing both HTMLs.)
If the assumptions above is not right, how is it supposed to work?
P.S.
THANKS, EVERYONE FOR PROMPT RESPONSE.
I know all of your answers are right, but I could only accept one answer.

A: For my case,case sensitity was the problem. One mistake that new user like me could make, is path name case sensitivity.

A: A couple of changes are required to your approach:

*

*Add <router-outlet></router-outlet> to the app.component.html file.

*Create another component for login ( eg. LoginComponent )

*Update route
   RouterModule.forRoot([
    { path: '', pathMatch: 'full', component: LoginComponent },
    { path: 'notifications', component: NotificationsComponent }
   ])],

*Also it's not recommended to use the home path for login, you can change the url to /login and re-route if it's not authenticated.
Have a look https://stackblitz.com/edit/angular-dfhxek.

A: AppComponent should be your app's root component, with <router-outlet></router-outlet> inside (and possibly little or nothing more). Don't have a route leading there, it's the one component that'll always be rendered.
Create a separate component handling login (LoginComponent for example), and have routes like:
RouterModule.forRoot([
        { path: 'login', component: LoginComponent},
        { path: 'notifications', component: NotificationsComponent}
        { path: '', redirectTo: 'login'},
    ])

A: A better way of doing what you want would be like this

*

*Create a new component for login

*In the app.component.html place the <router-outlet></router-outlet>

*Change your routing module this way:
RouterModule.forRoot([
        { path: '', component: LoginComponent},
        { path: 'notifications', component: NotificationsComponent}
    ])

A: Your RouterModule.forRoot cannot have the AppComponent. This component is bootstrapped in the main.ts.
You say you added the login html inside your AppComponent. This is not correct, you should move this to a separate component, LoginComponent. Once you've done this you can update your app.component.html:
<router-outlet></router-outlet>

You can obviously add extra stuff here which will always be visible, like navigation or a footer.
You should then update your routes to this:
RouterModule.forRoot([
  { path: '', component: LoginComponent},
  { path: 'notifications', component: NotificationsComponent}
]);

A: I just understood that the <router-outlet></router-outlet> line in app.component.html must be the only line in that file, and I moved all my app.component.* code to a new component I called 'home.component.*', and routed to 'home' from 'login' once login was successful. This worked well for me.


text:
Q: Association properties, nightmare performance (Entity Framework) I have a fairly large EF4 model, using POCO code gen. I've got lots of instances where I select a single entity from whichever table by its ID.
However on some tables, this takes 2 minutes or more, where on most tables it takes less than a second. I'm out of ideas as to where to look now, because I can't see any reason. It's always the same tables that cause problems, but I can query them directly against the database without problems, so it must be somewhere in Entity Framework territory that the problem is coming from.
The line is the quite innoccuous:
Dim newProd As New Product
Product.ShippingSize = Entities.ShippingSizes.Single(Function(ss) ss.Id = id)

*

*id is simply an integer passed in from the UI, Id on my entity is the primary key, which is indexed on the database

*Entities is a freshly created instance of my entity framework datacontext

*This is not the first query being executed against the Context, it is the first query against this EntitySet though

*I have re-indexed all tables having seen posts suggesting that a corrupt index could cause slow access, that hasn't made any difference

*The exact same line of code against other tables runs almost instantly, it's only certain tables

*This particular table is tiny - it only has 4 things in it

Any suggestions as to where to even start?
--edit - I'd oversimplified the code in the question to the point where the problem disappeared!

A: Where to start?

*

*Print or log the actual SQL string that's being sent to the database.

*Execute that literal string on the server and measure its performance.

*Use your server's EXPLAIN plan system to see what the server's actually doing.

*Compare the raw SQL performance to your EF performance.

That should tell you whether you have a database problem or an EF problem.

A: Seems like this is a function of the POCO template's Fixup behaviour in combination with lazy loading.
Because the entity has already been loaded via Single, subsequent operations seem to be happening in memory rather than against the database. The Fixup method by default makes Contains() calls, which is where everything grinds to a halt while 10s of thousands of items get retrieved, initialised as proxies, and evaluated in memory.
I tried changing this Contains() to a Where(Function(x) x.Id = id).Count > 0 (will do logically the same thing, but trying to force a quick DB operation instead of the slow in-memory one). The query was still performed in-memory, and just as slow.
I switched from POCO to the standard EntityGenerator, and this problem just disappeared with no other changes. Say what you will about patterns/practices, but this is a nasty problem to have - I didn't spot this until I switched from fakes and small test databases to a full size database. Entity Generator saves the day for now.


text:
Q: jquery droppable is not working Guys. I spent few hours just for checking my jquery, why it doesn't work well. Just confused why droppable function doesn't firing alert when the square div has dropped into box's div.
Here is my html

<title>jquery - draggable </title>
    <link rel="stylesheet" type="text/css" href="css/style.css">

And this is my style
#box {
    margin: 0 auto;
    background: #ecf0f1;
    border-radius: 10px;
    border-style: dashed;
    height: 100px;
    width: 100px;
}
#square {
    margin: 0 auto;
    background: #3498db;
    border-radius: 10px;
    height: 100px;
    width: 100px;
}

And this is my javascript
$(document).ready(function(){
    $("#square").draggable();

    $("#box").droppable({
        drop: handleDropEvent
    });

    function handleDropEvent(event, ui){
        alert('Hello');
    }

});

Any help would be appreciated. Thank you!

A: Play with droppables tolerance option.

*

*"fit": Draggable overlaps the droppable entirely.

*"intersect": Draggable overlaps the droppable at least 50% in both directions.

*"pointer": Mouse pointer overlaps the droppable.

*"touch": Draggable overlaps the droppable any amount.

$(document).ready(function(){
    $("#square").draggable();

    $("#box").droppable({
        drop: handleDropEvent,
       tolerance:"pointer"
    });

    function handleDropEvent(event, ui){
        alert('Hello');
    }

});
#box {
    margin: 0 auto;
    background: #ecf0f1;
    border-radius: 10px;
    border-style: dashed;
    height: 100px;
    width: 100px;
}
#square {
    margin: 0 auto;
    background: #3498db;
    border-radius: 10px;
    height: 100px;
    width: 100px;
}

<title>jquery - draggable </title>
    <link rel="stylesheet" type="text/css" href="css/style.css">

A:  $("#box").droppable({
        drop: handleDropEvent,
        tolerance:"pointer"
    });

would work as explained by SCHTAILian.
But this would force you to keep your pointer inside the #box div so the droppable #square would bee dropped correctly on it.
here is Another approach fiddle http://jsfiddle.net/naeemshaikh27/p0n27hcz/3/
just remove the
 margin:auto;


text:
Q: Coupled differential-integral equation This is coming from a physics paper I'm reading. It's been a while since I've done much differential equation solving and the system here is a bit unorthodox in that I'm actually searching for the initial conditions.
I would like to show that
$f(0) = g(0) (1 -  e^{-a \tau I}) + I$ where $I = \int_0^{\infty}\frac{f(t)}{\tau} dt$
given the differential equations:
$\frac{df}{dt} = - a f(t) g(t) - f(t)/\tau$
$\frac{dg}{dt} = - a f(t) g(t)$.
It might be important to state that f(t) and g(t) $\rightarrow 0$ as $t\rightarrow \infty$.
Thanks!
EDIT: $a$ and $\tau$ are constants greater than zero and everything's real.
EDIT: Actually $g(\infty)$ cannot be 0 [see comments below].

A: First we find $g(t)$ and as $g'(t)/g(t)=-af$ then we have
$$g(t)= g(0)e^{-a\int_0^t f(s)ds} $$
Now integrate the first equation between 0 and $t$ to give
$$\int_0^t f'(s) ds= -\int_0^t a f(s)g(s)ds - \int_0^t \frac{f(s)}{\tau} ds $$
Take the limit $t \to \infty$ then
$$-f(0)= -\int_0^{\infty} af(z)g(0) e^{-a\int_0^zf(s) ds}dz -\int_0^\infty \frac{f(s)}{\tau} ds $$
So the second term is intergated to give
$$g(0)e^{-a \int_0^z  f(s) ds} |_{z=0}^{\infty}= -g(0)[1-e^{-a\int_0^ \infty f(s) ds}] $$
which gives the result


text:
Q: Cannot see UIBinder output when rename-to attribute removed from module in GWT application I have a module hellomvp.gwt.xml with rename-to="hellomvp.gwt" and application works fine. But When I remove this remove-to attribute I don't see any output rendered. Why?

and in the html file, I have
<script type="text/javascript" language="javascript" src="../hellomvp/hellomvp.nocache.js"></script>

A: I think, you will get a 404 - File not found. That happened because ou removed the rename-to attribute.
In case you are removing the rename-to-attribute, you have to change the script tag to something like that:
<script type="text/javascript" language="javascript" src="[package-name of the module descriptor location]/[package-name of the module descriptor location].hellomvp.nocache.js"></script>

The src atribute is relativ to your host page, so the path might be different.
Compile your project and take a look at your war/webcontent-folder. There you can see what are the correct paths.

A: @EI's answer is good.
with/out rename-to attribute builds the war content in different path convention thus to include js is slightly different.
if the package is com.example.test containing test.gwt.xml
war content : without rename-to in module

*

*war

*

*com.example.test.test

*

*test.nocache.js

thus in < script > tag
src="com.example.test.test/com.example.test.test.nocache.js"
war content : with rename-to="test" in module

*

*war

*

*test

*

*test.nocache.js

thus in < script > tag
src="../test/test.nocache.js"


text:
Q: Showing PDE uniqueness in box Given PDE $\Delta u= -1$ for $|x|<1,|y|<1$. With boundary conditions $u=0$ for $|x|=1$ and $\frac{\partial u}{\partial x}-\frac{\partial u}{\partial y}=0$ for $|y|=1$. Show that there is at most one solution in $|x|<1,|y|<1$.
I'm not used to seeing boundary conditions of this type. I want to do something like assume $w$ is the difference of two solutions and then $0=\int w \Delta w = \cdots$, but I'm not getting anything with this BC.

A: You are on the right track. Let $u_1, u_2$ be two solutions, and let $w = u_1 - u_2$. You want to show that $w$ is constant, in which case it must be $w \equiv 0$ since $u_1 = u_2 = 0$ whenever $|x| = 1$. Let $\Omega$ be the square $\{ (x,y): |x| < 1, |y| < 1 \}$. Then
$$ \int_{\Omega} |Dw|^2 \, dx = - \int_{\Omega} w \Delta w \, dx + \int_{\partial \Omega} \frac{\partial w}{\partial \nu} w \, dS$$
where $dS$ is the surface measure and $\nu$ is vector normal to the surface. Because $\Delta w = 0$, the first term vanishes, and now we're left with the integral over $\partial \Omega$. Because $\partial \Omega$ is just the four sides of a square, you'll be able to explicitly calculate that each of the four integrals is zero by using the known boundary conditions. As a final hint, it might be useful to remember that $f \frac{\partial f}{\partial x} = \frac{1}{2} \frac{\partial}{\partial x}[f^2]$.


text:
Q: How to hide the caret in an HTML text input field? If I have an HTML input field like this one:
<input type="text" id="mytextfield"/>

all browsers seem to show the caret (insertion point) in the field. Is is possible to prevent this from appearing by applying some CSS or javascript?
(My reason for asking is that my input is the basis of a GWT-Ext combo box like the ones on http://www.gwt-ext.com/demo/#linkedComboBox - you can't type in it, but you can still see the caret, which is annoying).

A: What you could try is disable the input element and explicitly set its color to black:
<input type="text" disabled="disabled" style="color: black;" ... />

This should work for the GWT-Ext combo box (at least it did when setting the attributes in firebug).


text:
Q: how to apply same stash to different branches in git? I have four branches lets say A B C D.
I worked on branch B for some function and created stash.
This feature I also want in branch A and D .
Is there any way that I can use this stash from B and apply to A and D also and definitely I want it on B too that's why I don't want to commit instantly and go for stash.

A: git checkout A
git stash apply
git checkout D
git stash apply

Git won't delete your stash until you call git stash drop, so feel free to apply it to as many branches as you like!

A: beaumontwebdev answer works good if you want different branches share the same stash.
if you have different stashes on different branches and you want to go back to your stashes on a particular branch. you need to do as follows:
git stash list
then pick out the stashes on your desired branch and to check what you have in that stash, you need to
git stash show stash@{1}
if you want to pop that stash out on your desired branch.
git stash apply stash@{1}
this link is the reference


text:
Q: How does Magento figure out shipment speed detail? When I update a shipment in the admin with a tracking number, Magento will automatically figure out what kind of "speed" it is.
For example, I log on to admin -> Orders -> open an unprocessed order -> click to create a shipment. I would select "UPS", enter a tracking number, and submit the shipment. Once this is complete, Magento displays the following, even though I did not specify Next Day Air, nor is there any shipping rate request from UPS, as far as I can see on the admin side. The price is what the customer already paid during checkout.
Shipping & Handling Information
Track Order
United Parcel Service - *Next Day Air* $69.10

How or where does it figure out that this is a Next Day Air shipment?
UPDATE: made some clarifications.
UPDATE 2: In sales_flat_order.shipping_method, you'll find the shipping code responsible for the order.

A: It's not quite clear what you're asking, but in general Magento will communicate with the UPS API, which gives it access to UPS internal codes for package type, shipping, etc.  Most of these are translated using code in the class file
app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php

For example, the origin shipment codes for US domestic packages
#File: app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php
        'originShipment'=>array(
            // United States Domestic Shipments
            'United States Domestic Shipments' => array(
                '01' => Mage::helper('usa')->__('UPS Next Day Air'),
                '02' => Mage::helper('usa')->__('UPS Second Day Air'),
                '03' => Mage::helper('usa')->__('UPS Ground'),
                '07' => Mage::helper('usa')->__('UPS Worldwide Express'),
                '08' => Mage::helper('usa')->__('UPS Worldwide Expedited'),
                '11' => Mage::helper('usa')->__('UPS Standard'),
                '12' => Mage::helper('usa')->__('UPS Three-Day Select'),
                '13' => Mage::helper('usa')->__('UPS Next Day Air Saver'),
                '14' => Mage::helper('usa')->__('UPS Next Day Air Early A.M.'),
                '54' => Mage::helper('usa')->__('UPS Worldwide Express Plus'),
                '59' => Mage::helper('usa')->__('UPS Second Day Air A.M.'),
                '65' => Mage::helper('usa')->__('UPS Saver'),
            ),

Or the actual method codes
        'method'=>array(
            '1DM'    => Mage::helper('usa')->__('Next Day Air Early AM'),
            '1DML'   => Mage::helper('usa')->__('Next Day Air Early AM Letter'),
            '1DA'    => Mage::helper('usa')->__('Next Day Air'),
            '1DAL'   => Mage::helper('usa')->__('Next Day Air Letter'),
            '1DAPI'  => Mage::helper('usa')->__('Next Day Air Intra (Puerto Rico)'),
            '1DP'    => Mage::helper('usa')->__('Next Day Air Saver'),
            '1DPL'   => Mage::helper('usa')->__('Next Day Air Saver Letter'),
            '2DM'    => Mage::helper('usa')->__('2nd Day Air AM'),
            '2DML'   => Mage::helper('usa')->__('2nd Day Air AM Letter'),
            '2DA'    => Mage::helper('usa')->__('2nd Day Air'),
            '2DAL'   => Mage::helper('usa')->__('2nd Day Air Letter'),
            '3DS'    => Mage::helper('usa')->__('3 Day Select'),
            'GND'    => Mage::helper('usa')->__('Ground'),
            'GNDCOM' => Mage::helper('usa')->__('Ground Commercial'),
            'GNDRES' => Mage::helper('usa')->__('Ground Residential'),
            'STD'    => Mage::helper('usa')->__('Canada Standard'),
            'XPR'    => Mage::helper('usa')->__('Worldwide Express'),
            'WXS'    => Mage::helper('usa')->__('Worldwide Express Saver'),
            'XPRL'   => Mage::helper('usa')->__('Worldwide Express Letter'),
            'XDM'    => Mage::helper('usa')->__('Worldwide Express Plus'),
            'XDML'   => Mage::helper('usa')->__('Worldwide Express Plus Letter'),
            'XPD'    => Mage::helper('usa')->__('Worldwide Expedited'),
        ),

etc.
If that's not what you were after, a little more specificity in your question would help.


text:
Q: Outlier detection with robust multiple regression model I have a set of features (eg, location, income, budget, education) that I use to predict a continuous variable (say, amount spent per day on the internet). I am interested in detecting outliers. I want my model to be very strict and not to be swayed by outliers. I want my outlier detection to be done on the fly. My method is to use all the data I have so far to create a regression and then see if any point are above 3 SD from the residual mean (0). I then re-train the regression using all of the data EXCEPT the points I had just determined to be 3 SD from the residual mean. I continue this for some preset number of iterations, at each turn removing outliers and re-training. Each day I iteratively retrain the model using the new data and all of the old data.
I was wondering if there is a name for this technique-- since it's the first thing I thought of, someone else must have thought of it already?

A: The rule that you are talking about is known and it is called 3-$\sigma$ rejection rule. This is the simplest way of robustifying the regression model. You can find anything you are searching for here.

A: This rule is related to  the three sigma rule of thumb, or three-sigma rule, and it has own wiki page. For a Gaussian distribution, this interval contains $\pm 99.73\%$  of the cases. So your method is often called "three-sigma edit rule"; more precisely, iterated or iterative $3$-sigma rejection scheme in your case.
Doing so, you are using a kind of standard score called $Z$-score or $Z$-value: $$\frac{x_i-\bar{x}}{\sigma}\,$$
compared to $3$ and $-3$, and whose absolute value is called the two sided Grubbs test.
In different domains, people use a two-sigma or a five-sigma, depending on the level of confidence they require. Though common, such  methods can wor for reasonable symmetric and unimodal distributions. If not, it is likely to be very imprecise, especially if you have few points.
Moreover, it is not considered robust, as the sample mean and the standard deviation estimates are not robust. Some perform it the iterative way, as you do. Some authors prever a more robust alternative based on median statistics:
$$0.6745\frac{x-\text{median}(x)}{\text{MAD}(x)}\,$$
where $\text{MAD}$ denotes the Median Absolute Deviation. More details in
  Finding outliers in numerical data, A survey of outlier detection methodologies (V. J. Hodge, 2004),


text:
Q: Mask text Flutter I wanna format of differents ways a value from textfield.
In a pseudocode it would be like this:
if length(value) == 2: mask = ##; if length(value) == 3: mask = #.##;
I made this, but the mask don't change.
var maskedKg =
    MaskTextInputFormatter(mask: '#', filter: {"#": RegExp(r'[0-9]')});

switch (controller.text.length) {
    case 2:
      {
        controller.value = maskedKg.updateMask(mask: '##');
        break;
      }
    case 3:
      {
        controller.value = maskedKg.updateMask(mask: '#.##');
        break;
      }
    case 4:
      {
        controller.value = maskedKg.updateMask(mask: '##.##');
        break;
      }
    case 5:
      {
        controller.value = maskedKg.updateMask(mask: '###.##');
        break;
      }
  }


text:
Q: 555 Astable Timer produces incorrect period/frequency I am building a 555 astable timer circuit for a course which must match the BPM of a song. The song has a BPM of 104, which requires a timer frequency of roughly 1.733 Hz.
The circuit looks as follows:

(the green wires go off to the left onto another breadboard, which looks as follows:)

It is hard to see, but the 0.01µF capacitor goes to pin 5 of the 555 timer.
The values used in the circuit as follows (measured using a LCR meter):
R1 = 5.5kΩ
R2 = 38.5kΩ
Ctotal = 10.02 µF
The problem is that the circuit produces a frequency of roughly 1.5, far off the from the desired/predicted frequency of 1.733. 5V Power is being supplied to both rails, the chip has been replaced, but to no avail. Here is a picture of the simulated circuit in LTspice:

Is this due to some limits of the 555 timer at frequencies nearing 1Hz or due to some miswiring on my part?

simulate this circuit – Schematic created using CircuitLab

A: As practically everyone has commented, electrolytic capacitors are not usually chosen for precise timing applications.  CDE capacitors have typical capacitance
tolerances of ±20%, –10% +50%, and –10% +75%.  So your circuit is most likely working perfectly, but the value of the capacitor is not known.
However, since you have the circuit built and running, you can use it to estimate the resistor values required to make the circuit operate at your desired frequency.  If you are at 1.5 Hz, you are at 1.5/1.733 or 86.6% of your target frequency.  You can achieve 1.733 Hz by multiplying the values of the two timing resistors by 0.866, which would yield (in this case) 4.76K and 33.3K.  You can do the math and put in parallel resistors to achieve this result.  Even if you were to spend the money and get precision resistors and capacitors, the 555 timers will vary a couple of percent from chip to chip, so that in practice it is common to build a circuit that gives a too-low frequency (just as you have done) and leave pads to add parallel resistors to the timing resistors which are selected to compensate for component errors.
Good luck!

A: You could replace the 2 resistors with trim pots and dial in the values better.
https://www.digikey.com/products/en/potentiometers-variable-resistors/trimmer-potentiometers/80?k=trim+pot&k=&pkeyword=trim+pot&sv=0&pv69=80&sf=1&FV=ffe00050&quantity=&ColumnSort=0&page=1&pageSize=25


text:
Q: Advanced SCSS/SASS mixin/function I've made a pretty nice chaining effect, that I would love to turn into a mixin, or function, but I can't wrap my head around how to build it. Searched everywhere but I can't assemble the puzzle.
The output should look like this
{
  opacity: 0;
  transform: translateY(3em);

  @keyframes moveUp {
    from {
      opacity: 0;
      transform: translateY(3em);
    } to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  .inview ~ & {
    animation: moveUp 1s forwards;

    @for $i from 1 through 20 {
      &:nth-child(#{$i}) {
        animation-delay: (0.1 * $i) + s
      }
    }
  }
}

My current attempt (doesn't compile), looks like this:
    @mixin inviewChainAnimation($animationName, $from, $to, $duration, $delay, $count:20) {
        $from;

        @keyframes #{$animationName} {
            from {
                $from;
            }
            to {
                $to
            }
        }

        .inview ~ & {
            animation: #{$animationName} #{$duration} forwards;

            @for $i from 1 through #{$count} {
                &:nth-child(#{$i}) {
                    animation-delay: (#{$delay} * $i) + s
                }
            }
        }
    }

How can I get two objects ($from and $to) passed through a function. Is that even possible?

A: Have you tried SASS-maps to render the declarations? For example:
$mapFrom: (opacity: 0, transform: translateY(3em));
$mapTo: (opacity: 1, transform: translateY(0));

And then in your mixin using of @each directive:
@each $key, $value in $from {
  #{$key}: #{$value};
}

But then there is another problem. If I try to parse the modified mixin, I get the following error:
Error: "20" is not an integer.
    on line 22 of test.scss, in `inviewChainAnimation'
    from line 34 of test.scss

The error occurs at this line:
@for $i from 1 through #{$count} {

To solve this change #{count} to $count. The same for #{$delay}. That's it. Here is the final working mixin:
@mixin inviewChainAnimation($animationName, $from, $to, $duration, $delay, $count: 20) {
  @each $key, $value in $from {
    #{$key}: #{$value};
  }

  @keyframes #{$animationName} {
    from {
      @each $key, $value in $from {
        #{$key}: #{$value};
      }
    }
    to {
      @each $key, $value in $to {
        #{$key}: #{$value};
      }
    }
  }

  .inview ~ & {
    animation: #{$animationName} #{$duration} forwards;

    @for $i from 1 through $count {
      &:nth-child(#{$i}) {
        animation-delay: ($delay * $i) + s
      }
    }
  }
}

Use of the mixin:
.container {
  @include inviewChainAnimation('foo', $mapFrom, $mapTo, .15, .1);
}

If you have the need to pass only one set of css properties, you can use @content to simplify your mixin. See for an example at Passing css property:value into a mixins argument.


text:
Q: Eclipse Build Path - declared packages does not match In my Eclipse project I added source folder "pmml-evaluator/src/main/java" as a source folder, so I expect that all the subfolders are considered to be packages names.
Unfortunately the Eclipse expects package not "org.jpmml.evaluator" but "main.java.org.jpmml.evaluator". Did I missed something or it is Eclipse bug?
Eclipse Mars.1 Release 4.5.1

The declared package "org.jpmml.evaluator" does not match the expected package
   "main.java.org.jpmml.evaluator"

A: Maven doesn't know that is a java project because it's not specified in the pom.xml, you should add:
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.1</version><!--$NO-MVN-MAN-VER$ -->
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>

and reimport. Otherwise you can change source folder in java build path
PS: Make sure you delete .settings and .project before reimporting, or eclipse will import it the same way as before


text:
Q: Arduino command timeout I'm currently working with a Arduino to forfill one of my DIY projects.
As it currently stands, I have my fingerprint scanner (GT-511C3) connected to my Arduino and that works great. I'm able to verify enrolled fingerprints.
The verifying of the finterprints happends via Raspberry Pi command (whom is initiated by a button press)
Logically, this means, when the button is pressed, the Raspberry Pi sends a 'validate' command to the Arduino, whom in return ask the Fingerprint scanner to run the validate command.
However, I would like to have a timeout after the validate command it sent. The timeout needs to make sure that if the button pressed (and the validate command is initated) but no one puts their finger on the machine it timeouts and reverts back to a state where it waits for the validate command.
I'm not able to complete this. This is the code I've tried:
#include "FPS_GT511C3.h"
#include "SoftwareSerial.h"

FPS_GT511C3 fps(4, 5);
int val = 0;

void setup()
{
  Serial.begin(9600);
  delay(100);
  fps.Open();
  fps.SetLED(false);
}

void loop(){

if (Serial.available() > 0) {
  Continue:
  if(Serial.find("validate")){
    fps.SetLED(true);
    do {
      ++val;
      delay(100);
    }
    while(fps.IsPressFinger() == false || val > 150);
    if(val <= 150){
      fps.SetLED(false);
      goto Continue;
    }
    if (fps.IsPressFinger()){
      fps.CaptureFinger(false);
      int id = fps.Identify1_N();
      if (id <200)
    {
        Serial.print("Verified ID:");
        Serial.println(id);
        fps.SetLED(false);

    }
    else
    {
          Serial.println("Finger not found");
          fps.SetLED(false);
    }
  }
  else
  {
            Serial.println("Please press finger");
  }
  delay(100);

    }
  }
}

The code otherwise works fine, if the finger is placed and validated, it turns off and goes back to waiting for another validate command.
Any help would be greatly appreciated!

A: First, get rid of the label and goto. There is no justification for it here; it's considered bad programming practice and shouldn't be used unless you know exactly what you're doing. Only in Assembly is it okay to use goto (equivalent to JMPs) liberally.
Next, your while condition is wrong. If you try to interpret it, you'll notice it doesn't make any sense:
Wait for as long as nobody has placed a finger or if the timeout has expired.
What you probably want is:
Wait for as long as nobody has placed a finger and the timeout has not expired.
which translates to:
while(fps.IsPressFinger() == false && val < 150);
The IF condition that follows, is also wrong and should mean:
if the timeout has expired
translating to:
if(val >= 150){
  fps.SetLED(false);
  val = 0;
  continue;
}

Notice the use of the continue keyword which restarts a loop. To make it legit, change if (Serial.available() > 0) to while (Serial.available() > 0).


text:
Q: what's the featherjs way to handle non-data related actions and child objects? I just discovered feathersjs and really like the idea behind it, even though I'm still unsure how the service-based philosophy can fit for applications which are more complex than a simple CRUD UI.
In order to better understand it I made up an example: Consider an application where you can create and share surveys. You could easily manage to create a survey service to create, update and get the properties of a survey (i.e. questions and answers). But how should one handle the following aspects:
1) There are actions, i.e. service invocations which do not affect the data at all. One action could be to send a reminder email to all invited users who did not participate on a survey yet. If not using feathers I would created a dedicated express endpoint for this, but how do those actions fit in the feathers philosophy? Should one create a service (only implementing one HTTP verb) per action? This will get confusing soon. Use hooks that detect updates on virtual fields and trigger the action? Hard to document and confusing as well.
2) Imagine users could add comments to a survey. The comments would be part of the survey model (I'd use MongoDB for that, so consider each survey object to have a comments array). The client web would invoke the GET /survey/123 method on the survey service which would return the comments amongst the other properties (question, answers, ..). But what about adding comments? Should I use a dedicated service for it, or how would this fit into the survey service? How would such a request look like?

A: From the Feathers slack channel: https://feathersjs.slack.com/messages/C0HJE6A65/
Sending an email is fine in a hook. For actions you could do a patch with a certain action attribute and then use hooks to determine which action should be performed, etc. The other way would be a simple small service that only has create implemented. For comments I would probably have a comments or survey-comments service and then your survey/123 could populate the comments. Or the web could make 2 calls, one to fetch the survey, the other to fetch the comments.


text:
Q: How to make a custom alert dialog that is called using a method instead of embedding into parent view? How to make a custom alert dialog that is self destroyed when dismissed and called from any where in the app with a static method. Same as in react-native method

alert()

My current code:
import { View } from 'react-native';
import { Portal, Dialog } from 'react-native-paper';

static function showDialog(title, paragraph, buttonLabelText, onDismissHandler, canDismiss) {
    return (
        <View style={{ flex: 1 }}>
        <Portal>
            <Dialog dismissable={canDismiss} visible={need a value here} onDismiss={() => {this.onDismissHandler()}}>
                <Dialog.Title>{title}</Dialog.Title>
                <Dialog.Content>
                    <Paragraph>{paragraph}</Paragraph>
                </Dialog.Content>
                <Dialog.Actions>
                    <Button onPress={() => {this.onDismissHandler()}}>{buttonLabelText}}</Button>
                </Dialog.Actions>
            </Dialog>
        </Portal>
      </View>
    )
}

export default { showDialog };

A: React-native has it's on Alert and you can use like below.
import { Alert } from 'react-native';
import _ from 'lodash';

export const showPopupAlert = (message, onOKPressed: _.noop) => {
    Alert.alert(
      '',
      message,
      [
        { text: 'OK', onPress: onOKPressed },
      ],
    );
};

export const showOptionAlert = (message, buttonOk, buttonCancel, action, title) => {
  Alert.alert(
    title,
    message,
    [
      { text: buttonOk, onPress: action },
      { text: buttonCancel },
    ],
    { cancelable: false },
  );
};

Save this as ShowAlert.js as root laval component and call like below.
import { showPopupAlert } from 'yourpath/ShowAlert';
showPopupAlert('Your message'); // Call like this


text:
Q: Show content from database This is my first post on Wordpress StackExchange, so please be gentle.
I've been working with WordPress for some time but more as a front-end developer and not too much back end dev. I have a background working in Joomla (don't hold that against me...)
I am working on a current project, where an API is injecting data into a database, which the WordPress site has access to (it's not been decided whether it is the WordPress database or an external database yet. The data is based around art works, so various data is associated with each piece of art and there will also require a search/filter option to look through the various data within the db.
My question is how can I get the data to show in the frontend of the site and use filtering/search and so on? Is there a plugin that I can use to look at the database and build pages for each category and then each piece of art? Or would something need to be built, if so, where do I start from a backend point of view?
I know I haven't put any code as to how I've tried to work this out myself so far, I'm only asking if this can be done and what the best way to achieve this is from a Wordpress best practice point of view.
Thanks for any help in advance!

A: You could use custom post types and custom taxonomies.
Using the custom post types to store data, taxonomies to categorize the data and you can utilize WordPress' default searching functionality.
https://codex.wordpress.org/Post_Types
https://codex.wordpress.org/Taxonomies
https://codex.wordpress.org/Creating_a_Search_Page


text:
Q: Objective-C: What's the difference between NULL, nil and @""? As the title says, what's the difference between NULL, nil and @"" ?
For example, if I want to check a string in a dictionary is empty.
Which condition should I use ?
if ([dictionary objectForKey:@"aString"] == nil)

or
if [[dictionary objectForKey:@"aString"] isEqualToString:@""]

or
if ([dictionary objectForKey:@"aString"] == NULL)

Which one is right ?

A: valueForKey: (and most other Cocoa methods) returns a pointer (memory address) to an object. When you use the == symbol you're simply test the numeric value of that pointer and not the actual value of the string. When you use isEqualToString:, you are testing the value.
These two:
if ([dictionary valueForKey:@"aString"]==nil)
if ([dictionary valueForKey:@"aString"]==NULL)

are more-or-less equivalent and both test "Was the address returned equal to zero?", which is how valueForKey: indicates there was no object found for that key. If the dictionary does contain any object for that key, regardless of its value (e.g. Even an empty string) this if statement returns false.
(You normally use the nil version in Objective-C, as a styling convention as much as anything else)
This:
if ([[dictionary valueForKey:@"aString"] isEqualToString:@""])

Tests the actual value of the string to see if it's a zero length string. If there is no object in the dictionary, it will return false, since when you call isEqualToString: (or almost any other method) against a nil pointer you always get zero, or false.

A: nil is NULL's analog for objective-c objects. Actually they're the same:
 //MacTypes.h
 #define nil NULL

So
if ([dictionary valueForKey:@"aString"]==nil)
if ([dictionary valueForKey:@"aString"]==NULL)

both check if the specific key is present in a dictionary, although 1st line is more correct as it checks objective-c types.
About:
if ([[dictionary valueForKey:@"aString"] isEqualToString:@""])

This line checks if there's an entry in dictionary with "aString" key and compares that entry with empty string. The result will be one of the following:

*

*is false if there's no such entry for your key

*is true if there's entry for your key and that entry is empty string

*may crash if object for your key exists and does not respond to -isEqualToString: message

So depending on your needs you must use 1st line, or if you need to combine both checking if entry exists and it is not an empty string then you need 2 conditions:
if ([dictionary valueForKey:@"aString"]==nil ||
               [[dictionary valueForKey:@"aString"] isEqualToString:@""])

A: nil == (id) 0
Nil == (Class) 0
NULL == (void *) 0

@"" is an empty NSString constant.

A: nil is used to represent a null pointer to an Objective-C object.
Nil is used to represent a null pointer to an Objective-C class.
NULL is used to represent a null pointer to anything else.
All these, happen to have the numeric value of 0. They're all zero, but "NULL" is a void *, "nil" is an id, and "Nil" is a Class pointer.
@"" is used to denote an empty string, or say a string whose length is ZERO.

A: "The NSNull class defines a singleton object you use to represent null values in situations where nil is prohibited as a value (typically in a collection object such as an array or a dictionary)." You can use nil about anywhere you can use null. The main difference is that you can send messages to nil, so you can use it in some places where null cant work. In general, just use nil. that's exactly what's happening, the programmer is choosing to put a null object into the controllers array, where nil is not allowed as a value.
It is more a contextual reference where NULL is a pointer to 0x0, nil is a non-existent objective-c object and Nil is a non-existent objective-c class, but technically they are all just 0. Also, it is NULL not null -- null is in Java or C# but not in Objective-C
or ease  ways u say
They're all zero, but "NULL" is a void *, "nil" is an id, and "Nil" is a Class pointer.

A: Nil and NULL indicate the non-existence
@"" indicates the existence and it's empty


text:
Q: Protocol required error while installing magento 1.9 Please help me to solve below error I am getting while installing Magento 1.9 in my local system (I think I have added the right URL only), it is so ridiculous :(

A: To get rid of this error there possible 2 solutions in my mind.

1). Create virtual host for your magento.
2). Core hack !! Inspect on
this input field and than remove class base-secure-validate-url
class (Something like I ain't sure) .

Check Image Remove selected class and than go ahead.
Than execute setup wizard Ahead it will work.

A: I have faced the same error before few days while installation in my local,
Inspect that input and you will find it has class="required-entry validate-url input-text validation-failed" class.
Just remove "validate-url" class from your inspected input and click on continue.

This will solve your error.

A: Put http://127.0.0.1 instead of localhost and try


text:
Q: Jekyll multiversion documentation I'm using Jekyll for documentation website, and now I have to support multiple versions. The idea is very simple:
_posts/
    v1.0.0/
        page1.md
        page2.md
    v1.0.1/
        page1.md
        page2.md

In this case I want to see these pages at the final website:
https://URL/v1.0.0/page1/
https://URL/v1.0.0/page2/

https://URL/v1.0.1/page1/
https://URL/v1.0.1/page2/

And I do not want to add /v1.0.0/ in permalink: by myself: all .md-pages in subdirectory (for example, in v1.0.0) should contain name of this subdirectory as a prefix in the final URL.

A: Do not use the posts folder, use directories and pages directly.
v1.0.0/
   page1.md
   page2.md
 v1.0.1/
   page1.md
   page2.md

That would generate the desired output without using permalinks in front matter.


text:
Q: Angular does not encode the semi-colon character in an url We need an encoded semi-colon character in our url parameter but angular does not encode this character.
The resource we use looks something like this:
app.factory('TestResource', ['$resource', function ($resource) {
    return $resource('http://somedomain.com');
}]);

app.run(['TestResource', function (TestResource) {
    TestResource.query({
        q: 'sin;sout'
    });
}]);

This is the result we get:
http://somedomain.com/?q=sin;sout

We want the url to be:
http://somedomain.com/?q=sin%3Bsout

But if we pre-encode the parameter before sending the % char get's encoded like this:
http://somedomain.com/?q=sin%253Bsout

How can we get the desired result? (http://somedomain.com/?q=sin%3Bsout)

A: Angular uses its own function to encode the URL. And that function doesn't encode characters that usually don't need to be encoded like / or ?. ; is such a character, too. It's used in matrix URIs, e.g. So Angular's behavior actually conforms to the standard, but it could be a problem when such characters are used literally, i.e. without a special meaning. That seems to be the case here.
Since the URL is build just before sending the request, there's not much we can do. There is kind of a loophole though: Only parameters are encoded, not the base URL. So any workaround would involve creating the URL or at least a part of it yourself.
You could add an interceptor, that adds the properly encoded parameters to the URL before Angular does it. You could even completely replace Angular's behavior that way.
UPDATE:
Another solution came to my mind. The $http service delegates sending the actual request to the $httpBackend service which receives the already constructed URL. Using a decorator you can replace either the ; or the incorrectly encoded %253B with %3B right before the request is sent:
app.config(function($provide) {
  $provide.decorator('$httpBackend', function($delegate) {
    return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
      url = url.replace(';', '%3B');
      $delegate(method, url, post, callback, headers, timeout, withCredentials, responseType);
    };
  })
});

A: Building on zeroflagL's answer one could consider changing the replace to change all occurrences of the semi-colon (as it is written it will only replace the first semi-colon):
url = url.replace(/;/g, '%3B');

A: There is a closed issue for this https://github.com/angular/angular.js/issues/9224

path: Don't escape semicolons. Breaks matrix parameters, and no evidence that Angular's current behavior is problematic.
query: Escaping the entire query string would be unwise, as it breaks an established (albeit archaic) expectation for servers to be able to handle semicolon-delimited query strings.
query values: Probably safe to escape, especially if the server interprets semicolons as query delimiters. Passing complex data types (ie. JSON) via query parameters is a bad idea, but "real-world" string values often contain semicolons, and it seems like a good idea to escape them.

I'll go with zeroflagL's answer but only changing the query values. Like this:
$provide.decorator('$httpBackend', function($delegate) {
    return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
        var a = document.createElement('a');
        a.href = url;
        if(a.search.length > 1) {
            var params = a.search.substring(1).split('&');
            for (var i=0; i<params.length; i++) {
                var param = params[i].split('=');
                if(param[1]) {
                    params[i] = [param[0], param[1].replace(';', '%3B')].join('=');
                }
            }
            url = url.substring(0, url.lastIndexOf('?')) + '?' + params.join('&');
        }
        $delegate(method, url, post, callback, headers, timeout, withCredentials, responseType);
    };
});

A: You can use encodeURIComponent() method:
q: encodeURIComponent('sin;sout')


text:
Q: Showing that following is not a vector space? I have the following 8 axioms for a Vector Space and the following question.

I managed to prove that Axiom 3 doesn't work(and as a result Axiom 4 because 0 element doesn't exist) but the answer key also states that Axiom 6 doesn't work. I am having some trouble proving that. Can someone help ?

A: Take $\mathbf{x} = (1,1)$ and $\alpha = \beta = 1$, we have
$$(\alpha+\beta) \circ \mathbf{x} = (1+1) \circ (1,1) = 2\circ (1,1) = (2\cdot1,2\cdot1)=(2,2)$$
On the other hand. we have
$$\alpha \circ \mathbf{x} = 1 \circ (1,1) = (1\cdot1,1\cdot1)=  (1,1) = \beta \circ \mathbf{x}$$
$$\alpha \circ \mathbf{x} \oplus \beta \circ \mathbf{x}  = (1,1)\oplus(1,1) = (1+1,0)=(2,0)$$


text:
Q: (temporarily)using and learning ruby on rails without internet So I'm about to leave for africa for 2 weeks where i will for the most part not have an internet connection, during which i am going to start learning ruby on rails so that i can implement it in the social network i am going to start building when i get back. Im planning on saving the tutorials from rubyonrails.org to my computer before i go so that i can still use them but it seems like almost all of them are dependent on me being able to download files from the internet(for example won't "$ rails new blog" pull that info from the rails server?), does anyone know of a way i could use ruby (in particularly these tutorials) without the internet (like maybe i just need to pre-install a bunch of gems or something?)
I have basically no experience with rails so sorry if my interpretation of ruby and these tutorials is incorrect.

A: Theoretically, yes, practically, no.  Sure, you can fire up a local web server and write code, but you obviously don't want to write everything yourself, you want to take advantage of ruby's gem package system.  This will, obviously require an internet connection.


text:
Q: Magento 2 Workflow and Development Tools I am curious what other members of the community are using and suggest for M2 development:

*

*"What are some suggested Magento 2.X workflows?"

*"What tools/configurations/plugins are being used for Magento 2.X Development?"
This is subjective, but I would still like to solicit community feedback.
Thank you!

A: Integer_Net made a great article about Magento 2 frontend workflow, I suggest you check it out: https://www.integer-net.com/magento-2-frontend-workflow-step-by-step/
Basically the idea is:

*

*setup project's general structure

*setup Grunt environment

*create theme files

*start frontend workflow with Grunt

Regarding the useful tools, here are my suggestions based on my personal experience:

*

*PHPStorm IDE

*Magicento 2: http://magicento.com/

*Alan Storm's CommerceBug module: http://store.pulsestorm.net/products/commerce-bug-3

*MageRun 2: https://github.com/netz98/n98-magerun2

*xDebug

*modman: https://github.com/colinmollenhour/modman


text:
Q: Lifetime management of encapsulated objects What is the best approach to encapsulate objects and manage their lifetime? Example: I have a class A, that contains an object of type B and is solely responsible for it.
Solution 1, clone b object to ensure that only A is able to clean it up.
class A
{
    B *b;
public:
    A(B &b)
    {
        this->b = b.clone();
    }

    ~A()
    {
        delete b; // safe
    }
};

Solution 2, directly use the passed object, we risk a potential double free here.
class A
{
    B *b;
public:
    A(B *b)
    {
        this->b = b;
    }

    ~A()
    {
        delete b; // unsafe
    }
};

In my actual case, solution #2 would fit best. However I wonder if this is considered bad code because someone might not know about the behavior of A, even if it's documented. I can think of these scenarios:
B *myB = new B();
A *myA = new A(myB);
delete myB; // myA contains a wild pointer now

Or,
B *myB = new B();
A *firstA = new A(myB);
A *secondA = new A(myB); // bug! double assignment
delete firstA; // deletes myB, secondA contains a wild pointer now
delete secondA; // deletes myB again, double free

Can I just ignore these issues if I properly document the behavior of A? Is it enough to declare the responsibility and leave it up to the others to read the docs? How is this managed in your codebase?

A: I never delete anything myself unless I really have to.  That leads to errors.
Smart pointers are your friend.  std::auto_ptr<> is your friend when one object owns another and is responsible for deleting it when going out of scope.  boost::shared_ptr<> (or, now, std::tr1::shared_ptr<>) is your friend when there's potentially more than one object attached to another object, and you want the object deleted when there's no more references to it.
So, either use your solution 1 with auto_ptr, or your solution 2 with shared_ptr.

A: You should define your object so that the ownership semantics are, as much as possible, defined by the interface. As David Thornley pointed out, std::auto_ptr is the smart pointer of choice to indicate transfer of ownership. Define your class like so:
class A
{
    std::auto_ptr<B> b;
public:
    A(std::auto_ptr<B> b)
    {
        this->b = b;
    }
    // Don't need to define this for this scenario
    //~A()
    //{
    //   delete b; // safe
    //}
};

Since the contract of std::auto_ptr is that assignment = transfer of ownership, your constructor now states implicitly that an A object has ownership of the pointer to B it's passed. In fact, if a client tries to do something with a std::auto_ptr<B> that they used to construct an A after the construction, the operation will fail, as the pointer they hold will be invalid.

A: If you are writing code that someone else will be using later, these issues must be addressed. In this case I would go for simple reference counting (maybe with smart pointers). Consider the following example:
When an instance of the encapsulating class is assigned an object B, it calls a method to increase object's B reference counter. When the encapsulating class is destroyed, it doesn't delete B, but instead calls a method do decrease reference count. When the counter reaches zero, object B is destroyed (or destroys itself for that matter). This way multiple instances of encapsulating class can work with a single instance of object B.
More on the subject: Reference Counting.

A: If your object is solely responsible for the passed object then deleting it should be safe. If it is not safe than the assertion that you are solely responsible is false. So which is it? If you're interface is documented that you WILL delete the inbound object, then it is the caller responsibility to make sure you receive an object that must be deleted by you.

A: If you're cloning A, and both A1 and A2 retain references to B, then B's lifetime is not being controlled entirely by A. It's being shared among the various A. Cloning B ensures a one-to-one relationship between As and Bs, which will be easy to ensure lifetime consistency.
If cloning B is not an option, then you need to discard the concept that A is responsible for B's lifetime. Either another object will need to manage the various B, or you'll need to implement a method like reference counting.
For reference, when I think of the term 'Clone', it implies a deep copy, which would clone B as well. I'd expect the two As to be completely detached from each other after a clone.

A: I don't clone things unnecessarily or "just to be safe".
Instead I know whose responsibility it is to delete something: either via documentation, or by smart pointers ... for example, if I have a create function which instantiates something and returns a pointer to it and doesn't delete it, so that it's unclear where and by whome that thing is ever supposed to be deleted, then instead of create's returning a naked pointer I might define create's return type as returning the pointer contained within some kind of smart pointer.


text:
Q: MySQL issue: Table 'data_dictionary.CHARACTER_SETS' doesn't exist Recently I have updated from MySQL 5.1 to 5.5 and after few weeks the following error message was displayed each time I access the phpMyAdmin application:

1146 - Table 'data_dictionary.CHARACTER_SETS' doesn't exist

I have investigated the issue to the point where I have been forced to downgrade the MySQL service to 5.0.95 and  then to upgrade the service once again to 5.1.
None of the above outlines steps however resolved the issue and the error message in questions still persist . This error disables me to access any database/table via the phpMyAdmin interface.
The error logs on the server are not providing additional information at all. The checked logs were:
-> mysql.err log
-> the cpanel error log
Any help will be highly appreciated

A: Run sudo mysql_upgrade -u root -p --force
Then restart mysql
i.e. sudo service mysql restart or sudo service mysqld restart depending on the version and distribution you have
You need to logout of phpMyAdmin then login for the change to take effect.

A: I was facing the same problem. It can be resolved by reconfiguring phpMyAdmin.
 sudo dpkg-reconfigure phpmyadmin

Close phpMyAdmin page and


text:
Q: Prove that if $E(X\log X)<\infty$ then $E(\sup_n |S_n|/n)<\infty$. This is part 2 of a two part question. In the first part, we were asked to show that if you had a non-negative sub martingale $M_n$ then $$\sup_n E(\sup_{k\leq n} M_k)\leq \sup_n 2E(M_n \log M_n)+2$$
We need to use the above fact to Prove that if $E(X\log X)<\infty$ then $$E(\sup_n |S_n|/n)<\infty,$$ where $S_n=X_1+\dots+X_n$, with $X_i$ iid with distribution $X$.
I am unsure of how to introduce a sub-martingale into the problem since $S_n/n$ is not a martingale. Any help/hints would be appreciated.

A: Hints:

*

*Show that $(S_n/n)_{n \in \mathbb{N}}$ is a backwards martingale.

*Applying the first part to the (backwards) martingale gives a bound in terms of $$\mathbb{E}\left(\left| \frac{S_n}{n} \right| \cdot \left|\log\left( \frac{S_n}{n} \right) \right| \right).$$ In order to show that this expression is finite, use that $$[1,\infty) \ni x \mapsto x \log(x)$$ is a convex function and $$(0,1] \ni x \mapsto x \cdot \log(x)$$ is bounded.


text:
Q: JPA repository native SQL Query, using GROUP BY As a programming student, I'm discovering Java (11) & Springboot.
In the application I'm developing, I would like to have a top-sellers list.
It is clear to me how to collect this data in SQL - the query is working effectiv, but using the JPA Repositories & native query it isn't...
Why do I get the error to include the Id column in the "group by" part? If I do this, the result is offcourse not what I was looking for ...
@Query(value = "SELECT *, SUM(od.numberofproducts) AS sold, SUM(p.price * od.numberofproducts) AS revenue FROM OrderDetail od JOIN product p ON p.id = od.productid GROUP BY od.productid ORDER BY sold DESC limit 10", name = "getTopSellersList", nativeQuery=true)


text:
Q: Cloud Firestore Function returns only one document? I create a firebase function to return posts collection, for some reason cloud function return only one post(document). But when I run this function locally, in terminal I get all posts. Any idea why?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({origin: true});
admin.initializeApp();

exports.postWidget = functions.https.onRequest((request, response) => {
cors(request, response, () => {});

var db = admin.firestore();

var postsRef = db.collection('posts')
postsRef.where('postStatus', '==', 'published').get()
.then(snapshot => {
    snapshot.forEach(doc => {
        let data = doc.data()
        return response.send(data)
    });
})
.catch(err => {
    console.log('Error getting documents', err);
});

});

A: You're calling response.send(data) multiple times in forEach loop.  That's not likely to do what you want, as you're only supposed to call send() once with then entire response.  Instead, you should be collecting all the data to send in a single object, and call send() with that one object.


text:
Q: "message": "Call to undefined method Tymon\\JWTAuth\\Exceptions\\TokenInvalidException::getStatusCode() i have done it in two ways. When i directly pass Http status code it works but when i write $exception->getStatusCode(), i am getting error .I don't know whats wrong here.

The Second way is working fine but
what i want is ,it automatically generating the status code rather than being specific .

A: The reason is that most likely you are using v1.0.* and in this version, the exceptions extend JWTException which extends Exception. These have no implementation of getStatusCode() and therefore you cannot use them.
Tymon states in this link that there is no plan for implementing HTTP specific behavior on the exceptions.

A: Status Code will work only with http exception. In other types of exception you need to use getCode()
public function render($request, Exception $exception)
 {
   if ($exception instanceof \HttpException) {
     $statusCode = $exception->getStatusCode();
     return response()->json('status_code'=>$statusCode);
   }
 }