text:
Q: Undefined reference to klee when building s2e I'm trying to start a new prject and build s2e in a new directory. But at arounf the 100% mark, it gives me an undefined reference error. The relevant part (imo) is this:

[ 92%] Linking CXX executable ../ExprTest
../../lib/libkleeCore.a(Executor.cpp.o): In function `klee::Executor::setModule(llvm::Module*, klee::Interpreter::ModuleOptions const&, bool)':
~/s2e_projects/source/s2e/klee/include/klee/Internal/Module/KModule.h:189: undefined reference to `klee::KModule::KModule(llvm::Module*)'

My directory structure is such:
|-s2e-env
|-s2e_projects
|-venv

I followed the steps from here: http://s2e.systems/docs/s2e-env.html I followed all the steps upto s2e build which is where this problem occurs.
For reference, the (truncated) output which I got from doing s2e build &> log:
[ 88%] Built target kleeModule
make[3]: Entering directory '~/s2e_projects/build/klee-release'
make[3]: Entering directory '~/s2e_projects/build/klee-release'
make[3]: Entering directory '~/s2e_projects/build/klee-release'
make[3]: Leaving directory '~/s2e_projects/build/klee-release'
make[3]: Leaving directory '~/s2e_projects/build/klee-release'
make[3]: Leaving directory '~/s2e_projects/build/klee-release'
make[3]: Entering directory '~/s2e_projects/build/klee-release'
make[3]: Entering directory '~/s2e_projects/build/klee-release'
make[3]: Entering directory '~/s2e_projects/build/klee-release'
[ 91%] Linking CXX executable ../ADTTest
[ 91%] Linking CXX executable ../UtilsTest
[ 92%] Linking CXX executable ../ExprTest
../../lib/libkleeCore.a(Executor.cpp.o): In function `klee::Executor::setModule(llvm::Module*, klee::Interpreter::ModuleOptions const&, bool)':
~/s2e_projects/source/s2e/klee/include/klee/Internal/Module/KModule.h:189: undefined reference to `klee::KModule::KModule(llvm::Module*)'
../../lib/libkleeCore.a(Executor.cpp.o): In function `klee::Executor::setModule(llvm::Module*, klee::Interpreter::ModuleOptions const&, bool)':
~/s2e_projects/build/llvm-10.0.0.src/include/llvm/IR/DataLayout.h:393: undefined reference to `llvm::DataLayout::getPointerSize(unsigned int) const'
../../lib/libkleeCore.a(Executor.cpp.o): In function `klee::Executor::setModule(llvm::Module*, klee::Interpreter::ModuleOptions const&, bool)':
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:107: undefined reference to `klee::KModule::linkLibraries(klee::Interpreter::ModuleOptions const&)'
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:108: undefined reference to `klee::KModule::buildShadowStructures()'
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:110: undefined reference to `klee::KModule::prepare(klee::Interpreter::ModuleOptions const&, klee::InterpreterHandler*)'
../../lib/libkleeCore.a(Executor.cpp.o): In function `klee::Executor::initializeGlobalObject(klee::ExecutionState&, boost::intrusive_ptr<klee::ObjectState> const&, llvm::Constant const*, unsigned int)':
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:150: undefined reference to `llvm::ConstantDataSequential::getNumElements() const'
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:151: undefined reference to `llvm::ConstantDataSequential::getElementAsConstant(unsigned int) const'
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:153: undefined reference to `llvm::DataLayout::getStructLayout(llvm::StructType*) const'
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:158: undefined reference to `klee::KModule::evalConstant(std::unordered_map<llvm::GlobalValue const*, klee::ref<klee::ConstantExpr>, std::hash<llvm::GlobalValue const*>, std::equal_to<llvm::GlobalValue const*>, std::allocator<std::pair<llvm::GlobalValue const* const, klee::ref<klee::ConstantExpr> > > > const&, llvm::Constant const*, klee::KInstruction const*)'
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:163: undefined reference to `klee::ConstantExpr::ZExt(unsigned int)'
../../lib/libkleeCore.a(Executor.cpp.o): In function `klee::Executor::initializeGlobals(klee::ExecutionState&)':
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:200: undefined reference to `llvm::Value::getName() const'
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:241: undefined reference to `llvm::Value::getName() const'
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:247: undefined reference to `llvm::GlobalValue::isDeclaration() const'
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:258: undefined reference to `llvm::Value::getName() const'
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:260: undefined reference to `llvm::Value::getName() const'
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:262: undefined reference to `llvm::Value::getName() const'
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:268: undefined reference to `llvm::Value::getName() const'
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:281: undefined reference to `llvm::Value::getName() const'
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:306: undefined reference to `klee::KModule::evalConstant(std::unordered_map<llvm::GlobalValue const*, klee::ref<klee::ConstantExpr>, std::hash<llvm::GlobalValue const*>, std::equal_to<llvm::GlobalValue const*>, std::allocator<std::pair<llvm::GlobalValue const* const, klee::ref<klee::ConstantExpr> > > > const&, llvm::Constant const*, klee::KInstruction const*)'
~/s2e_projects/source/s2e/klee/lib/Core/Executor.cpp:311: undefined reference to `llvm::Value::getName() const'
../../lib/libkleeCore.a(Executor.cpp.o): In function `klee::Executor::initializeGlobals(klee::ExecutionState&)':
~/s2e_projects/build/llvm-10.0.0.src/include/llvm/IR/GlobalVariable.h:92: undefined reference to `llvm::GlobalValue::isDeclaration() const'
../../lib/libkleeCore.a(Executor.cpp.o): In function `klee::Executor::initializeGlobals(klee::ExecutionState&)':

...

A: I had the exact same error and solved it with:
sudo apt install gcc-9 g++-9

Also check to make sure clang selects the installed gcc-9 toolchain:
$ PATH_TO_S2E/install/bin/clang++ -v
...
Selected GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/9
...

As for why a compatible gcc toolchain is needed, even though clang is used to compile S2E:
Why clang selects a gcc installation?


text:
Q: Is $\mathbb R^2$ equipotent to $\mathbb R$? I know that $\mathbb N^2$ is equipotent to $\mathbb N$ (By drawing zig-zag path to join all the points on xy-plane). Is this method available to prove $\mathbb R^2 $ equipotent to $\mathbb R$?

A: That method is not available to prove the equipotency of $\mathbb R$ and $\mathbb R^2$. The geometry is different. When the zigzag finishes a diagonal line in $\mathbb Z^2$, it can move over and do the next diagonal line.  But in $\mathbb R^2$ there is no "next" line.
In fact it turns out that there is no continuous bijection between $\mathbb R$ and $\mathbb R^2$.
For ideas that do work, see Examples of bijective map from $\mathbb{R}^3\rightarrow \mathbb{R}$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django: ValueError: Prefetch querysets cannot use raw(), values(), and values_list() I am trying to run prefetch as below and gives me error: Prefetch querysets cannot use raw(), values(), and values_list().
queryset = SymbolList.objects.prefetch_related(
            Prefetch('stock_dailypricehistory_symbol',queryset = DailyPriceHistory.objects.filter(id__in=[1,2,3,4]).values('close','volume'))).all()

DailyPriceHistory model has lot of columns, i only want close and volume
Here id__in=[1,2,3,4] is just shown for example, it can go upto 10000+ ids at a time.

A: You can indeed not make use of .values(…) [Django-doc] and .values_list(…) [Django-doc] when prefetching. That would also result in extra complications, since then Django has more trouble to find out how to perform the "joining" at the Django/Python level, if this is even possible.
You however do not need to use .values(…) to limit the number of columns you fetch, you can use .only(…) [Django-doc] instead. .only(…) will only fetch the given columns and the primary key immediately in memory, and will "postpone" fetching other columns. Only if you later need these columns, it will make extra queries. This is thus a bit similar how Django will only fetch the related object of a ForeignKey in memory when you need it with an extra query.
queryset = SymbolList.objects.prefetch_related(
    Prefetch(
        'stock_dailypricehistory_symbol',
        queryset = DailyPriceHistory.objects.filter(
            id__in=[1,2,3,4]
        ).only('close', 'volume', 'symbol_id')
    )
)
The symbol_id is the column of the ForeignKey that refers from the DailyPriceHistory to the SymbolList model, this might be a different field than symbol_id. If you do not include this, Django will have to make extra queries to find out how it can link DailyPriceHistory to the corresponding SymbolList, and this will only slow down processing with extra queries, therefore you better include this as well.


text:
Q: Variables and parameters with methods I am doing a practice exercise because I really need to improve my java rapidly. The application is for a pizza ordering program and I need to keep most of the user input in variables until the end but they are returning as null and 0. I am clearly doing something wrong can someone enlighten me I learn best from my own code and reading others examples can be confusing for me.I need the variables from the methods that get the pizza size, pizza crust and toppings etc to display in the receipt method
import java.util.Scanner;

public class test {
    ;
    public static final double TEN_INCH_PRICE=10.99;
    public static final double TWELVE_INCH_PRICE=12.99;
    public static final double FOURTEEN_INCH_PRICE=14.99;
    public static final double SIXTEEN_INCH_PRICE=16.99;
    public static final double TOPPING_COST=1.25;

    public static void main(String[] args) {
        int pizzaChoice = 0;
        String pizzaSize = null;
        int crustChoice;
        int toppingChoice;
        String crustWanted = null;
        String toppingWanted = null;
        String customerName;
        double pizzaPrice = 0;

        displayWelcome();
        pizzaSize(pizzaSize);
        pizzaCrust(crustWanted);
        toppingChoice(toppingWanted);
        pizzaCost(pizzaChoice, pizzaPrice);
        receipt(pizzaSize, crustWanted, toppingWanted,pizzaPrice);
    }

    /**
     * Display Welcome Message
     * */
    public static void displayWelcome() {

        System.out.println("******************************************");
        System.out.println("* CIT Pizza *");
        System.out.println("******************************************");

    }

    public static String getname() {

        return null;

    }

    public static String pizzaSize(String pizzaSize){
        System.out.println("Pizza Size (inches) Cost");
        System.out.println("=================== ====");
        System.out.println("10                  10.99");
        System.out.println("12                  12.99");
        System.out.println("14                  14.99");
        System.out.println("16                  16.99 ");
        String message = "Please enter the size of pizza you want";
        int pizzaChoice=readValidPizzaSize(message); //Get pizza size choice
        if (pizzaChoice==10)
            pizzaSize="10 inch pizza";

        if (pizzaChoice==12)
            pizzaSize="12 inch pizza";

        if (pizzaChoice==14)
            pizzaSize="14 inch pizza ";

        if (pizzaChoice==16)
            pizzaSize="16 inch pizza";

        return pizzaSize;

    }

    public static String pizzaCrust(String crustWanted){
        System.out.println("Pizza Crust Choice");
        System.out.println("==================");
        System.out.println("All crusts cost the same price.");
        System.out.println("1 - Hand-tossed");
        System.out.println("2 - Thin-crust");
        System.out.println("3 - Deep-dish");
        String message = ("Please enter crust choice");
        int crustChoice=readValidCrustChoice(message);
        if (crustChoice==1)
            crustWanted="Hand-Tossed";

        if (crustChoice==2)
            crustWanted="Thin-crust";

        if (crustChoice==3)
            crustWanted="Deep-dish";

        return crustWanted;

    }

    public static String toppingChoice(String toppingWanted){
        System.out.println("Pizza Topping Choice");
        System.out.println("====================");
        System.out.println("All pizzas come with cheese and tomato sauce.");
        System.out.println("An additional topping costs €1.25.");
        System.out.println("Choose from:");
        System.out.println("1 - Pepperoni");
        System.out.println("2 - Sausage");
        System.out.println("3 - Onion");
        System.out.println("4 - None");
        String message = ("Please enter topping choice");
        int toppingChoice=readValidToppingChoice(message);
        if (toppingChoice==1)
            toppingWanted="Pepperoni";

        if (toppingChoice==2)
            toppingWanted="Sausage";

        if (toppingChoice==3)
            toppingWanted="Onion";

        if (toppingChoice==4)
            toppingWanted="None";

        return toppingWanted;
    }

    public static double pizzaCost(int pizzaChoice, double pizzaPrice){
        if (pizzaChoice==10)
            pizzaPrice=TEN_INCH_PRICE;

        if (pizzaChoice==12)
            pizzaPrice=TWELVE_INCH_PRICE;

        if (pizzaChoice==14)
            pizzaPrice=FOURTEEN_INCH_PRICE;

        if (pizzaChoice==16)
            pizzaPrice=SIXTEEN_INCH_PRICE;

        return pizzaPrice;

    }

    public static void receipt(String pizzaSize, String crustWanted, String toppingWanted,double pizzaPrice){
        System.out.println("Order Details");
        System.out.println("=============");
        System.out.println("your order is as follows:");
        System.out.println(pizzaSize);
        System.out.println(crustWanted);
        System.out.println("Cheese,Tomato sauce,"+ " "+toppingWanted);
        System.out.println("The cost of your order is:"+ " "+pizzaPrice);

    }
    public static int readInt(String prompt)
    {
        // Create a scanner object for input from the console window
        Scanner keyboard = new Scanner(System.in);

        // boolean flag which is used to control the
        // data validation loop

        boolean numGood = false; // Assume the worst
        do
        {
            System.out.print(prompt);  // ask for the value
            if(!keyboard.hasNextInt()) // check if what's in the keyboard buffer is not a double
            {
                System.out.println("You must enter an  value!"); // display an error message
                keyboard.nextLine(); // consume the bad value entered
            }
            else
                numGood = true; // value entered is good
        } while(!numGood);
        // at this point we know the value in the
        // keyboard buffer is numeric so we can go ahead and
        // return it.
        return keyboard.nextInt();
    }
    /**
     * The readValidPizzaSize method reads an applicable pizza size
     * from the console window and will display an appropriate
     * error message if a non-applicable int value is entered.
     * @param prompt A prompt to request the user to enter a pizza size
     * @return The applicable int value entered.
     */
    public static int readValidPizzaSize(String prompt)
    {
        int value;
        do
        {
            value = readInt(prompt); // ask for and read an double value
            if (value !=10 && value !=12 && value!=14 && value!=16) // check if the value entered is applicable
                // display an error message
                System.out.println("Error - you must enter a valid pizza size");
        } while (value !=10 && value !=12 && value!=14 && value!=16);
        // at this point we know the value entered is positive
        // so return it
        return value;
    }

    public static int readValidCrustChoice(String prompt)
    {
        int value;
        do
        {
            value = readInt(prompt); // ask for and read an double value
            if (value !=1 && value !=2 && value!=3) // check if the value entered is applicable
                // display an error message
                System.out.println("Error - you must enter a valid crust choice");
        } while (value !=1 && value !=2 && value!=3);
        // at this point we know the value entered is positive
        // so return it
        return value;
    }
    public static int readValidToppingChoice(String prompt)
    {
        int value;
        do
        {
            value = readInt(prompt); // ask for and read an double value
            if (value !=1 && value !=2 && value!=3 &&value!=4) // check if the value entered is applicable
                // display an error message
                System.out.println("Error - you must enter a valid topping choice");
        } while (value !=1 && value !=2 && value!=3 && value!=4);
        // at this point we know the value entered is positive
        // so return it
        return value;
    }
}

A: Just change your main method to:
public static void main(String[] args) {
    int pizzaChoice = 0;
    String pizzaSize = null;
    int crustChoice;
    int toppingChoice;
    String crustWanted = null;
    String toppingWanted = null;
    String customerName;
    double pizzaPrice = 0;

    displayWelcome();
    pizzaSize = pizzaSize(pizzaSize);
    pizzaChoice = Integer.parseInt(pizzaSize.replaceAll("[^0-9]", ""));
    crustWanted = pizzaCrust(crustWanted);
    toppingWanted = toppingChoice(toppingWanted);
    pizzaPrice = pizzaCost(pizzaChoice, pizzaPrice);
    receipt(pizzaSize, crustWanted, toppingWanted,pizzaPrice);
}

The problem is that whenever you assign a new text to a String, you're actually creating a new String object in Java. In addition, Java's pass-by-reference, passes a copy of the reference. As a result, you're assigning a new object to a copy of the reference; hence,  your original String is not affected. You might wanna study how objects and primitive types are passed in Java.


text:
Q: What are strategies for bridging Google Cloud with AWS? Let's say a company has an application with a database hosted on AWS and also has a read replica on AWS. Then that same company wants to build out a data analytics infrastructure in Google Cloud -- to take advantage of data analysis and ML services in Google Cloud.
Is it necessary to create an additional read replica within the Google Cloud context? If not, is there an alternative strategy that is frequently used in this context to bridge the two cloud services?

A: While services like Amazon Relational Database Service (RDS) provides read-replica capabilities, it is only between managed database instances on AWS.
If you are replicating a database between providers, then you are probably running the database yourself on virtual machines rather than using a managed service. This means the databases appear just like any resource on the Internet, so you can connect them exactly the way you would connect two resources across the internet. However, you would be responsible for managing, monitoring, deploying, etc. This takes away from much of the benefit of using cloud services.
Replicating between storage services like Amazon S3 would be easier since it is just raw data rather than a running database. Also, Big Data is normally stored in raw format rather than being loaded into a database.
If the existing infrastructure is on a cloud provider, then try to perform the remaining activities on the same cloud provider.


text:
Q: Prove/Disprove $f(x) = x + \frac{x}{{x + 1}}$ is uniformly continuous at $\forall x,y \in [0,\infty )$ Prove/Disprove $f(x) = x + \frac{x}{{x + 1}}$ is uniformly continuous at $\forall x,y \in [0,\infty )$
This is my trial:
$$\forall \varepsilon  > 0\exists \delta  > 0.\forall x,y \in [0,\infty ):$$
Let $$\left| {x - y} \right| < \delta $$
$$\left| {x + \frac{x}{{x + 1}} - y - \frac{y}{{y + 1}}} \right|... \le \delta  + \frac{\delta }{{(x + 1)(y + 1)}}$$
As you can see after some algebra I got an expreesion with denominator involving $x,y$.
I need to "get rid" of $x,y$ at the denominator.
One way doing it is just multiplying by $(x+1)(y+1)$, because then I left with just $2\delta$ which is great. what do you think? Am I doing it right?

A: Yes, you're doing it right.  $x$ and $y$ are nonnegative so $(x+1)(y+1)\geq 1$, and
$$ \delta + \frac{\delta}{(x+1)(y+1)} \leq 2\delta. $$
So for any $\epsilon>0$, let $\delta = \epsilon/2$, etc., etc.
This is basically julien's comment.

A: It would be a better choice to estimate derivative first :
$f(x)=x+\frac{x}{x+1}\Rightarrow f'(x)=1+\frac{1}{(x+1)^2}$
check what values would $f'(x)$ takes on $[0,\infty)$
Suppose $|f'(x)|\leq M$..... You can now use definition of derivative :
$|f'(x)|=\lim_{y\rightarrow x}\frac{|f(x)-f(y)|}{|x-y|}$
So, once you know this fellow is bounded by $M$ (If it actually is)
Then, with slight modifications you would end up with something like :
$|f(x)-f(y)|\leq M |x-y|$ for all $x,y\in [0,\infty)$ which would imply uniform continuity... (Why?)
On a serious note, Boundedness of derivative is only to guess what $\delta$ could be for given $\epsilon$.
It may not be good to go for derivative all the time..
Good luck!


text:
Q: Score/points update in beginner python turtle game I'm a newbie to python and I'm having a problem with the score in my turtle game. The score is updated the first time I collect the ball, but it does not update when I collect the ball on any subsequent occasion. I would like the score to increase by a number e.g. 2 every time a ball is collected.
Might someone be able to offer a solution?
I suspect the issue could lie in:

*

*the scope of the variable 'score

*the improper looping of any/some function

import turtle
import random
import math

screen = turtle.Screen()
screen.title("My game by python code")
screen.bgcolor("black")
screen.setup(width=600, height=600)

# Making the user 'bubble'
bubble = turtle.Turtle()
bubble.color("red")
bubble.shape("circle")
bubble.penup()
speed = 3

# Making the collection balls
collection_ball = turtle.Turtle()
collection_ball.color("red")
collection_ball.penup()
collection_ball.shape("circle")
collection_ball.shapesize(0.5, 0.5, 0.5)
ball_cor1 = random.randint(30, 280)
ball_cor2 = random.randint(30, 280)
collection_ball.setposition(ball_cor1, ball_cor2)
collection_ball.color("yellow")

# Scoring
points = turtle.Turtle()
points.color("yellow")
style = ('Courier', 30, 'italic')
points.penup()
points.goto(-200, 250)
points.write("Points: 0", font=style)
points.hideturtle()

# Turning
def turn_left():
    bubble.left(90)

def turn_right():
    bubble.right(90)

# Collection of the balls
def collection(a, b):
    return abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 20

def collection_ball_restart():
    collection_ball.color("black")
    ball_cor1 = random.randint(30, 280)
    ball_cor2 = random.randint(30, 280)
    collection_ball.goto(ball_cor1, ball_cor2)
    collection_ball.color("yellow")
    bubble.forward(speed)
    screen.ontimer(play_game, 10)

def play_game():
    if collection(bubble, collection_ball):
        score = 0
        score += 2
        points.clear()
        points.write("Points: " + str(score), font=style)
        collection_ball_restart()
        bubble.forward(speed)

    else:
        bubble.forward(speed)
        screen.ontimer(play_game, 10)

turtle.onkeypress(turn_left, "Left")
turtle.onkeypress(turn_right, "Right")

screen.listen()

play_game()

screen.mainloop()

A: In addition to the score initialization issue that @TimRoberts points out (+1), below is a rework of your code to simplify the logic:
from turtle import Screen, Turtle
from random import randint

FONT_STYLE = ('Courier', 30, 'italic')

screen = Screen()
screen.title("My game by python code")
screen.bgcolor('black')
screen.setup(width=600, height=600)

# Making the user 'bubble'
bubble = Turtle()
bubble.color('red')
bubble.shape('circle')
bubble.penup()

# Making the collection balls
collection_ball = Turtle()
collection_ball.color('yellow')
collection_ball.shape('circle')
collection_ball.shapesize(0.5)
collection_ball.penup()
ball_cor1 = randint(30, 280)
ball_cor2 = randint(30, 280)
collection_ball.setposition(ball_cor1, ball_cor2)

# Scoring
score = 0
speed = 3

points = Turtle()
points.hideturtle()
points.color('yellow')
points.penup()
points.goto(-200, 250)
points.write("Points: 0", font=FONT_STYLE)

# Turning
def turn_left():
    bubble.left(90)

def turn_right():
    bubble.right(90)

# Collection of the balls
def was_collected(bubble):
    return bubble.distance(collection_ball) < 15

def collection_ball_reset():
    collection_ball.hideturtle()
    collection_ball.goto(randint(30, 280), randint(30, 280))
    collection_ball.showturtle()

def play_game():
    global score

    if was_collected(bubble):
        score += 2
        points.clear()
        points.write("Points: " + str(score), font=FONT_STYLE)
        collection_ball_reset()

    bubble.forward(speed)
    screen.ontimer(play_game, 10)

screen.onkeypress(turn_left, 'Left')
screen.onkeypress(turn_right, 'Right')
screen.listen()

play_game()

screen.mainloop()

E.g. use hideturtle() and showturtle() instead of color tricks; minimize necessary calls to ontimer(); use built-in distance function.


text:
Q: Python: Importing everything from a python namespace / package all.
I'd think that this could be answered easily, but it isn't. As long as I've been searching for an answer, I keep thinking that I'm overlooking something simple.
I have a python workspace with the following package structure:
    MyTestProject
        /src
           /TestProjectNamespace
              __init__.py
              Module_A.py
              Module_B.py

    SecondTestProject
        /src
           /SecondTestProjectNamespace
              __init__.py
              Module_1.py
              Module_2.py
              ...
              Module_10.py

Note that MyTestProjectNamespace has a reference to SecondTestProjectNamespace.
In MyTestProjectNamespace, I need to import everything in SecondTestProjectNamespace. I could import one module at a time with the following statement(s):
    from SecondTestProjectNamespace.Module_A import *
    from SecondTestProjectNamespace.Module_B import *

...but this isn't practical if the SecondTestProject has 50 modules in it.
Does Python support a way to import everything in a namespace / package? Any help would be appreciated.
Thanks in advance.

A: No.  It is possible to set up SecondTestProject to automatically import everything in its submodules, by putting code in __init__.py to do the from ... import * you mention.  It's also possible to automate this to some extent using the __import__ function and/or the imp module.  But there is no quick and easy way to take a package that isn't set up this way and make it work this way.
It's probably not a good idea anyway.  If you have 50 modules, importing everything from all of them into your global namespace is going to cause a proliferation of names, and very likely conflicts among those names.

A: Yes, you can roll this using pkgutil.
Here's an example that lists all packages under twisted (except tests), and imports them:
# -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4

import pkgutil
import twisted

for importer, modname, ispkg in pkgutil.walk_packages(
    path=twisted.__path__,
    prefix=twisted.__name__+'.',
    onerror=lambda x: None):
        # skip tests
        if modname.find('test') > -1:
            continue
        print(modname)
        # gloss over import errors
        try:
            __import__(modname)
        except:
            print 'Failed importing', modname
            pass

# show that we actually imported all these, by showing one subpackage is imported
print twisted.python

I have to agree with the other posters that star imports are a bad idea.

A: As other had put it - it might not be a good idea. But there are ways of keeping your namespaces and therefore avoiding naming conflicts - and having all the modules/sub-packages in a module available to the package user with a single import.
Let's suppose I have a package named "pack", within it a module named "a.py" defining some "b" variable. All I want to do is :
>>> import pack
>>> pack.a.b
1

One way of doing this is to put in pack/__init__.py a line that says
import a - thus in your case you'd need fifty such lines, and keep them up to date.
Not that bad.
However, the documentation at http://docs.python.org/tutorial/modules.html#importing-from-a-package  - says that if you have a string list named __all__ in your __init__.py file, all module/sub-package names in that list are imported when one does from pack import *
That alone would half-work - but would require users of your package to perform the not-recommended "from x import *" form.
But -- you can do the "... import *" inside __init__.py itself, after defining the __all__ variable - so all you have to do is to keep the __all__ up to date:
With the TestProjectNamespace/__init__.py being like this:
__all__ = ["Module_A", "Module_B", ...]
from TestProjectNamespace import *

your users would have
TestProjectNamespace.Module_A (and others) available upon import of TestProjectNamespace.
And, of course - you could automate the creation of __all__ - it is just a variable, after all - but I would not recommend that.

A:
Does Python support a way to import everything in a namespace / package?

No. A package is not a super-module -- it's a collection of modules grouped together.

At least part of the reason is that it's not trivial to determine what 'everything' means inside a folder: there are problems like network drives, soft links, hard links, ...


text:
Q: PyWin32: Windows Classic theme In the PyWin32 demos folder, the win32gui_dialog.py sample uses the classic windows  controls.
Can the Windows Vista themed buttons also be displayed using PyWin32, and if so, how? I'm using ActivePython 3.1, if that makes any difference.
Sample:
PyWin32 http://imagespark.net/files/old.png

A: Short answer: a resounding YES.
I know that this is possible because I have seen it being done before. but I am not entirely certain as to how it is done.
At the very least, you can use IronPython and use Windows' builtin .NET framework by wielding clr.
If you are not interested in IronPython, then might you consider something along the lines of easyGUI or TkInter?

A: You'll need to add a side-by-side manifest specifying a correct version of ComCtl32.dll to the Python interpreter. Fortunately there is no need to change the interpreter executable itself.

*

*Create a file named python.exe.manifest in the directory containing python.exe.

*Put the following contents in that file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly
   xmlns="urn:schemas-microsoft-com:asm.v1"
   manifestVersion="1.0">
 <assemblyIdentity
    processorArchitecture="x86"
    version="5.1.0.0"
    type="win32"
    name="python.exe"/>
 <description>Python</description>
 <dependency>
  <dependentAssembly>
    <assemblyIdentity
         type="win32"
         name="Microsoft.Windows.Common-Controls"
         version="6.0.0.0"
         publicKeyToken="6595b64144ccf1df"
         language="*"
         processorArchitecture="x86"/>
  </dependentAssembly>
 </dependency>
</assembly>

You may want to copy python.exe.manifest to pythonw.exe.manifest too.

A: Have you tried using 'winxpgui' module instead of 'win32gui' module?
I'm not sure if there's a 'winvistagui' or 'win7gui' module, but 'winxpgui' does exist and may work, as it has a manifest included.


text:
Q: Why Ionic 4 doesnt support nativeURL file:// I'm trying to get the video properties from my phone storage with import { File } from '@ionic-native/file/ngx'; then its getting an error after im trying to display the nativeURL in the HTML.. Not Allowed to load local resource: file:///storage/emulated/0/..
nativeURL image from File plugins
I have tried to downgrade the webview into @1.2.1 and end up with white screen problem. then I remove the webview into the latest one back.
TS:
import { File } from '@ionic-native/file/ngx';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer/ngx';
...

constructor(
    ....
  private transfer: FileTransfer,
  private file: File,
) { }

selectVideo() {
    const options: CameraOptions = {
      mediaType: this.camera.MediaType.VIDEO,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
    }

    this.camera.getPicture(options)
      .then( async (videoUrl) => {
        if (videoUrl) {
          console.log("Here");
          this.uploadedVideo = null;

          var filename = videoUrl.substr(videoUrl.lastIndexOf('/') + 1);
          var dirpath = videoUrl.substr(0, videoUrl.lastIndexOf('/') + 1);
          console.log('dir', dirpath);
          dirpath = dirpath.includes("file://") ? dirpath : "file://" + dirpath;
          //http://localhost/_app_file_/storage/emulated/0/
          // dirpath = this.win.Ionic.WebView.convertFileSrc(dirpath);
          console.log('new dirpath', dirpath);
          try {

            var dirUrl = await this.file.resolveDirectoryUrl(dirpath);
            var retrievedFile = await this.file.getFile(dirUrl, filename, {});
            console.log(dirUrl);
            console.log(retrievedFile);
          } catch(err) {

            console.log("Error Something went wrong.");
          }

          retrievedFile.file( data => {

              // this.dismissLoader();
              if (data.size > MAX_FILE_SIZE) return console.log("You cannot upload more than 5mb.");
              if (data.type !== ALLOWED_MIME_TYPE) return console.log("Incorrect file type.");

              this.selectedVideo = retrievedFile.nativeURL;
          });
        }
      },
      (err) => {
        console.log(err);
      });
  }

HTML:

  <video controls [src]="selectedVideo"></video>

    <button ion-button clear (click)="cancelSelection()">
      <ion-icon name="close-circle" color="danger"></ion-icon>
    </button>
    <button ion-button clear (click)="uploadVideo()">
      <ion-icon name="checkmark-circle" color="secondary"></ion-icon>
    </button>

        <ion-spinner name="bubbles"></ion-spinner>

Uploading - {{ uploadPercent }}% Complete

      <button ion-button clear (click)="cancelUpload()">
        <ion-icon name="close-circle" color="danger"></ion-icon>
      </button>

    <button ion-button clear (click)="cancelSelection()">
    Start Over
    </button>

I want to load the video into HTML view. from these properties (nativeURL)

A: Ionic don't support it because it make CORS errors.
You can buypass this problem with with this:
import { WebView } from "@ionic-native/ionic-webview";
[your code]
WebView.convertFileSrc(pathToFile);

A: To display the video inside the video HTML element, you need to get the file properties using Cordova plugins.
Below is working code to get the file in an Android device, and display the read source then render the blob into the DOM. The selected file will be read and put it into a Blob. then you can do whatever you want, like to send it to the API endpoints, or just display the video inside the DOM.
TS:
import { Component, ElementRef } from '@angular/core';
import { FileChooser } from '@ionic-native/file-chooser/ngx';
import { FilePath } from '@ionic-native/file-path/ngx';
import { File } from '@ionic-native/file/ngx';
...

selectedVideo: any;

constructor(
    private fileChooser: FileChooser,
    private filePath: FilePath,
    private file: File,
    private elementRef: ElementRef,
  ) {

}

getFileData(): Promise<any> {
    return this.fileChooser.open().then(fileURI => {
      return this.filePath.resolveNativePath(fileURI).then(_ => {
        return this.file.resolveLocalFilesystemUrl(fileURI).then((fileEntry: any) => {
          return new Promise((resolve, reject) => {
            fileEntry.file(
              (file) => {
                console.log('meta', file);
                let reader = new FileReader();
                reader.onload = () => {
                  console.log('Loaded: ', reader.result);
                  const blobFile = new Blob([reader.result], { type: file.type });
                  resolve(
                    blobFile
                  );
                };
                reader.onerror = error => {
                  console.log('Error: ', error);
                  reject(
                    error
                  );
                };
                reader.onabort = () => {
                  console.log('Aborted');
                };
                reader.readAsArrayBuffer(file);

                // this.file.resolveLocalFilesystemUrl(file['localURL']).then((entry: any) => {
                //   var nativePath = entry.toURL();
                //   console.log('Native URI: ' + nativePath);

                // });
              }, error => {
                console.log(error);
              }
            );
          });
        });
      });
    });
}

async selectAFile() {
    this.getFileData().then(async blobFile => {
      console.log(blobFile);
      this.selectedVideo = true;
      let video = this.elementRef.nativeElement.querySelector("#video");
      video.src = window.URL.createObjectURL(blobFile);

    }).catch(error => {
      // Something wrong with getting file infomation
      console.log(error);
      this.selectedVideo = false;
    });
}

HTML:
<ion-content>

Please select a video for upload from your gallery

    <ion-button (click)="selectAFile()">Select Video</ion-button>

  <video *ngIf="selectedVideo" id="video" controls autoplay></video>
</ion-content>


text:
Q: Android and Kotlin varargs: formatted strings returns garbage I'm encountering a strange problem: I've a general function which is used to retrieve resource strings (it's just to avoid writing context.resources.getString() everytime):
protected fun string(@StringRes stringRes: Int, vararg args: String): String = app.getString(stringRes, args)

worked fine up until now, when I added the varargs to retrieve formatted strings. Simple strings still work fine but when I tried to retrieve a formatted one:
string(R.string.formatted_string, myId)

my string resource:
<string name="formatted_string">#%s</string>

I get some garbage:
#[Ljava.lang.String;@3a59711

expected:
#4848684

the garbage change with the resource I request
It looks a Object identifier.
If I don't use the method it works fine
What is happening here?

A: The solution for you is to use the spread operator *:
fun string(@StringRes stringRes: Int, vararg args: String): String = getString(stringRes, *args)

Variable number of arguments (Varargs)


text:
Q: variable $it in Gradle task : Reference : Gradle in Action book Whilke going through the book I came across this line

Groovy automatically exposes an implicit variable named it to indicate
  the loop iteration index.

from the Gradle in Action book, chapter 2 Listing 2.1
The line says that $it represents loop iteration index. However when I try add
 $it to println statement of task yayGradle0/1/2, it prints out the task and not the index. I'm confused about this behavior. Please guide.
3.times{
    task "yayGradle$it" <<{
        println 'Gradle rocks--->>>'+"$it"
    }
}

The output after running task yayGradle0 is :
Gradle rocks--->>>task ':yayGradle0'

A: (edit after rereading)
it is the  index in loop.
From groovy shell
  3.times  {
    println "${it}"
  }

0
1
2

In your code there is another closure, it becomes variable to that closure (which is task name)
Following example uses explicit variable at top level.
3.times{ counter->
    task "hello${counter}" <<{
        println 'Gradle rocks--->>>'+" ${it}  ${counter}"
    }
}

$gradle hello2 gets following output.

Task :hello2
  Gradle rocks--->>> task ':hello2'  2

references
novice
groovy closures

A: You are using the it variable in a different context than presented in the book. In your case you are working in the context of the task's Closure. Therefore, it represents a different object, a org.gradle.api.Task instance. It would be helpful to reference Closure delegation strategies. Please also see Appendix B in the book.


text:
Q: YouTube iframe inside another iframe doesn't work fullscreen I am using YouTube iframe inside another iframe which looks like the snippet below. The problem is, I cannot use fullscreen feature for the video even though I have enabled the attributes required.
if the video doesn't work in the snippet, I have created a fiddle here.
https://jsfiddle.net/moviecrew/uwhg6452/

<iframe class="uvembed114199" frameborder="0" src="https://app.upviral.com/embed/lead/call/ajax/camp/114199/cid/lp114199//widget/iframe/k/0" style="width: 100%; height: 1254px;" allowfullscreen="allowfullscreen"></iframe>

A: added allowfullscreen="allowfullscreen"  to the outside iframe as well and it solved the problem.


text:
Q: Is the NSBluetoothAlwaysUsageDescription error message on MacOS a bug? I am developing an app on MacOS that uses the CoreBluetooth framework.
I have added the NSBluetoothAlwaysUsageDescription key and the description to the Info.plist file as required.
<key>NSBluetoothAlwaysUsageDescription</key>
<string>Use bluetooth to find devices</string>

However the app still crashes with the following message:
This app has crashed because it attempted to access privacy-sensitive data without a usage description.  The app's **Info.plist** must contain an NSBluetoothAlwaysUsageDescription key with a string value explaining to the user how the app uses this data.

I have tried this in iOS and it is not an issue. In iOS I automatically get a dialog requesting the use Bluetooth and when it is accepted the app works. But the MacOS version of the app never throws the dialog requesting use of Bluetooth and just crashes with the above message shown in Xcode.
Is this a bug or are there extra steps required to request Bluetooth usage?


text:
Q: Comparing 3D surface plots in R obtained with plot_ly() and persp(): different outputs? I am trying to draw a 3D surface plot using plotly in R but cannot get the  x and y values to match the z ones correctly – unlike when using persp().
The example on the plotly website itself (https://plot.ly/r/3d-surface-plots/) returns a different output than when using persp().
kd <- with(MASS::geyser, MASS::kde2d(duration, waiting, n = 50))

# with plotly
plot_ly(x = ~kd$x, y = ~kd$y, z = ~kd$z) %>% add_surface()

# with persp
persp(x = kd$x, y = kd$y, z = kd$z, theta=130, phi=40, r = sqrt(10), d = 3, ticktype = "detailed")

In the 'plotly for R' book, it says "there should be a sensible ordering to the x/y axes in a surface plot since plotly.js interpolates z values."
I expect the issue to emerge from that but I cannot figure out how to solve it, except manually inverting x and y:
plot_ly(x = ~kd$y, y = ~kd$x, z = ~kd$z) %>% add_surface()

Is there a way to get the correct output with plot_ly directly, i.e. looking similar to the one with persp()?
See the different output side by side here


text:
Q: Quick PHP inquiry regarding is_resource() function I am trying to learn and get proficient at PHP. I have no programming experience at all. Just finished a 200 video tutorial series on Youtube made by PHPAcademy and I am getting the hang of understanding of what it takes to think like a programmer.
I am going through another tutorial that provides the entire source code and instructions on how to make a complex log-in system with both front and back end settings. I only JUST started but am already kind of confused. I need to make a PHP script called "database.php" that connects to the database.
The code that is written in the source code is as follows:
<?php
session_start();
ob_start();
$hasDB = false;
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'acl_test';
$link = mysql_connect($server,$user,$pass);
if (!is_resource($link)) {
$hasDB = false;
die("Could not connect to the MySQL server at localhost.");
} else {
$hasDB = true;
mysql_select_db($db);
}
?>

MY QUESTION:
1) I never learned the function is_resource. So I looked it up but the definition doesn't make any sense to me. Is is_resource just checking to see if you get something back? I don't understand why it's necessary when you can do it like this: (which is the way I learned from PHPacademy)
<?php

$conn_error = 'Could not connect.';
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'tutorial';

if (!@mysql_connect($server, $user, $pass) || !@mysql_select_db($db)) {
die($conn_error);
}

?>

2) What is the benefit or con of using the function "is_resource()"  as opposed to just testing the mysql_connect() directly?? And what does $hasDB mean? In the IF statement above, it is testing to see if is_resource($link) is NOT true, then it goes down and read $hasDB = false, which then goes to die() and kills the page. Why is the $hasDB even necessary at this point??
3) Isn't it a better idea to use OOP to connect to the database and create some class/instances?
I'm asking because although I can probably write it the way I learned, I am seeing and observing new and different methods of getting the same thing done and I want to learn good, clean coding habit from the beginning. Sorry if this is such a beginner question but gotta start somewhere. Sometimes online definition of functions don't reveal the real-life implications, especially for future coding habit.
ANY help appreciated. Thanks.

A: 1) is_resource() function tells you if given variable of resource type or not.
The code you have from whatever "PHPacademy" is no better though. it is using strange things like @, die() and $conn_error of which former two shouldn't be used at all and a latter one not defined anywhere.
It should be at least something like
if (!mysql_connect($server, $user, $pass) || !mysql_select_db($db)) _503();

where _503() is a function that sends appropriate HTTP status code and outputs some predefined error page.
in case you are using site-wide error handler, you may just omit this condition, leaving functions as is - most clean way:
mysql_connect($server, $user, $pass);
mysql_select_db($db);

2) I doubt there is any benefit. $hasDB is apparently a boolean variable tells you if you have DB or not. Seems quite useless to me as well. However, you have to ask the author of this code to get certain answer.
Nevertheless you can use the mysql_connect() return value as a such flag variable all right.
3) OOP is good only if you understand it. In such a case it is usually better.

A: 1+2) The function returns either a resource or false, so checking for one is just as good as the other.
3) Only where using OOP makes sense.

A: 1) mysql_connect() will return a resource, or false on failure. Using is_resource() is a way to test if mysql_connect() succeed.
3) Isn't it a better idea to use OOP to connect to the database and create some class/instances?
If you're already familiar with OOP in other languages, I would definitely recommend you to do that, according to your needs of course. A good way to start would be to use a PHP Framework for example.

A: Keep it simple dude.  Why are you wrapping your database in a session and output buffering? As far as I'm concerned is_resource is extraneous and superfluous - you really only need to ensure the db connection is not false (it always returns a resource otherwise).  The php.net mysql_connect function works just fine and a full example is provided:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

http://php.net/manual/en/function.mysql-connect.php
Welcome to StackOverflow.


text:
Q: Override a single function in an Emacs library I use an Emacs mode to annotate some of my files (the actual mode is not important). It's supplied as a library and comes with compiled lisp code (of course). I want to modify its behavior by overriding a single function in it. Just for my local Emacs session. For now, I just copy-paste the function from the library's source file, modify it a bit, then hit eval-last-sexp. So far, so good. However, I get inconsistent results: I'm not sure how Emacs handles functions coming from .elc files mixed with functions coming from source. Sometimes I see my own version of the function running, sometimes the original version. Very confusing (and annoying).
Any ideas how can I consistently replace a lisp function in an Emacs library without modifying the library's source files which are read-only?

A: Something like this should do the trick:
(advice-add 'name-of-func-to-override :override
            (lambda () (message "does this instead now")))

Replace name-of-func-to-override with the function  name and the lambda with your version.
I suggest looking at the add-function (and advice-add) docs as :override may not actually be what you want.

A: The most likely explanation for your problem is that you sometimes (copy and) eval-last-sexp before the other library is loaded: the last one wins!
Using advice-add as suggested by @Jack is a good solution, because that override can be applied before the function is defined and it will survive the function's normal definition.
This said, in many cases you don't need to override any function.  Maybe all it takes is to define your own function with your own name and then change the keymap so that it runs your function instead of the one from the library.


text:
Q: Change icon image size and border in SAPUI5 Are there any way to change the size and border of this icon (icon="images/{Land}.png")??. I tried with this class "mIcon" but it changes all the list, not only the icon with the image. I don't know if is posible only change the size of icon.
xmlns:html="http://www.w3.org/1999/xhtml"  class="hosp-popup" >

        <List id="idListCounPop"
            width="100%"
            mode="SingleSelectLeft"
            selectionChange="onListChange"
            items="{ path: '/countrySet' }">
            <StandardListItem title="{Landx}" icon="images/{Land}.png" class="mIcon">
                <customData>
                    <core:CustomData key="Land" value="{Landx}" />
                    <core:CustomData key="Icon" value="sap-icon://globe"/>
                </customData>
            </StandardListItem>
        </List>

this is a part of the css because is too long:
.hosp-popup {
    height:20em;
    min-height: 15em;
    max-height: 40em;
}

.hosp-popup .mIcon{
    min-height: 4em;
    max-height: 4em;
}

Thank you!!!

A: For the size, try this:
px : give fixed pixels to your icon
em : dimensions with respect to your current font. Say ur current font is 12px then 1.5em will be 18px (12px + 6px).
pt : stands for points. Mostly used in print media
% : percentage. Refers to the size of the icon based on its original size.
Try with width and height until you get the size you want for your icon. Maybe some of this types of setting sizes help you best than others.

For the border, just try adding this line to your existent code:
    .hostp-popup .mIcon {
     text-shadow: 0 0 3px #000;
     }


text:
Q: linux command setsid I am trying to write a wrapper which will execute a script as a session leader.
I am confused by the behaviour of the linux command setsid. Consider this script, called test.sh:
#!/bin/bash
SID=$(ps -p $$ --no-headers -o sid)
if [ $# -ge 1 -a $$ -ne $SID ] ; then
  setsid bash test.sh
  echo pid=$$ ppid=$PPID sid=$SID parent
else
  sleep 2
  echo pid=$$ ppid=$PPID sid=$SID child
  sleep 2
fi

The output differs depending on whether it is executed or sourced:
$ bash
$ SID=$(ps -p $$ --no-headers -o sid)
$ echo pid=$$ ppid=$PPID sid=$SID
pid=9213 ppid=9104 sid= 9104
$ ./test.sh 1 ; sleep 5
pid=9326 ppid=9324 sid= 9326 child
pid=9324 ppid=9213 sid= 9104 parent
$ . ./test.sh 1 ; sleep 5
pid=9213 ppid=9104 sid= 9104 parent
pid=9336 ppid=1 sid= 9336 child
$ echo $BASH_VERSION
4.2.8(1)-release
$ exit
exit

So, it seems to me that setsid returns immediately when the script is sourced, but it waits for its child when the script is executed.
Why would the presence of a controlling tty have anything to do with setsid? Thanks!
Edit: For clarification I added pid/ppid/sid reporting to all relevant commands.

A: The source code of the setsid utility is actually very straightforward. You'll note that it only fork()s if it sees that its process ID and process-group ID are equal (i.e., if it sees that it's a process group leader) — and that it never wait()s for its child process: if it fork()s, then the parent process just returns immediately. If it doesn't fork(), then it gives the appearance of wait()ing for a child, but really what happens is just that it is the child, and it's Bash that's wait()ing (just as it always does). (Of course, when it really does fork(), Bash can't wait() for the child it creates, because processes wait() for their children, not their grandchildren.)
So the behavior that you're seeing is a direct consequence of a different behavior:

*

*when you run . ./test.sh or source ./test.sh or whatnot — or for that matter, when you just run setsid directly from the Bash prompt — Bash will launch setsid with a new process-group-ID for job control purposes, so setsid will have the same process-ID as its process-group-ID (that is, it's a process group leader), so it will fork() and won't wait().

*when you run ./test.sh or bash test.sh or whatnot and it launches setsid, setsid will be part of the same process group as the script that's running it, so its process-ID and process-group-ID will be different, so it won't fork(), so it'll give the appearance of waiting (without actually wait()ing).

A: The behavior I observe is what I expect, though different from yours.  Can you use set -x to make sure you're seeing things right?

$ ./test.sh 1
child
parent
$ . test.sh 1
child
$ uname -r
3.1.10
$ echo $BASH_VERSION
4.2.20(1)-release

When running ./test.sh 1, the script's parent — the interactive shell — is the session leader, so $$ != $SID and the conditional is true.
When running . test.sh 1, the interactive shell is executing the script in-process, and is its own session leader, so $$ == $SID and the conditional is false, thus never executing the inner child script.

A: I do not see any problem with your script as is. I added extra statements in your code to see what is happening:
    #!/bin/bash

    ps -H -o pid,ppid,sid,cmd

    echo '$$' is $$

    SID=`ps -p $$ --no-headers -o sid`

    if [ $# -ge 1 -a $$ -ne $SID ] ; then
      setsid bash test.sh
      echo pid=$$ ppid=$PPID sid=$SID parent
    else
      sleep 2
      echo pid=$$ ppid=$PPID sid=$SID child
      sleep 2
    fi

The case that concerns you is:
./test.sh 1

And trust me run this modified script and you will see exactly what is happening. If the shell which is not a session leader runs the script then it simply goes to else block. Am I missing something?
I see now what you mean: When you do ./test.sh 1 with your script as is then parent waits for the child to complete. child blocks the parent. But if you start the child in background then you will notice that parent completes before child. So just make this change in your script:
      setsid bash test.sh &


text:
Q: elasticsearch failed to resolve host [elasticsearch-discovery] I deploy elastichsearch to my AWS EKS for logging purpose, using stable/elasticsearch chart, with this command:
helm install stable/elasticsearch --namespace logging --name elasticsearch --set data.terminationGracePeriodSeconds=0

once installed, all pods running under logging are Running but not in ready status
NAME                                    READY   STATUS    RESTARTS   AGE
elasticsearch-client-64bb574bff-85lp9   0/1     Running   0          41s
elasticsearch-client-64bb574bff-t4h6r   0/1     Running   0          44m
elasticsearch-data-0                    0/1     Pending   0          44m
elasticsearch-master-0                  0/1     Pending   0          44m

And I got this warnings from elasticsearch pod logs
[elasticsearch-client-647c67f49d-npjp4] not enough master nodes discovered during pinging (found [[]], but needed [2]), pinging again
[2018-11-27T22:53:55,009][WARN ][o.e.d.z.UnicastZenPing   ]
[elasticsearch-client-647c67f49d-npjp4] failed to resolve host
[elasticsearch-discovery] java.net.UnknownHostException: elasticsearch-discovery: Name or service not known

UPDATE
helm template ./charts/stable/elasticsearch --namespace logging --name elasticsearch --set data.terminationGracePeriodSeconds=0 > deployment.yaml
this is the template that helm install
---
# Source: elasticsearch/templates/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: elasticsearch
  labels:
    app: elasticsearch
    chart: "elasticsearch-1.14.1"
    release: "elasticsearch"
    heritage: "Tiller"
data:
  elasticsearch.yml: |-
    cluster.name: elasticsearch

    node.data: ${NODE_DATA:true}
    node.master: ${NODE_MASTER:true}
    node.ingest: ${NODE_INGEST:true}
    node.name: ${HOSTNAME}

    network.host: 0.0.0.0
    # see https://github.com/kubernetes/kubernetes/issues/3595
    bootstrap.memory_lock: ${BOOTSTRAP_MEMORY_LOCK:false}

    discovery:
      zen:
        ping.unicast.hosts: ${DISCOVERY_SERVICE:}
        minimum_master_nodes: ${MINIMUM_MASTER_NODES:2}

    # see https://github.com/elastic/elasticsearch-definitive-guide/pull/679
    processors: ${PROCESSORS:}

    # avoid split-brain w/ a minimum consensus of two masters plus a data node
    gateway.expected_master_nodes: ${EXPECTED_MASTER_NODES:2}
    gateway.expected_data_nodes: ${EXPECTED_DATA_NODES:1}
    gateway.recover_after_time: ${RECOVER_AFTER_TIME:5m}
    gateway.recover_after_master_nodes: ${RECOVER_AFTER_MASTER_NODES:2}
    gateway.recover_after_data_nodes: ${RECOVER_AFTER_DATA_NODES:1}
  log4j2.properties: |-
    status = error
    appender.console.type = Console
    appender.console.name = console
    appender.console.layout.type = PatternLayout
    appender.console.layout.pattern = [%d{ISO8601}][%-5p][%-25c{1.}] %marker%m%n
    rootLogger.level = info
    rootLogger.appenderRef.console.ref = console
    logger.searchguard.name = com.floragunn
    logger.searchguard.level = info
  pre-stop-hook.sh: |-
    #!/bin/bash
    exec &> >(tee -a "/var/log/elasticsearch-hooks.log")
    NODE_NAME=${HOSTNAME}
    echo "Prepare to migrate data of the node ${NODE_NAME}"
    echo "Move all data from node ${NODE_NAME}"
    curl -s -XPUT -H 'Content-Type: application/json' 'elasticsearch-client:9200/_cluster/settings' -d "{
      \"transient\" :{
          \"cluster.routing.allocation.exclude._name\" : \"${NODE_NAME}\"
      }
    }"
    echo ""

    while true ; do
      echo -e "Wait for node ${NODE_NAME} to become empty"
      SHARDS_ALLOCATION=$(curl -s -XGET 'http://elasticsearch-client:9200/_cat/shards')
      if ! echo "${SHARDS_ALLOCATION}" | grep -E "${NODE_NAME}"; then
        break
      fi
      sleep 1
    done
    echo "Node ${NODE_NAME} is ready to shutdown"
  post-start-hook.sh: |-
    #!/bin/bash
    exec &> >(tee -a "/var/log/elasticsearch-hooks.log")
    NODE_NAME=${HOSTNAME}
    CLUSTER_SETTINGS=$(curl -s -XGET "http://elasticsearch-client:9200/_cluster/settings")
    if echo "${CLUSTER_SETTINGS}" | grep -E "${NODE_NAME}"; then
      echo "Activate node ${NODE_NAME}"
      curl -s -XPUT -H 'Content-Type: application/json' "http://elasticsearch-client:9200/_cluster/settings" -d "{
        \"transient\" :{
            \"cluster.routing.allocation.exclude._name\" : null
        }
      }"
    fi
    echo "Node ${NODE_NAME} is ready to be used"

---
# Source: elasticsearch/templates/client-serviceaccount.yaml

apiVersion: v1
kind: ServiceAccount
metadata:
  labels:
    app: elasticsearch
    chart: elasticsearch-1.14.1
    component: "client"
    heritage: Tiller
    release: elasticsearch
  name: elasticsearch-client

---
# Source: elasticsearch/templates/data-serviceaccount.yaml

apiVersion: v1
kind: ServiceAccount
metadata:
  labels:
    app: elasticsearch
    chart: elasticsearch-1.14.1
    component: "data"
    heritage: Tiller
    release: elasticsearch
  name: elasticsearch-data

---
# Source: elasticsearch/templates/master-serviceaccount.yaml

apiVersion: v1
kind: ServiceAccount
metadata:
  labels:
    app: elasticsearch
    chart: elasticsearch-1.14.1
    component: "master"
    heritage: Tiller
    release: elasticsearch
  name: elasticsearch-master

---
# Source: elasticsearch/templates/client-svc.yaml
apiVersion: v1
kind: Service
metadata:
  labels:
    app: elasticsearch
    chart: elasticsearch-1.14.1
    component: "client"
    heritage: Tiller
    release: elasticsearch
  name: elasticsearch-client

spec:
  ports:
    - name: http
      port: 9200
      targetPort: http
  selector:
    app: elasticsearch
    component: "client"
    release: elasticsearch
  type: ClusterIP

---
# Source: elasticsearch/templates/master-svc.yaml
apiVersion: v1
kind: Service
metadata:
  labels:
    app: elasticsearch
    chart: elasticsearch-1.14.1
    component: "master"
    heritage: Tiller
    release: elasticsearch
  name: elasticsearch-discovery
spec:
  clusterIP: None
  ports:
    - port: 9300
      targetPort: transport
  selector:
    app: elasticsearch
    component: "master"
    release: elasticsearch

---
# Source: elasticsearch/templates/client-deployment.yaml
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  labels:
    app: elasticsearch
    chart: elasticsearch-1.14.1
    component: "client"
    heritage: Tiller
    release: elasticsearch
  name: elasticsearch-client
spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: elasticsearch
        component: "client"
        release: elasticsearch
    spec:
      serviceAccountName: elasticsearch-client
      securityContext:
        fsGroup: 1000
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 1
            podAffinityTerm:
              topologyKey: kubernetes.io/hostname
              labelSelector:
                matchLabels:
                  app: "elasticsearch"
                  release: "elasticsearch"
                  component: "client"
      initContainers:
      # see https://www.elastic.co/guide/en/elasticsearch/reference/current/vm-max-map-count.html
      # and https://www.elastic.co/guide/en/elasticsearch/reference/current/setup-configuration-memory.html#mlockall
      - name: "sysctl"
        image: "busybox:latest"
        imagePullPolicy: "Always"
        command: ["sysctl", "-w", "vm.max_map_count=262144"]
        securityContext:
          privileged: true
      containers:
      - name: elasticsearch
        env:
        - name: NODE_DATA
          value: "false"
        - name: NODE_MASTER
          value: "false"
        - name: DISCOVERY_SERVICE
          value: elasticsearch-discovery
        - name: PROCESSORS
          valueFrom:
            resourceFieldRef:
              resource: limits.cpu
        - name: ES_JAVA_OPTS
          value: "-Djava.net.preferIPv4Stack=true -Xms512m -Xmx512m "
        - name: MINIMUM_MASTER_NODES
          value: "2"
        resources:
            limits:
              cpu: "1"
            requests:
              cpu: 25m
              memory: 512Mi

        readinessProbe:
          httpGet:
            path: /_cluster/health
            port: 9200
          initialDelaySeconds: 5
        livenessProbe:
          httpGet:
            path: /_cluster/health?local=true
            port: 9200
          initialDelaySeconds: 90
        image: "docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.0"
        imagePullPolicy: "IfNotPresent"
        ports:
        - containerPort: 9200
          name: http
        - containerPort: 9300
          name: transport
        volumeMounts:
        - mountPath: /usr/share/elasticsearch/config/elasticsearch.yml
          name: config
          subPath: elasticsearch.yml
      volumes:
      - name: config
        configMap:
          name: elasticsearch

---
# Source: elasticsearch/templates/data-statefulset.yaml
apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
  labels:
    app: elasticsearch
    chart: elasticsearch-1.14.1
    component: "data"
    heritage: Tiller
    release: elasticsearch
  name: elasticsearch-data
spec:
  serviceName: elasticsearch-data
  replicas: 2
  template:
    metadata:
      labels:
        app: elasticsearch
        component: "data"
        release: elasticsearch
    spec:
      serviceAccountName: elasticsearch-data
      securityContext:
        fsGroup: 1000
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 1
            podAffinityTerm:
              topologyKey: kubernetes.io/hostname
              labelSelector:
                matchLabels:
                  app: "elasticsearch"
                  release: "elasticsearch"
                  component: "data"
      initContainers:
      # see https://www.elastic.co/guide/en/elasticsearch/reference/current/vm-max-map-count.html
      # and https://www.elastic.co/guide/en/elasticsearch/reference/current/setup-configuration-memory.html#mlockall
      - name: "sysctl"
        image: "busybox:latest"
        imagePullPolicy: "Always"
        command: ["sysctl", "-w", "vm.max_map_count=262144"]
        securityContext:
          privileged: true
      - name: "chown"
        image: "docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.0"
        imagePullPolicy: "IfNotPresent"
        command:
        - /bin/bash
        - -c
        - chown -R elasticsearch:elasticsearch /usr/share/elasticsearch/data &&
          chown -R elasticsearch:elasticsearch /usr/share/elasticsearch/logs
        securityContext:
          runAsUser: 0
        volumeMounts:
        - mountPath: /usr/share/elasticsearch/data
          name: data
      containers:
      - name: elasticsearch
        env:
        - name: DISCOVERY_SERVICE
          value: elasticsearch-discovery
        - name: NODE_MASTER
          value: "false"
        - name: PROCESSORS
          valueFrom:
            resourceFieldRef:
              resource: limits.cpu
        - name: ES_JAVA_OPTS
          value: "-Djava.net.preferIPv4Stack=true -Xms1536m -Xmx1536m "
        - name: MINIMUM_MASTER_NODES
          value: "2"
        image: "docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.0"
        imagePullPolicy: "IfNotPresent"
        ports:
        - containerPort: 9300
          name: transport

        resources:
            limits:
              cpu: "1"
            requests:
              cpu: 25m
              memory: 1536Mi

        readinessProbe:
          httpGet:
            path: /_cluster/health?local=true
            port: 9200
          initialDelaySeconds: 5
        volumeMounts:
        - mountPath: /usr/share/elasticsearch/data
          name: data
        - mountPath: /usr/share/elasticsearch/config/elasticsearch.yml
          name: config
          subPath: elasticsearch.yml
        - name: config
          mountPath: /pre-stop-hook.sh
          subPath: pre-stop-hook.sh
        - name: config
          mountPath: /post-start-hook.sh
          subPath: post-start-hook.sh
        lifecycle:
          preStop:
            exec:
              command: ["/bin/bash","/pre-stop-hook.sh"]
          postStart:
            exec:
              command: ["/bin/bash","/post-start-hook.sh"]
      terminationGracePeriodSeconds: 0
      volumes:
      - name: config
        configMap:
          name: elasticsearch
  updateStrategy:
    type: OnDelete
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes:
        - "ReadWriteOnce"
      resources:
        requests:
          storage: "30Gi"

---
# Source: elasticsearch/templates/master-statefulset.yaml
apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
  labels:
    app: elasticsearch
    chart: elasticsearch-1.14.1
    component: "master"
    heritage: Tiller
    release: elasticsearch
  name: elasticsearch-master
spec:
  serviceName: elasticsearch-master
  replicas: 3
  template:
    metadata:
      labels:
        app: elasticsearch
        component: "master"
        release: elasticsearch
    spec:
      serviceAccountName: elasticsearch-master
      securityContext:
        fsGroup: 1000
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 1
            podAffinityTerm:
              topologyKey: kubernetes.io/hostname
              labelSelector:
                matchLabels:
                  app: "elasticsearch"
                  release: "elasticsearch"
                  component: "master"
      initContainers:
      # see https://www.elastic.co/guide/en/elasticsearch/reference/current/vm-max-map-count.html
      # and https://www.elastic.co/guide/en/elasticsearch/reference/current/setup-configuration-memory.html#mlockall
      - name: "sysctl"
        image: "busybox:latest"
        imagePullPolicy: "Always"
        command: ["sysctl", "-w", "vm.max_map_count=262144"]
        securityContext:
          privileged: true
      - name: "chown"
        image: "docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.0"
        imagePullPolicy: "IfNotPresent"
        command:
        - /bin/bash
        - -c
        - chown -R elasticsearch:elasticsearch /usr/share/elasticsearch/data &&
          chown -R elasticsearch:elasticsearch /usr/share/elasticsearch/logs
        securityContext:
          runAsUser: 0
        volumeMounts:
        - mountPath: /usr/share/elasticsearch/data
          name: data
      containers:
      - name: elasticsearch
        env:
        - name: NODE_DATA
          value: "false"
        - name: DISCOVERY_SERVICE
          value: elasticsearch-discovery
        - name: PROCESSORS
          valueFrom:
            resourceFieldRef:
              resource: limits.cpu
        - name: ES_JAVA_OPTS
          value: "-Djava.net.preferIPv4Stack=true -Xms512m -Xmx512m "
        - name: MINIMUM_MASTER_NODES
          value: "2"
        resources:
            limits:
              cpu: "1"
            requests:
              cpu: 25m
              memory: 512Mi

        readinessProbe:
          httpGet:
            path: /_cluster/health?local=true
            port: 9200
          initialDelaySeconds: 5
        image: "docker.elastic.co/elasticsearch/elasticsearch-oss:6.5.0"
        imagePullPolicy: "IfNotPresent"
        ports:
        - containerPort: 9300
          name: transport

        volumeMounts:
        - mountPath: /usr/share/elasticsearch/data
          name: data
        - mountPath: /usr/share/elasticsearch/config/elasticsearch.yml
          name: config
          subPath: elasticsearch.yml
      volumes:
      - name: config
        configMap:
          name: elasticsearch
  updateStrategy:
    type: OnDelete
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes:
        - "ReadWriteOnce"
      resources:
        requests:
          storage: "4Gi"

---
# Source: elasticsearch/templates/client-pdb.yaml

---
# Source: elasticsearch/templates/data-pdb.yaml

---
# Source: elasticsearch/templates/master-pdb.yaml

---
# Source: elasticsearch/templates/podsecuritypolicy.yaml

---
# Source: elasticsearch/templates/role.yaml

---
# Source: elasticsearch/templates/rolebinding.yaml

A: I fixed adding a PVC and a StorageClass, because the events logs from master-0 and data-0 was PVC is not bound


text:
Q: Getting existing Internet Explorer Window Created by PowerShell I need to interact with a IE window that was previously created in PowerShell without using a global variable.
If(WindowAlreadyCreatedByPowerShell){
    $IE = WindowAlreadyCreatedByPowerShell
}Else{
    $IE = New-Object -com internetexplorer.application;
    $IE.visible = $true;
    $IE.navigate($url);
}

Note: Using ((New-Object -ComObject Shell.Application).Windows).Invoke() | ?{$_.Name -eq "Internet Explorer"} returns nothing

A: So you will need to store something in the parent scope - if you don't want to store the IE object, store the URL you opened, or even better, the window handle (HWND property, which should be unique). Otherwise, you won't have a reliable way of getting which window you want, especially if your session is opening other IE windows as well.
# Variable for the created IE window handle
$expectedHWND = $null

# This will enumerate all ShellWindows opened as a COM object in your session
$allShellWindows = ( New-Object -ComObject Shell.Application ).Windows()

# Get the IE object matching the HWND you stored off when you first opened IE
# If you opened other windows in the session, the HWND should be unique so you
# can get the correct window you are expecting
$existingIE = $allShellWindows | Where-Object {
  $_.HWND -eq $expectedHWND
}

# Your code, slightly modified
if( $existingIE ){
  # You should be able to operate on $existingIE here instead of reassigning it to $IE
  Write-Output "Found existing IE session: HWND - $($existingIE.HWND), URL - $($existingIE.LocationURL)"
} else {
  $IE = New-Object -com internetexplorer.application;
  $IE.visible = $true;
  $IE.navigate($url);
  $expectedHWND = $IE.HWND
}

If you run that twice, but don't set $expectedHWND to $null the second time, it will find your IE window. Note that this is a lot of work for avoiding storing a variable in the parent scope, but is technically feasible.
You will likely need to curate the sample above for your specific application, but serves as a good demonstration of getting an operable object for the IE window you previously opened.


text:
Q: Errors when exporting plots to Plot.ly I have this data (sample of the first 20 rows):

*

*Codering  variable    value

*1 Z1  Week.0  0

*2 Z2  Week.0  0

*3 Z3  Week.0  0

*4 Z4  Week.0  0

*5 Z5  Week.0  0

*6 Z6  Week.0  0

*7 Z7  Week.0  0

*8 Z8  Week.0  0

*9 Z9  Week.0  0

*10    Z101    Week.0  NA

*11    Z102    Week.0  NA

*12    Z1  Week.1  0

*13    Z2  Week.1  0

*14    Z3  Week.1  0

*15    Z4  Week.1  0

*16    Z5  Week.1  0

*17    Z6  Week.1  0

*18    Z7  Week.1  0

*19    Z8  Week.1  0

and I plot it using:
pZ <- ggplot(zmeltdata,aes(x=variable,y=value,color=Codering,group=Codering)) +
  geom_line()+
  geom_point()+
  theme_few()+
  theme(legend.position="right")+
  scale_color_hue(name = "Treatment group:")+
  scale_y_continuous(labels = percent)+
  ylab("Germination percentage")+
  xlab("Week number")+
  labs(title = "Z. monophyllum germination data")
pZ

The graph displays just fine:

Yet when I want to export this to Plot.ly I get the following errors:
> py <- plotly()
> response<-py$ggplotly(pZ)
Error in if (all(xcomp) && all(ycomp)) { :
  missing value where TRUE/FALSE needed
In addition: Warning message:
In trace.list[[lind[1]]]$y == trace.list[[lind[2]]]$y :
  longer object length is not a multiple of shorter object length

And I have searched for these errors, yet the explanation thoroughly confuses me. "The missing value where TRUE/FALSE needed." is supposed to occur if you use logical termms as IF/ELSE/TRUE/FALSE and such in your process, which I don't at all! Even when checking for any NA's in the value of the graph I get:
> is.na(pZ)
       data      layers      scales     mapping       theme coordinates       facet    plot_env      labels
      FALSE       FALSE       FALSE       FALSE       FALSE       FALSE       FALSE       FALSE       FALSE

and the 'longer object length is not multiple of shorter object length' is supposed to pop up when you have objects of different lengths, but I'm only using 1 object with 3 rows that have exactly the same length.. The value of the graph does give me a NULL when I ask for those rows, but that is supposed to happen..
> nrow(zmeltdata)
[1] 143
> nrow(test)
NULL

All in all, I'm very confused and don't know how to correctly handle these errors, could someone elaborate?
Thanks for your time.
EDIT: I have tried to export a different graph to Plot.ly using a random sample of 1:100 and that worked just fine, I'm pretty sure the error is in my data, I just can't figure out how to fix it.
EDIT2: In response to @Gregor:
> dput(head(zmeltdata, 20))
structure(list(Codering = structure(c(16L, 19L, 20L, 21L, 22L,
23L, 24L, 25L, 26L, 17L, 18L, 16L, 19L, 20L, 21L, 22L, 23L, 24L,
25L, 26L), .Label = c("B1", "C2", "C3", "C8", "M1", "M101", "M102",
"M2", "M3", "M4", "M5", "M6", "M7", "M8", "M9", "Z1", "Z101",
"Z102", "Z2", "Z3", "Z4", "Z5", "Z6", "Z7", "Z8", "Z9"), class = "factor"),
    variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Week.0",
    "Week.1", "Week.2", "Week.3", "Week.4", "Week.5", "Week.6",
    "Week.7", "Week.8", "Week.9", "Week.10", "Week.11", "Week.12"
    ), class = "factor"), value = c(0, 0, 0, 0, 0, 0, 0, 0, 0,
    NA, NA, 0, 0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("Codering",
"variable", "value"), row.names = c(NA, 20L), class = "data.frame")

And the tail:
> dput(tail(zmeltdata, 43))
structure(list(Codering = structure(c(19L, 20L, 21L, 22L, 23L,
24L, 25L, 26L, 17L, 18L, 16L, 19L, 20L, 21L, 22L, 23L, 24L, 25L,
26L, 17L, 18L, 16L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 17L,
18L, 16L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 17L, 18L), .Label = c("B1",
"C2", "C3", "C8", "M1", "M101", "M102", "M2", "M3", "M4", "M5",
"M6", "M7", "M8", "M9", "Z1", "Z101", "Z102", "Z2", "Z3", "Z4",
"Z5", "Z6", "Z7", "Z8", "Z9"), class = "factor"), variable = structure(c(10L,
10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 11L, 11L, 11L, 11L,
11L, 11L, 11L, 11L, 11L, 11L, 11L, 12L, 12L, 12L, 12L, 12L, 12L,
12L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L,
13L, 13L, 13L), .Label = c("Week.0", "Week.1", "Week.2", "Week.3",
"Week.4", "Week.5", "Week.6", "Week.7", "Week.8", "Week.9", "Week.10",
"Week.11", "Week.12"), class = "factor"), value = c(0.1, 0.06,
0.05, 0.09, 0.04, 0.08, 0.05, 0.08, 0, 0, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), .Names = c("Codering",
"variable", "value"), row.names = 101:143, class = "data.frame")

I am not at all surprised by these, there are quite some NA's in the dataset but they shouldn't prove to be an issue, since I have used a similar (bigger) dataset before.
And I also have the .csv file for you to use if you wish: https://www.mediafire.com/?jij1vlp14a29ntt

A: The issue is about handling NA's...  I got https://plot.ly/~marianne2/417/z-monophyllum-germination-data/ by running the following code:
pZ <- ggplot(na.omit(zmeltdata), aes(x=variable, y=value, color=Codering,
                                 group=Codering)) +
  geom_line() +
  geom_point() +
  # theme_few() +
  theme(legend.position="right") +
  scale_color_hue(name="Treatment group:") +
  # scale_y_continuous(labels = percent) +
  ylab("Germination percentage") +
  xlab("Week number") +
  labs(title="Z. monophyllum germination data")

py$ggplotly(pZ, kwargs=list(fileopt="overwrite", filename="test_zdata"))

Note that I had to comment out theme_few() and scale_y_continuous(labels = percent) because from loading only "ggplot2", I would get the following errors:
Error: could not find function "theme_few"

and
Error in structure(list(call = match.call(), aesthetics = aesthetics,  :
object 'percent' not found

respectively.  I guess these are dependency issues (maybe you're using a version of "ggthemes"?).
I don't know what kind of magic theme_few() does, but if I don't use na.omit() on zmeltdata, my pZ plot looks like this:

Eww, "Week.10" comes after "Week.1" instead of after "Week.9"...  So you wouldn't want to send this to plotly anyway!  So I cannot exactly reproduce your ggplot example.  But I wonder if you really want to keep these NA's (the CSV itself reads "NA", I was expecting blank "cells").  Don't you want to pre-process these anyway?
Note that I get the following warning message when I don't use na.omit() on zmeltdata:
Warning messages:
1: Removed 20 rows containing missing values (geom_path).
2: Removed 47 rows containing missing values (geom_point).

Again, beyond pure displaying/plotting considerations, since this looks like scientific data, wouldn't you want to number weeks with actual numbers, or pad the digits if you really want a string? ("Week.01", "Week.02", etc.)
And it looks like the missing data is all trailing...  There's just no data (yet) for weeks 10+, right?
Thanks for reporting,
Marianne


text:
Q: getting weird answer about pre-increment value i got final tomorrow & stuck in this question .
Let's say ( c++ )
x = 1;
cout << ++x + ++x; // this gives me equals to 6 !

isn't it suppose to be 5 ? ( 2 + 3 )
i'm lost , any help would be truly appreciated .

A: It's like :
the first ++x = 2

so now x=2
next ++x = 3
now x=3

so out = 3 + 3 = 6

because you are using the same variable so it will be applied to both the x.


text:
Q: Sum of all values from dynamically created edittexts Reference image
I need to add the editexts values, like in a billing app, and to store this data in shared preferences.
As shown in the image I need to add all of the editexts (empty) values and then disply the sum in Result field. Just like that others, Ety cage, Load, Ld Cage..
Please someone help me..
createTextview.setOnClickListener(new View.OnClickListener() {
        @SuppressLint({"SetTextI18n",})
        public void onClick(View v) {
            LinearLayout ll = new LinearLayout(getApplicationContext());
            ll.setOrientation(LinearLayout.HORIZONTAL);
            ll.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 100));
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.weight = 3.0f;
            params.setMargins(10,0,10,0);
           // ll.setPadding(5, 1, 10, 0);
            final TextView txt = new TextView(getApplicationContext());
            final EditText txtLoad = new EditText(getApplicationContext());
            final EditText txtLoad1 = new EditText(getApplicationContext());
            final EditText txtLoad2 = new EditText(getApplicationContext());
            final EditText txtLoad3 = new EditText(getApplicationContext());

            txt.setText( ""+(j + 1));
            txt.setPadding(5, 0, 5, 0);
            txt.setTextColor(Color.BLACK);
            txt.setTextSize(20);

            txtLoad.setHintTextColor(Color.GRAY);
            txtLoad.setHint("Empty");
            txtLoad.setPadding(5, 0, 1, 0);
            int txtloadid = j+10;
            txtLoad.setLayoutParams(params);
            txtLoad.setId(txtloadid);

            txtLoad1.setHint("Ety Cage");
            int txtload1id = j+50;
            txtLoad1.setId(txtload1id);

            txtLoad2.setHint("Load");
            int txtload2id = j+100;
            txtLoad2.setId(txtload2id);

            txtLoad3.setHint("Ld Cage");
            int txtload3id = j+150;
            txtLoad3.setTextSize(18);
            txtLoad3.setId(txtload3id);

            ll.addView(txt);
            ll.addView(txtLoad);
            ll.addView(txtLoad1);
            ll.addView(txtLoad2);
            ll.addView(txtLoad3);

            //Add fields to LinearLayout defined in XML
            mainLinear.addView(ll);
            count++;
            j=count;
        }

    });

A: Whenever you create a new edittext for which you want to refer the value you can set a tag for it.
Also maintain a list of tags. That way you later you can use to iterate.

*

*Set Tags on view using view.setTag() and keep a record of tags in a list.

*iterate the list of tags and refer to your views using findViewWithTag()

*While iterating you can access the values in your edittext

A: Add all your EditText in an ArrayList.
List<EditText > editTexts - new ArrayList<>();

Once you have this value in your arraylist simply iterate through array List and add values.
int sum = 0;
for(EditText editText: editTexts) {
    String sTextFromET = editText.getText().toString();
    int nIntFromET = new Integer(sTextFromET ).intValue();
    sum =+ nIntFromET
}


text:
Q: Integrate $\int_0^{2\pi}\frac{1}{4\cos^2(t)+9\sin^2(t)}\mathrm{d}t$ with complex functions or Fourier transformations.
What is the value of the following integral:
$$\int_0^{2\pi}\frac{1}{4\cos^2(t)+9\sin^2(t)}\mathrm{d}t$$
$\frac\pi9$ ; $\frac\pi6$ ; $\frac\pi3$ ; $\frac\pi2$ or $\frac\pi4$?

a full solution for this problem would be much appreciated

A: Integrate with Fourier series as follows
$$\int_0^{2\pi}\frac{1}{4\cos^2 t+9\sin^2 t}{d}t
=\int_0^{2\pi}\frac{2}{13-5\cos 2t} {d}t\\
=\int_0^{2\pi}\left( \frac16 + \frac13\sum_{n=1}^\infty \frac{1}{5^n} \cos (2n t) \right)dt
=\frac\pi3
$$

A: Here is a solution using differentiation under integral sign. Consider a more general integral, namely:
\begin{align*}
I_1(\alpha,\beta) & = \int_{0}^{2\pi}\frac{dx}{\alpha \cos^2x+\beta \sin^2x} \\
                  & = \int_{0}^{2\pi} \frac{\sec^2x}{\alpha + \beta \tan^2x} \,\mathrm{d}x\\
                  & = \frac{1}{\beta} \int_0^{2\pi} \frac{1}{\left(\sqrt{\frac{\alpha}{\beta}}\right)^2 + \tan^2 (x)}\; \mathrm{d}(\tan x)\,\\
& = \frac{1}{\sqrt{\alpha \beta}} \left[ \left(\tan^{-1}\left(\sqrt{\frac{\beta}{\alpha}}\tan (x)\right)\right) \right]_0^{2\pi} = \frac{2\pi}{\sqrt{\alpha\beta}}
\end{align*}


text:
Q: HEVC Disabling Rate Distortion Optimization in the HM Reference code I'm using HEVC HM reference code version 10. My task is to disable the RDO of the HEVC reference encoder. For doing this i have tried to set RDOQ and RDOQTS to 0 in the configuration file, however it didn't help as the PSNR and file size before and after performing the changes remained the same. Any tip/answer to do the same will be really helpful to me. So please help if you can. Thanks in advance.

A: I encoded two sequences using the parameters below
$ ./TAppEncoderStatic -c ../cfg/encoder_lowdelay_main.cfg --InputFile=t1.yuv --BitstreamFile=slask.bin --ReconFile=slask.yuv --SourceWidth=832 --SourceHeight=480 --QP=29 --InputBitDepth=8 --FrameSkip=0 --FramesToBeEncoded=4 --FrameRate=30

$ ./TAppEncoderStatic -c ../cfg/encoder_lowdelay_main.cfg --InputFile=t1.yuv --BitstreamFile=slask.bin --ReconFile=slask.yuv --SourceWidth=832 --SourceHeight=480 --QP=29 --InputBitDepth=8 --FrameSkip=0 --FramesToBeEncoded=4 --FrameRate=30 --RDOQ=0 --RDOQTS=0

The difference is shown in the image below

As you can see, the rate-distortion parameters are working for me (tm)
I'm using commit a3598fcb9d0cbf16f7594f59b18c4a25ed23df6b from the git-mirror on
git://hevc.kw.bbc.co.uk/git/jctvc-hm.git

Hope it helps...


text:
Q: CocoaPods Swift Linker Error I am trying to use the Loggly libraries through Lumberjack in an iOS application written in Swift. I am getting the following linker errors:
undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_LogglyFormatter", referenced from:
  __TMaCSo15LogglyFormatter in AppDelegate.o
"_OBJC_CLASS_$_LogglyLogger", referenced from:
  __TMaCSo12LogglyLogger in AppDelegate.o
ld: symbol(s) not found for architecture x86_64

I have it using a bridging header for some other libraries (not pod ones) that work just fine.
Here is the contents of my bridging header:
#import <AFNetworking/AFNetworking.h>
#import <CocoaLumberjack/DDLog.h>
#import <LogglyLogger-CocoaLumberjack/LogglyLogger.h>
#import <LogglyLogger-CocoaLumberjack/LogglyFormatter.h>

Lastly here is the contents of my Podfile:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '7.0'
pod 'CocoaLumberjack'
pod 'AFNetworking'
pod 'LogglyLogger-CocoaLumberjack', :git => 'https://github.com/melke/LogglyLogger-CocoaLumberjack'

Anybody have a suggestion on this?

A: As of Cocoapods 0.25.0 the Xcode configuration maintains that the Pods are built with build setting ONLY_ACTIVE_ARCH set to YES. You have two options:

*

*Make sure you set "Build Active Architecture" to YES for your Debug configuration

*Set Build Active Architecture to NO for the cocoapods in the Debug configuration

So assuming you did option 1, navigate to your build settings and you should end up with something like this:

Included from the official Troubleshooting Guide

This applies to users migrating projects from Xcode 4, or are still
  using Xcode 4.

*

*The Pods Xcode project now sets the ONLY_ACTIVE_ARCH build setting to
  YES in the Debug configuration. You will have to set the same on your
  project/target, otherwise the build will fail.

*Ensure your
  project/target has an ARCHS value set, otherwise the build will fail.

*When building a iOS project from the command-line, with the xcodebuild
  tool that comes with Xcode 4, you'll need to completely disable this
  setting by appending to your build command: ONLY_ACTIVE_ARCH=NO.


text:
Q: Relation of mean of standard deviations and standard deviation Let $\{x_{i,j} : i=1..7,j=1,..n\}$ be a set of samples from $n$ weeks (where $i$ denotes the day of the week).
Is there any interesting information to be gleaned from the relationship (ratio, difference, etc.) between $ \mathbb{E}_{i} [std(x_i)]$ and $std(x)$?

A: This is closely related to ANOVA, which essentially compares a pooled within-group (within-week, here) variance estimate with the between-group (between-week) variance estimate. If $\text{var}(x_i)$ is much smaller than $\text{var}(x)$ then there is evidence that the mean differs from group to group (week to week).


text:
Q: Why does JSTL's fmt:setLocale tag only work with scope set to session? My web application has a default locale, which is based on the country that the server is in. However, jobs created on the system could be based in another country so could quite easily have a different locale. On a certain page, I am temporarily (within page scope) trying to set the locale using JSTL's fmt:setLocale tag to the locale of the job on display, but it isn't working.
I'm using it like so, where currentLocale is the locale code of the job (e.g. en_GB or en_HK).
<fmt:setLocale value="${currentLocale}"/>

I've even specifically set it to one of the above locale codes:
<fmt:setLocale value="en_HK"/>

But then when it comes to using the fmt:formatNumber function, the currency isn't set properly:
<fmt:formatNumber value="${dailyRate}" type="currency"/>

This uses the default locale of en_US so the currency symbol is the dollar, not HKD as it should be in the above example!
However, when I change the scope of the locale to "session" it works and uses the correct currency code:
<fmt:setLocale value="en_HK" scope="session"/>

But I don't want to be overriding the session's locale for obvious reasons. Does anybody know why this is the case or if there is a workaround for this issue? I have seen comments on other questions on Stack Overflow where the odd person has said the setLocale tag only works when scope is set to session, but no one has explained why this might be the case.
Just for reference, here is a related question I found where people have had a similar issue: JSTL formatDate ignoring locale
Thanks in advance!


text:
Q: List of Tuples remove error ExpenseL is my list of tuples and I try to remove from the list starting from start to stop but I just get this error: in removeFromAtoB
    expenseL.pop(i)
TypeError: 'tuple' object cannot be interpreted as an integer
Please help me!!! :)
def removeFromAtoB():
    aux = copy.deepcopy(expenseL)
    print(expenseL, "\n")
    start = int(input("Starting point: "))
    stop = int(input("Ending point: "))
    j = 0
    for i in expenseL:
        if j >= start and j <= stop:
            expenseL.pop(i)
        j += 1
    print(expenseL)

A: You're iterating over your list of tuples:
for i in expenseL

That means i will be one of those tuples. Then you try to use it in list.pop:
expenseL.pop(i)

This won't work, because list.pop expects an index. Just enumerate your list:
for index, tpl in enumerate(expenseL):
    ...
    expenseL.pop(index)

But this breaks, too, because the indices change when you remove an element. You could circumvent that by not increasing j in that case, but the simpler way is just assigning an empty list to the slice:
def removeFromAtoB():
    start = int(input("Starting point: "))
    stop = int(input("Ending point: "))
    expenseL[start:stop+1] = []


text:
Q: Transit MKDirectionsRequest produces null error Error Domain=MKErrorDomain Code=5 "(null)" I'm trying to use the MapKit Directions Request to get transit directions between two coordinates.
When I switch to other (non-Transit) types, the code below works, but when I switch to Transit, it throws an error that doesn't show up anywhere in Apple's documentation.
The two locations (source and destination) are both in New York City so there should definitely be transit directions available.
Error message:
Error Domain=MKErrorDomain Code=5 "(null)"

Code snippet:
override func viewDidLoad() {
    super.viewDidLoad()

    let request = MKDirectionsRequest()

    // Set request parameters
    request.source = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: 40.7127, longitude: -74.0059), addressDictionary: nil))
    request.destination = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: 40.6761, longitude: -73.9521), addressDictionary: nil))
    request.requestsAlternateRoutes = true

    // Set tranport type parameter (anything other than .Transit works)
     request.transportType = .Transit

    let directions = MKDirections(request: request)

    directions.calculateDirectionsWithCompletionHandler { response, error in
        print(response)

        guard let routes = response?.routes else {
            print(error?.description)
            return
        }

        // Prints step-by-step directions
        for r in routes {
            print("New route")
            for step in r.steps {
                print("  " + step.instructions)
            }
        }
    }
}

Any advice on what I might be doing wrong for the particular Transit case? Thank you!

A: Routing directions for transit is currently not supported (iOS 9). MKDirectionsRequest will return a null error, as you observed.
This only seems to be documented directly in MapKit's headers. Take a look at the comment for the Transit type.
//  MKDirectionsTypes.h

@available(iOS 7.0, *)
public struct MKDirectionsTransportType : OptionSetType {
    public init(rawValue: UInt)

    public static var Automobile: MKDirectionsTransportType { get }
    public static var Walking: MKDirectionsTransportType { get }
    @available(iOS 9.0, *)
    public static var Transit: MKDirectionsTransportType { get } // Only supported for ETA calculations
    public static var Any: MKDirectionsTransportType { get }
}


text:
Q: Azure Function - Failed to start a new language worker for runtime: Python (M1 Mac incompatible architecture (have 'x86_64', need 'arm64e')) I am trying to Build http triggered python function app. I just initialized it using terminal commands. I have not modified anything in base template. I am trying to run it on localhost but when I use 'func start host' I get this ImportError:
ImportError: dlopen(/opt/homebrew/Cellar/azure-functions-core-tools@4/4.0.3971/workers/python/3.7/OSX/X64/grpc/_cython/cygrpc.cpython-37m-darwin.so, 0x0002): tried: '/opt/homebrew/Cellar/azure-functions-core-tools@4/4.0.3971/workers/python/3.7/OSX/X64/grpc/_cython/cygrpc.cpython-37m-darwin.so' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e')), '/usr/local/lib/cygrpc.cpython-37m-darwin.so' (no such file), '/usr/lib/cygrpc.cpython-37m-darwin.so' (no such file)
even after this error it seems function is hosted on localhost and I get localhost link to trigger api call, but when I try to call via api the host api it doesn't respond and just crashes with following errors.
error log

A: The function runtime does not support M1 processors at this time.
https://github.com/Azure/azure-functions-core-tools/issues/2834

A: This is an existing issue.
The workaround could be using the python interpreter from a conda environment

*

*Create a conda environment with supported python version

*Go to the root directory of the project

*Remove .venv folder

*Activate the newly created conda environment

*Create new virtual environment using python -m venv .venv/
OR
you could manually select python interpreter while creating the azure function
Image


text:
Q: Enque Scripts and Styles Wordpress I'm trying to make this work.. http://jsfiddle.net/EnY74/20/ but I'm new to javascript and didn't realise I needed the external resources.
So I copied the javascript in from jsfiddle into a folder and enqueue the script and it didn't work. (but the enqueue is correct) I then realised I needed external resources.
So now I'm trying to resolve the dependencies the jsfiddle uses so it will work on my site.
-angularjs 1.1.1
-bootstrap-combined.min.css
-jquery-1.9.1.min.js
function wootique_child_scripts() {

     // jQuery
     wp_enqueue_script('jquery');

     // AngularJS not sure if this is right?
     wp_enqueue_script('angular-core', '//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js', array('jquery'), null, false);
     wp_enqueue_script('angular-route', '//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular-route.min.js', array('angular-core'), null, false);
     wp_enqueue_script('angular-resource', '//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular-resource.min.js', array('angular-route'), null, false);

     // my custom javascript
     wp_enqueue_script('custom-pagination-js', get_stylesheet_directory_uri() . '/js/pagination.js');

}

add_action('wp_enqueue_scripts', 'wootique_child_scripts');

I'm not sure how to include the bootstrap and how to include it here, I'm new to javascript but have a lot of experience with PHP.
Am I recalling the AngularJS correctly? Is the jQuery enqueue correct (I read it's included in wordpress).
I feel quite lost at the moment with this any help would be appreciated specifically with loading the twitter bootstrap thank you.

A: Your enqueue looks fine.
wp_enqueue_style('bootsrap-style', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css')
wp_enqueue_script('bootstrap-js', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js')

Keep it up, you are doing fine.