text:
Q: My makeshift calculator isn't able to access the library I made, how do I fix this? In python I have a library that I made that contains makeshift functions for a calculator as a learning project. It worked earlier but now the main program can't get definitions of functions or variables from the library.
Main executable:
```print('Version 1.2.1 Beta')
print('Notice: Version 1.1.3 is unstable')
import maths
run = True
while run == True:
    print getFunction
    inLine = raw_input('>>> ')
    desFunction = inLine
    checkFunction()

Library:
    #Mathematical Symposium
#Begin Assignments
print('Version 1.1.4')
print('Converted to pylib for math functions')
print('Non-Executable')
print('Alternatively you can define desFunction as your function then execute checkFunction()')
getFunction = 'Please input desired function'
getX = 'Please input the first numerical value'
getY = 'Please input the second numerical value'
ans = 'Null'
run = True
#End Assignments
#Begin Definitions
def funcdir():
    functionli = ['add', 'subtract', 'multiply', 'divide', 'square root']
    print functionli
def checkFunction():
    if desFunction == 'add':
        add()
    elif desFunction == 'subtract':
        subtract()
    elif desFunction == 'multiply':
        multiply()
    elif desFunction == 'divide':
        divide()
    elif desFunction == 'square root':
        sqroot()
    elif desFunction == 'halt':
        run = False
    elif desFunction == 'help':
        funcdir()
def add():
    print getX
    inLine = raw_input('>>> ')
    x = inLine
    print getY
    inLine = raw_input('>>> ')
    y = inLine
    ans = float(x) + float(y)
    print ans
def subtract():
    print getX
    inLine = raw_input('>>> ')
    x = inLine
    print getY
    inLine = raw_input('>>> ')
    y = inLine
    ans = float(x) - float(y)
    print ans
def multiply():
    print getX
    inLine = raw_input('>>> ')
    x = inLine
    print getY
    inLine = raw_input('>>> ')
    y = inLine
    ans = float(x) * float(y)
    print ans
def divide():
    print getX
    inLine = raw_input('>>> ')
    x = inLine
    print getY
    inLine = raw_input('>>> ')
    y = inLine
    ans = float(x) / float(y)
    print ans
def sqroot():
    import math
    num = input('>>> ')
    print math.sqrt(num)
#End Definitions
#Begin Visible Process
#No Visible Process
#End Visible Process

If anyone knows how to fix this, it would be a big help. Thanks.

A: After you import "maths", it's functions and variables are accessible as "maths.getFunction", etc.

A: Importing a module only adds the name of the module to the current namespace. It doesn't give you direct access to the module's contents. For that you need to either use attribute access syntax (print maths.getFunction for instance), or use from module import names to explicitly import some names (either listing all the names you want, or using * to import everything). You may want from maths import getFunction, checkFunction (though I'm not sure what your desFunction line is supposed to do).


text:
Q: Various Regex Validation I'm new to regex. I have an array (call it arr1) with assorted values. I am trying to validate that it has the following format for its elements with arr1[x] provided as an example
arr1[x] = "item1, item2, item3, item4, item5":

item 1 - "abcdef" (variable number of letters) or "abcdef asdf" (variable number of letters separated by one whitespace character)
item 2 - "abcdef" (variable number of letters) or "abcdef asdf" (variable number of letters separated by one whitespace character)
item 3 - "12345678" (eight digits)
item 4 - "123 456 7890" (telephone number with 3 digits followed by 3 digits followed by 4 digits with two whitespace characters as shown)

Here is a snippet of what I have for phone number validation (not sure how the second line works - got it from a different SO thread):
function f(s) {
  var s2 = (""+s).replace(/\D/g, '');
  var m = s2.match(/^(\d{3})(\d{3})(\d{4})$/);
}

Thanks in advance for any assistance.

A: You can try this regex to account for all your cases:
^(?:[a-z]+(?: [a-z]+)?|\d{8}|\d{3} \d{3} \d{4})$

Use it with i option, e.g.:
var re = /^(?:[a-z]+(?: [a-z]+)?|\d{8}|\d{3} \d{3} \d{4})$/i;
if (re.exec(s) !== null) {
    return true;
}

Have a look at the demo.

var re = /^(?:[a-z]+(?: [a-z]+)?|\d{8}|\d{3} \d{3} \d{4})$/i;
var str = 'abcdef';
if (re.exec(str) !== null) {
    alert(true);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proving the asymptotic relationship between $(lg\cdot n)^{0.5}$ and $lg\cdot (n^{0.5})$? Say $f(n) = (lg\cdot n)^{0.5}$
and $g(n) = lg\cdot (n^{0.5})$
It would appear that $f(n) = O(g(n))$ for $n \gt 55$ correct? How do I go about proving the the relationship for this?

A: You don't need specific values for $n$ necessarily to show that $f(n) = O(g(n))$. All you need is that the limit $f(n)/g(n)$ goes to a non-negative constant as $n \to \infty$ (even 0) or that $f(n)/g(n)$ is bounded above by some non-negative constant for $n$ large enough.


text:
Q: How to locate the meta files generated by EF in a class library? I've moved my Entity Framework 4 model to a class library. The meta files are built to \bin\Debug
What is the connection string I use to locate the meta files in the class library? I have tried:
  <add name="Models.DataModelConnectionString"
connectionString="metadata=res://MyClassLibrary, 1.0.0.0, neutral,
 null/bin/Debug/Models.DataModel.csdl|res://MyClassLibrary, 1.0.0.0, neutral,
 null/bin/Debug/Models.DataModel.ssdl|res://MyClassLibrary, 1.0.0.0, neutral,
 null/bin/Debug/Models.DataModel.msl;provider=Devart.Data.Oracle;
....">

I still get the error "The specified metadata path is not valid".
Do I need to move the meta files to the class library root directory?
Edit
I have tried using res://*/Models.DataModel.csdl etc. but got the error "Unable to load the specified metadata resource." instead

A: When the EF model is located in a separate/project (MyCompany.MyApp.Infra) which is used by another project, you need to correctly configure the connection string in the app.config or web.config
See this example:
MyContext.cs in MyCompany.MyApp.Infra project.
namespace MyCompany.MyApp.Domain
{
    using System.Data.Objects;

    /// <summary>
    /// The MyContext
    /// </summary>
    public partial class MyContext : ObjectContext, IUnitOfWork
    {
        /// <summary>
        /// The ConnectionString
        /// </summary>
        public const string ConnectionString = "name=MyContext";

        /// <summary>
        /// The ContainerName
        /// </summary>
        public const string ContainerName = "MyContext";

        /// <summary>
        /// Initializes a new instance of the <see cref="MyContext"/> class.
        /// </summary>
        public MyContext()
            : base(ConnectionString, ContainerName)
        {
            this.ContextOptions.LazyLoadingEnabled = true;
        }
    }
}

web.config in Silverlight Web Project
<add name="MyContext"
connectionString="metadata=res://MyCompany.MyApp.Infra/DataModel.MyContext.csdl|
                           res://MyCompany.MyApp.Infra/DataModel.MyContext.ssdl|
                           res://MyCompany.MyApp.Infra/DataModel.MyContext.msl;
provider=System.Data.SqlClient;
provider connection string="Data Source=localhost\DB_01;Initial Catalog=MyDB;Persist Security Info=True;User ID=usr;Password=pwd;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient"
/>

A: The solution is to embed the metadata files in the assembly by changing the output from CopyToOutputDirectory to EmbedInOutputAssembly
This would allow res://*/Model.ssdl etc. to work


text:
Q: How create the infinite route with one component in Nuxt I lately get a project with Nuxt.js and facing some problems with it.
I have a component that gets some products from an API and gets them from Vuex.
Each product may have an array of children and each child may have an array of children and so on.

import Images from '@/components/products/Images'
import { mapGetters } from 'vuex'

export default {
  components: {
    Images
  },
  data () {
    return {
      images: [],
      options: {
        width: 300,
        padding: {
          2: 8,
          default: 12
        }
      }
    }
  },
  computed: {
    ...mapGetters({
      products: 'getProducts'
    })
  },
  mounted () {
    this.images = this.products.filter(
      item => item.slug === this.$route.params.slug
    )
  }
}
<template>

          {{ item.title }}

        <Images
          :item="item"
          :slug="true"
          :childs="item.childs"
          large
        />

</template>

Products data can be like this:

products: {
  { id: 1, childs: [], title: "title 1" },
  { id: 2, childs: [
    { id: 3, childs: [], title: "title 3" },
    { id: 4, childs: [
      { id: 5, childs: [
        { id: 6, childs: [], title: "title 6" },
      ], title: "title 5" },
    ], title: "title 4" },
  ], title: "title 2" }
}

What I need is each time user clicks on the image component, If the product has childs item and the length of it was bigger than 0 redirect the child to the current route and get the children array.

A: Not sure if I understand it properly, but you may have a recursive route, right?
Nuxt's Unknown Dynamic Nested Routes may help here IMO: https://nuxtjs.org/docs/2.x/features/file-system-routing#unknown-dynamic-nested-routes
If you organize your pages like this
pages/
--| people/
-----| _id.vue
-----| index.vue
--| _.vue
--| index.vue

You'll get the following routes
/ -> index.vue
/people -> people/index.vue
/people/123 -> people/_id.vue
/about -> _.vue
/about/careers -> _.vue
/about/careers/chicago -> _.vue


text:
Q: Listing over multiple inputs (tensor rank > 1) in a compiled function I'm trying to optimize the solution given by Michael E2 to my previous problem (Efficiently determining if 3D points are within a surface composed of polygons) which I figured would be relatively straight forward to do with Compile but I'm having trouble listing over two inputs to a compiled function.
Starting with Michael's code:
data = Flatten[
   Table[{x, y, z, x^2 + y^2 + z^2 + RandomReal[0.1]},
     {x, -2, 2, 0.2}, {y, -2, 2, 0.2}, {z, -2, 2, 0.2}], 2];

plot = ListContourPlot3D[data, Contours -> {1}, Mesh -> None];

polygonCoords =
  Cases[Normal[plot[[1]]], Polygon[x_, ___] :> x, {0, Infinity}];

g = Graphics3D[{Opacity[.09], EdgeForm[Opacity[.3]],
   Polygon[#,
      VertexColors -> Table[Hue[RandomReal[]], {Length[#]}]] & /@
    Cases[Normal[plot[[1]]], Polygon[x_, ___] :> x, {0, Infinity}]},
  Lighting -> "Neutral", ImageSize -> 400, Axes -> True];

side[{P_, Q_, R_, ___}, X_] := Det@Differences[{X, P, Q, R}];
insideQ[polyhedron_, point_] := And @@ Positive[side[#, point] & /@ polyhedron];

points = RandomReal[{-1.5, 1.5}, {1000, 3}];
insideQ[polygonCoords, #] & /@ points; // AbsoluteTiming

Too slow: 0.5 sec for 1000 points and I have millions.
I inlined the formula for the det and replaced And + Positive with Min + UnitStep:
sideC = Compile[{{poly, _Real, 2}, {X, _Real, 1}},
   Block[{p1 = poly[[1, 1]], p2 = poly[[1, 2]], p3 = poly[[1, 3]],
     q1 = poly[[2, 1]], q2 = poly[[2, 2]], q3 = poly[[2, 3]],
     r1 = poly[[3, 1]], r2 = poly[[3, 2]], r3 = poly[[3, 3]],
     x1 = X[[1]], x2 = X[[2]], x3 = X[[3]]},
    UnitStep[-p3 q2 r1 + p2 q3 r1 + p3 q1 r2 - p1 q3 r2 - p2 q1 r3 +
      p1 q2 r3 + p3 q2 x1 - p2 q3 x1 - p3 r2 x1 + q3 r2 x1 +
      p2 r3 x1 - q2 r3 x1 - p3 q1 x2 + p1 q3 x2 + p3 r1 x2 -
      q3 r1 x2 - p1 r3 x2 + q1 r3 x2 + p2 q1 x3 - p1 q2 x3 -
      p2 r1 x3 + q2 r1 x3 + p1 r2 x3 - q1 r2 x3]
    ], CompilationTarget -> "C", RuntimeAttributes -> {Listable},
   Parallelization -> True, RuntimeOptions -> "Speed"];

insideQC[polyhedron_, point_] := Min@sideC[polygonCoords[[All, ;; 3]], point]

This lists over all the polygons. Lets test it,
insideQC[polygonCoords, #] & /@ points; // AbsoluteTiming

Now this is over 10x faster, 0.04 seconds. Compiling this again, because of the CompiledFunctionCall provides only a tiny speed improvment.
I think it should be faster to list over both the list of polygon coordinates and the points. I suspect this question is related: Threading a compiled function over multiple arguments of different lengths, specifically ruebenko's last answer which works fine on MMA 9 on Win7 x64, It should be possible?
Why doesn't this work:
sideC[polygonCoords, points]

Shouldn't this list over both inputs? How can I make this work?
I tried to force inline-ing of the compiled function definition but it doesn't appear to be supported?
insideQC =
  Compile[{{polyhedron, _Real, 3}, {points, _Real, 2}},
   Min@sideC[polyhedron, #] & /@ points, CompilationTarget -> "C",
   RuntimeOptions -> "Speed",
   CompilationOptions -> {"InlineCompiledFunctions" -> True,
     "InlineExternalDefinitions" -> True},
   RuntimeAttributes -> {Listable}, Parallelization -> True];

Compile::cfinll: "The CompiledFunction could not be inlined because its use requires threading with the Listable runtime attribute."


text:
Q: Throw custom exception if a file is not sorted correctly I have an app that merges sorted files. How to throw an exception and stop merging a corrupted file from the line that is unsorted (and dequeue the file)?
public class ComparableFile<T extends Comparable<T>> implements Comparable<ComparableFile<T>> {
    private final Deserializer<T> deserializer;
    private final Iterator<String> lines;
    private T buffered;

    public ComparableFile(File file, Deserializer<T> deserializer) {
        this.deserializer = deserializer;
        try {
            this.lines = Files.newBufferedReader(file.toPath()).lines().iterator();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    public T pop() {
        T tmp = peek();

        if (tmp != null) {
            buffered = null;
            return tmp;
        }

        throw new NoSuchElementException();
    }

    private T peek() {
        if (buffered != null) return buffered;
        if (!lines.hasNext()) return null;
        return buffered = deserializer.deserialize(lines.next());
    }

    public boolean isEmpty() {
        return peek() == null;
    }

    @Override
    public int compareTo(ComparableFile<T> that) {
        T mine = peek();
        T theirs = that.peek();

        if (mine == null) return theirs == null ? 0 : -1;

        if (theirs == null) return 1;

        return mine.compareTo(theirs);
    }

}

public class MergeFiles<T extends Comparable<T>> {
    private final PriorityQueue<ComparableFile<T>> files;

    public MergeFiles(List<File> files, Deserializer<T> deserializer) {
        this.files = new PriorityQueue<>(files.stream()
                .map(file -> new ComparableFile<>(file, deserializer))
                .filter(comparableFile -> !comparableFile.isEmpty())
                .collect(toList()));
    }

    public Iterator<T> getSortedElements() {
        return new Iterator<T>() {

            @Override
            public boolean hasNext() {
                return !files.isEmpty();
            }

            @Override
            public T next() {
                if (!hasNext()) throw new NoSuchElementException();
                ComparableFile<T> head = files.poll();
                T next = head.pop();
                if (!head.isEmpty()) files.add(head);
                return next;
            }};
    }

}

public interface Deserializer<T> {
    T deserialize(String s);
}

public class Main {

    public static void main(String[] args) {
        File in1 = new File("src/main/resources/in1.txt");
        File in2 = new File("src/main/resources/in2.txt");
        File in3 = new File("src/main/resources/in3.txt");
        List<File> files = Arrays.asList(in1, in2, in3);
        File out = new File("out.txt");

        Iterator<String> sortedElements
                  = new MergeFiles(files, line -> line).getSortedElements();

        while (sortedElements.hasNext()) {
            System.out.println(sortedElements.next());
        }

    }

}

In .txt files each word is a new line.
in1.txt:
Any
Conrad
Diarmid
Elyse
Genvieve
Jerald
Jessy
Jobie
Kania
Kerk
Mattie
Ronna
Roscoe
Sharona
Vevay

in2.txt:
Alayne
Albertina
Austina
Axel
Jasmin
Jordana
Lin
Robinetta
Sari
Sonnnie

in3.txt:
Astra
Dolley
Erick
Glynnis
Katti
Lucien
Meara
Rena
Syd
Tamqrah
Udell

Also a hint on how to write the merged content into out.txt would be appreciated. The size of the files can exceed PC memory...


text:
Q: Grep only string in a line in shell script I writing a shell script.
The line will look like:
"holderIdentity":"leader-elector1-5cd5b9d76d-ztfgf","numberofLeader":{"":0,"node2":1,"node3":2,"node4":2}"

The character 5cd5b9d76d-ztfgf will be created randomly, so my keyword to grep is just only leader-elector. And the string ,"numberofLeader":{"":0,"node2":1,"node3":2,"node4":2}" is also randomly (it is diffent everytime)
How can I get just this string leader-elector1-5cd5b9d76d-ztfgf from the line.
Thank you so much!

A: using GNU grep
grep -Eo 'leader-elector[^"]*' <<< '"holderIdentity":"leader-elector1-5cd5b9d76d-ztfgf","numberofLeader":{"":0,"node2 ":1,"node3":2,"node4":2}"'

otherwise with bash regex feature
var='"holderIdentity":"leader-elector1-5cd5b9d76d-ztfgf","numberofLeader":{"":0,"node2 ":1,"node3":2,"node4":2}"'
re='leader-elector[^"]*'

if [[ $var =~ $re ]] ; then
  declare -p BASH_REMATCH
  echo "${BASH_REMATCH[0]}"
fi


text:
Q: Default move constructor/assignment and deleted copy constructor/assignment According to the standard,

If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if
— X does not have a user-declared copy constructor,
— X does not have a user-declared copy assignment operator,
— X does not have a user-declared move assignment operator, and
— X does not have a user-declared destructor.

Now the following fails to compile
# include <utility>

class Foo
{
public:
  Foo() = default;
  Foo(Foo const &) = delete;
};

int main()
{
  Foo f;
  Foo g(std::move(f)); // compilation fails here
  return 0;
}

So it seems that a deleted function is considered as user-defined, which makes sense (it is not its default implementation). However, in that particular case, how would deleted copy construtor/assignment mess default move constructor/assignment?
I think this question has practical importance because manual generation and esp. maintenance of such default functions is error prone, while at the same time, the (righteous) increase of the use of classes such as std::unique_ptr as class members made non-copyable classes much more common beasts than they used to be.

A: user-declared means either either user-provided (defined by the user), explicitly defaulted (= default) or explicitly deleted (= delete) in contrast with implicitly defaulted / deleted (such as your move constructor).
So in your case, yes the move constructor is implicitly deleted because the copy-constructor is explicitly deleted (and thus user-declared).

However, in that particular case, how would deleted copy constructor/assignment mess default move constructor/assignment?

It would not, but the standard does not make the difference between this case and a complicated one.
The shortest answer is that having an implicitly defined move-constructor with an explicitly deleted copy-constructor might be dangerous in some cases, the same when you have a user-defined  destructor and no user-defined copy-constructor (see rule  of three/five/zero). Now, you can argue that a user-defined destructor does not delete the copy-constructor, but this is simply a flaw in the language which cannot be removed because it would break a lot of old (bad) program. To quote Bjarne Stroustrup:

In an ideal world, I think we would decide on "no generation" as the default and provide a really simple notation for "give me all the usual operations." [...] Also, a "no default operations" policy leads to compile time errors (which we should have an easy way to fix), whereas a generate operations by default policy leads to problems that cannot be detected until run time.

You can read more about this in N3174=10-0164.
Note that most people follow the rule  of three/five/zero, and in my opinion you should. By implicitly deleting the default move-constructor, the standard is "protecting" you from mistakes and should have protected you a long time before by deleting copy-constructor in some cases (see Bjarne's paper).
Further reading if you are interested:

*

*Enforcing the Rule of Zero

*N3153 - Implicit Move Must Go

*N3174

*N3201

I think this question has practical importance because manual generation and esp. maintenance of such default functions is error prone, while at the same time, the (righteous) increase of the use of classes such as std::unique_ptr as class members made non-copyable classes much more common beasts than they used to be.

Marking the move constructor as explicitly defaulted will solve this problem:
class Foo {
public:
  Foo() = default;
  Foo(Foo const &) = delete;
  Foo(Foo&&) = default;
};

You get a non-copyable object with a default move constructor, and in my opinion these explicit declarations are better than implicit ones (e.g. by only declaring the move constructor as default without deleting the copy-constructor).

A: As you stated, from §12.8

If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declared
  as defaulted if and only if

*

*X does not have a user-declared copy constructor,

*[...]

Note the user-declared. But if you look at §8.4.3:

A function definition of the form:
attribute-specifier-seqopt decl-specifier-seqopt declarator virt-specifier-seqopt = delete ;
is called a deleted definition. A function with a deleted definition is also called a deleted function.
A program that refers to a deleted function implicitly or explicitly, other than to declare it, is ill-formed.

So the standard defines deleted functions as user-declared (as you can see from above), even though they are deleted and can't be used.
Then, according to §12.8, the implicit move constructor is not defined, because of the user-declared (with = delete;) copy constructor.

A: The behavior can essentially be illustrated with:
void foo(const int& i)
{
    std::cout << "copy";
}

void foo(int&& i)
{
    std::cout << "move";
}

When both overloads are present, the int&& overload is selected for rvalues while the const int& overload is selected for lvalues. If you remove the int&& overload, const int& is called (ergo, not an error) even for rvalues. This is essentially what's happening in this case:
class Foo
{
public:
  Foo() = default;
  Foo(Foo const &) = delete;
};

Overload resolution only sees one candidate but since it is explicitly deleted, the program is ill-formed.
The non-normative note below the section you quoted clarifies this is what's happening:

[ Note: When the move constructor is not implicitly declared or explicitly supplied, expressions that otherwise would have invoked the
  move constructor may instead invoke a copy constructor.  — end note
  ]


text:
Q: How to 'force' Minecraft music to play? I have taken a look at these two answers but they do not mention a way to force the Minecraft music to play: [1] [2]
I was wondering if there is a way to 'force' music to play, whether this is achieved through datapacks, commands, or simply by walking to a specific area under specific conditions to make it happen.
Does anyone know if there is any way of doing this?

A: You can force Minecraft music to play with the /playsound command.
Syntax:
playsound <sound> <source> <targets> [<position>] [<volume>] [<pitch>] [<minVolume>]

For example:
/playsound minecraft:music.creative music @s ~ ~ ~ 999999

(The volume is not how loud the sound is, but how far from the source you can still hear it. Since you probably don't want the music to fade when you move away from the position, it is set to an extremely high number.)

Using Minecraft's autocomplete feature, if you type in:
/playsound minecraft:music.

...a list of options will appear, and you can select which one you like.


text:
Q: Execute "git submodule foreach" in parallel Is there any way to execute a git submodule foreach command in parallel, similarly of how the --jobs 8 parameter works with git submodule update?
For example, one of the projects we work on involves almost 200 sub-components (submodules) and we heavily use the foreach command to operate on them. I'd like to speed them up.
PS: In the case the solution involves a script, I work on Windows and, most of the time, using git-bash.

A: I propose you a solution based on a interpreted language multiplatform like Python.

Process Launcher

First of all you need define a class to manage the process to launch the command.
class PFSProcess(object):
    def __init__(self, submodule, path, cmd):
        self.__submodule = submodule
        self.__path = path
        self.__cmd = cmd
        self.__output = None
        self.__p = None

    def run(self):
        self.__output = "\n\n" + self.__submodule + "\n"
        self.__p = subprocess.Popen(self.__cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,
                             cwd=os.path.join(self.__path, self.__submodule))
        self.__output += self.__p.communicate()[0].decode('utf-8')
        if self.__p.communicate()[1]:
            self.__output += self.__p.communicate()[1].decode('utf-8')
        print(self.__output)

Multithreading

Next step is a generate multithread execution. Python includes in its core very powerful library to work with Threads. You can use it importing the following package:
import threading

Before threads creation you need create a worker, a function to call for each thread:
def worker(submodule_list, path, command):
    for submodule in submodule_list:
        PFSProcess(submodule, path, command).run()

As you can see the worker recives a submodule list. For clarity and because it is out of our scope, I recommend you take a look to .gitmodules from where you can generate the list of your submodules reading the file.

 < Tip >
As basic orientation you can find the following line in each submodule:
path = relative_path/project

For that purpose you can use this regular expression:
'path ?= ?([A-za-z0-9-_]+)(\/[A-za-z0-9-_]+)*([A-za-z0-9-_])'

If the regular expression matches you can get the relative path using the following one in the same line:
' ([A-za-z0-9-_]+)(\/[A-za-z0-9-_]+)*([A-za-z0-9-_])'

Pay attention because the last regular expression returns the relative path with a space character at first position.
 < / Tip>

Then split the submodule list into as many chunks as jobs that you want:
num_jobs = 8

i = 0
for submodule in submodules:
    submodule_list[i % num_jobs].append(submodule)
    i += 1

Finally dispatch each chunk (job) to each thread and wait until all threads finish:
for i in range(num_jobs):
    t = threading.Thread(target=worker, args=(list_submodule_list[i], self.args.path, self.args.command,))
    self.__threads.append(t)
    t.start()

for i in range(num_jobs):
    self.__threads[i].join()

Obviously I have exposed the basic concepts, but you can access to full implementation accessing to parallel_foreach_submodule (PFS) project in GitHub.

A: A simple, bash only solution is to do this (replace <command with your command>):
IFS=$'\n'
for DIR in $(git submodule foreach -q sh -c pwd); do
    cd $DIR && <command> &
done
wait

As a generic command (create a file called "git-foreach-parallel"):
#!/bin/bash

if [ -z "$1" ]; then
    echo "Missing Command" >&2
    exit 1
fi

IFS=$'\n'
for DIR in $(git submodule foreach -q sh -c pwd); do
    cd "$DIR" && "$@" &
done
wait

A: If somebody is looking for a pure-bash way to do it(to not install python in docker container or something), that's what helped me
Usage examples
bash git-submodule-foreach-parallel.sh "git fetch && git checkout master"

bash git-submodule-foreach-parallel.sh "git fetch && git pull"

bash git-submodule-foreach-parallel.sh "git fetch && git push"

COMMAND="git clean -dfx -e \"**/.idea\""
# Running command in parent repository
eval "$COMMAND"
# Running command in submodules
bash git-submodule-foreach-parallel.sh "$COMMAND"

git-submodule-foreach-parallel.sh (usage examples run it)
#!/bin/bash

if [ -z "$1" ]; then
    echo "Missing Command" >&2
    exit 1
fi

COMMAND="$@"

IFS=$'\n'
for DIR in $(git submodule foreach --recursive -q sh -c pwd); do
    printf "\nStarted running command \"${COMMAND}\" in directory \"${DIR}\"\n" \
    && \
    cd "$DIR" \
    && \
    eval "$COMMAND" \
    && \
    printf "Finished running command \"${COMMAND}\" in directory \"${DIR}\"\n" \
    &
done
wait


text:
Q: Can not deduce type of ranges iterator The following code fails to compile both on MSVC 2022 and gcc 12.1 (with c++20 enabled) with the same error:
#include <iostream>
#include <random>
#include <ranges>
#include <vector>

using namespace std;

int main()
{
    auto v0 = views::iota(0) | views::take(5) | views::transform([](auto i) -> double { return 10.1 * double(i); });
    // output: 0 10.1 20.2 30.3 40.4
    // output: double
    for (auto i = v0.begin(); i != v0.end(); ++i)
        cout << *i << ' ';
    cout << endl << typeid(decltype(*v0.begin())).name() << endl;

    // error: template argument deduction failed
    discrete_distribution<int>::param_type p0(v0.begin(), v0.end()); // (**)

    // this is ok
    vector<double> v1{10.1, 20.2, 30.3};
    discrete_distribution<int>::param_type p1(v1.begin(), v1.end());
    return 0;
}

The line (**) generates an error that the type of the param_type ctor iterators can not be deduced:
std::discrete_distribution<int>::param_type::param_type(_InIt,_InIt)': template parameter '_InIt' is ambiguous
Why does the deduction of this iterator type fail with both compiler? The output loop works fine with the same iterator.
How can this be fixed?

A: The problem is that many types in C++ were created under the pre-C++20 range paradigm. This means that they take a pair of iterators.
All of your views and operations construct ranges based on the C++20 std::ranges paradigm. This means that their ranges can be defined by an iterator and a sentinel value representing the end. The sentinel does not have to be an iterator. And for the case of v0, it does indeed have a sentinel that is not an iterator (this is because iota is a sentinel-based range).
But most types that were written pre-C++20 which conceptually consume ranges still use the paired iterator model of ranges. So they cannot work with any C++20 range that uses a sentinel. The constructor template has one type across two parameters, but your begin/end arguments are different types. Therefore, it fails to deduce the one type.
You will need to convert this range into either a container or a common_range (a range using paired iterators) via the views::common operation.


text:
Q: Add items to listbox in C# with thread I want to add some items to listbox with a thread or backgroundworker in C#. But when I call addlist function in a loop my program is not responding for a while. How can I fix that?
Here is my code:
   public delegate void addToList(string st);

   public void addlist(string st)
   {
        if (listBox1.InvokeRequired)
        {
            listBox1.Invoke(new addToList(addlist), st);
        }
        else
        {
            listBox1.Items.Add(st);
        }
    }

A: I'm assuming with your .InvokeRequired/Invoke(...) code that you are using WinForms and not WPF.
BackgroundWorker will call the ProgressChanged and RunWorkerCompleted events on the main thread (assuming you created the worker on that thread). If you are adding items to your ListBox on either one of these events, you should not require the Invoke().
If you are going to be rapidly adding items to the ListBox.Items collection, I suggest you use ListBox.BeginUpdate() and ListBox.EndUpdate() which will temporarily suspend redrawing of the ListBox while you add items. This is useful when you are adding hundreds or thousands of items to the ListBox in mere seconds.
For example:
void ReloadListBox()
{
   listBox.BeginUpdate(); // Suspend redrawing
   listBox.Items.Clear(); // Remove all existing items first

   backgroundWorker.RunWorkerAsync(); // Asynchronous generate new items
}

void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
   // Report a new list item in e.UserState.

   var newItem = e.UserState;
   listBox.Items.Add(newItem);
}

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
   // Alternatively, return a list of items in e.Result.

   var items = e.Result;
   listBox.Items.AddRange(items);

   listBox.EndUpdate(); // Resume redrawing and update
}

A: You could do this..
private delegate void Update();

public void addlist(string st)
 {
   listBox1.Invoke(new Update(() => listBox1.Items.Add(st)));
 }

A: I am not really that sure that i understood your question, but try
    Application.Current.Dispatcher.Invoke((Action)(() =>
{
    //listBox1..... do whatever you want.
}));

Also read http://msdn.microsoft.com/en-us/library/ms741870.aspx.

A: I had a problem similar to this while I was using a thread and I have solved it with the following

*

*First of all in the Form class constructor or in the Form_Load event make sure to set the control property like

ListBox.CheckForIllegalCrossThreadCalls = false;

*add a delegate like this code

delegate void setTextCallBack(String data);
private void setText(String data) {
if (this.ListBox1.InvokeRequired)
{
setTextCallBack d = new setTextCallBack(setText);
this.Invoke(d, new object[] { data });
}
else {
ListBox1.Items.Add(data);
}
}

and this worked for me
some answers I got while researching was to add the first step only but I'm not sure


text:
Q: Laravel Mix Bootstrap Glyphicons not loading I created a new laravel application and added the auth template.
I tried to add this button:
<button type="button" class="btn btn-default btn-lg">

</button>

But the glyphicons are not loading I get this error in my Chrome console:
GET http://localhost/fonts/vendor/bootstrap-sass/bootstrap/glyphicons-halflings-regular.woff2?448c34a56d699c29117adc64c43affeb
GET http://localhost/fonts/vendor/bootstrap-sass/bootstrap/glyphicons-halflings-regular.woff?fa2772327f55d8198301fdb8bcfc8158
GET http://localhost/fonts/vendor/bootstrap-sass/bootstrap/glyphicons-halflings-regular.ttf?e18bbf611f2a2e43afc071aa2f4e1512

npm watch is already running.
What else could cause this error?

A: Run command npm run dev or npm run production in production
https://laravel.com/docs/5.4/mix#running-mix

A: This problem is caused by you accessing the site through http://localhost/something/public - and not using a VirtualHost.
Just had the exact same error myself, and realized it was requesting the files from http://localhost/ and not from the projectfolder.


text:
Q: Prove that a perfect square is either a multiple of $4$ or of the form $4q+1$. Prove that a perfect square is either a multiple of $4$ or of the form $4q+1$ for some $q\in \mathbb{Z}$.
Any ideas on how to start? Do I use a proof by contraposition? Also what's the definition of a perfect square?

A: Hint: A perfect square is an integer $k$ such that $k = n^2$ for some integer $n$. It follows that $k$ must be non-negative and that $n$ can be chosen to be non-negative. As for approaching the problem, first break it up into two cases: $k$ even and $k$ odd.


text:
Q: React Build Failed Compile Error: Unclosed comment at Array.every I'm having a problem building my application on ReactJS, it is outputting this error:
     $ npm run build

> nannapp-web-app@0.1.0 build
> react-scripts build

Creating an optimized production build...
Failed to compile.

static/css/main.ed463b24.css from Css Minimizer plugin
Error: Unclosed comment
    at Array.every (<anonymous>)

I can't seem to find the comment it is referring, is there any way to get a detail on the error or file it referring to?
This is the index.html, i have added script tags to import Revolution Slider, as well as a bundled stylesheet:
    <!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

        <link href="dashboard/assets/css/style.bundle.css" rel="stylesheet" type="text/css" />

    <title>React App</title>

    You need to enable JavaScript to run this app.


text:
Q: How can I select only the columns containing non negative values from a frame using Deedle in C#? I would like to select / filter the columns from a frame that do not contain negative Values. That means creating a new frame with the columns that only contain positive values.
Something like the following (syntax is wrong):
var myFrameNoNeg = myFrame.Columns.Where(kvp => kvp.Value > 0); //

The idea is to Drop the columns which contain negative values.
Thank you.

A: Your code is pointing in the right direction - you need to use frame.Columns.Where. However, this does not give you individual values, but the whole column (as a series) and so you need to (again) iterate over all values in the column:
using Deedle;
using System.Linq;

Frame.FromColumns(frame.Columns.Where(kvp =>
  !kvp.Value.As<double>().Values.Any(v => v < 0.0)))

Since you are iterating over columns, you need to call Frame.FromColumns at the end to turn the series of columns back into a frame.
The Where method gives you the column data as boxed series containing objects. Using As<double>() is an efficient way to get the values as floating points.


text:
Q: Spark Scala Flumeutill not found I am getting the below error:

Exception in thread "main" java.lang.NoClassDefFoundError:
  org/apache/spark/streaming/flume/FlumeUtils$
          at SampleStream$.main(NetworkWordCount.scala:10)
          at SampleStream.main(NetworkWordCount.scala)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
          at java.lang.reflect.Method.invoke(Method.java:606)
          at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:665)
          at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:170)
          at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:193)
          at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:112)
          at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala) Caused by: java.lang.ClassNotFoundException:
  org.apache.spark.streaming.flume.FlumeUtils$
          at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
          at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
          at java.security.AccessController.doPrivileged(Native Method)
          at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:358)

i refer below link
https://spark.apache.org/docs/1.4.1/streaming-flume-integration.html

A: You need to have all libraries loaded in classpath.
Add this to build.sbt file: libraryDependencies += "org.apache.spark" % "spark-streaming-flume_2.10" % "1.6.1"

A: You need to package spark-streaming-flume and its dependencies (except spark-core and spark-streaming which are provided by spark-submit) into the application JAR.
https://spark.apache.org/docs/1.6.1/streaming-flume-integration.html has a better description about deploying. You can use this doc as there is no API changes between 1.4 and 1.6.


text:
Q: Validating inexistence of a Max in a continuous function In my assignment I have to prove the following statement:

Let $f$ be a continuous function which satisfies the following:
For every $x \in \Bbb R $ there is $y>x$ such that $f(y)>f(x)$
Let $a\in \Bbb R$
Prove that for every $M>0$ there is a $y>M$ such that $f(y)>f(a)$

My solution:

*

*Assume by contradiction that for there is M such that for every $y>M,f(y)\le f(a)$

*Therefore, f is Bounded because for every $y>M$ there is a value bigger then $f(y)$, which is constant, which is $f(a)$.

*From the above we can say that f is bounded in $[M,a]$

*Since f is continuous and blocked in a closed interval, we can say that f has a max value $f(a)$ in the closed interval $[M,a]$

*Conclusion number 4 is a contradiction to the fact that For every $x \in \Bbb R $ there is $y>x$ such that $f(y)>f(x)$

*Therefore, for every $M>0$ there is a $y>M$ such that $f(y)>f(a)$
Did I get right here?
Your help is much appreciated.
Alan


text:
Q: What is the best way to upload a folder to a website? I need an easy way to allow users to upload multiple files at once (ie I need to allow a user to upload a folder).  I do not wish to put the burden of zipping on the user.
I would prefer to avoid Flash or variants if possible.  I'm looking for a straight javascript / HTML solution if it is possible.  Please note, this rules out the answers at: What is the best client side browser library to upload multiple files over http?.

A: With Firefox 42 and Edge having implemented the new directory upload proposal we'll finally able to do cross-browser directory uploads. The APIs are nasty enough that you may want to check out my wrapper, uppie.

A: If you're avoiding Flash (and presumably Java?) the JS/HTML-only solution still requires single-file inputs, but essentially you attach an onchange event to your input, adding a new input to the DOM whenever a file is selected.

A: You won't be able to do it with just HTML and Javascript. I'd recommend trying Fancy Upload, a MooTools plugin for multiple file uploads. It uses a mixture of JavaScript and Flash, but degrades gracefully. It works with all major browsers including IE6 and there is also a Flash 10 compatible release available for download (though the demo hasn't been updated yet).

Update (2012-11-26):
Multiple file uploads are possible with valums or blueimp file uploaders.
For recursive directory uploads, your best solution is using Chrome 11's new folder upload API.  It also seems to work on Firefox if you use a vendor prefix.

A: Multiple file uploads are possible with valums or blueimp file uploaders.
For recursive directory uploads, your options are more limited:

*

*Your best solution is using Chrome 11's new folder upload API.  It also seems to work on Firefox if you use a vendor prefix.

*This is also possible cross-browser with a Java applet. However the % of folks with a JRE installed has gotten pretty low these days (< 70%)

A: This isn't a pure js/html solution. As EndangeredMassa has pointed out, it's not possible.  In fact, this idea is an IE/Windows only solution.  I don't recommend it, but it can work.
So, all disclaimers aside ...
Many years and several employers ago, we used to do some client side stuff that instantiated the FileSystemObject. It would iterate through each of the files and pass them through to the server one at a time.  Can't remember the details of how we did that :o(
Anyway, this usually meant that the client box would need to have to add the site to the list of trusted sites and give trusted sites a bunch of permissions that are turned off (for very good reasons).  Stuff like the ability to Initialize and script ActiveX controls not marked as safe.  That kind of thing.
I know that this isn't a perfect answer, but it could point you in the right direction.

A: FTP?  And if necs, wrap in Java Applet, ActiveX or whatever you want.
If not, although you don't want flash, SWFUpload is quite cool, you may want to reconsider it as a decent option.

A: Here is pure JS solution using ExtJS library


text:
Q: Converting WPF project to Silverlight? System.Windows.UIElement reference cant be found Im trying to convert my WPF project, written in MVVM template into a silverlight project.
However, i am running into some problems.
There is a class in the ViewModel folder (WPF) called BaseViewModel, that uses System.Windows.UIElement and System.Windows.Application.
But I can not find reference to these classes. Is there a workaround?

A: Both of these classes are in Silverlight's System.Windows namespace and are supported in SL 3 and 4.
Try installing the Silverlight 4 Tools for Visual Studio from here. When creating a new Silverlight project in VS2010, the reference should be added automatically. For reference, my path to the reference was:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0\System.Windows.dll


text:
Q: Laravel 5 Auth - What exactly are it's methods? I've just picked up laravel, so a total novice at this.
I'm using the native Authorisation services.
in the view app.blade.php is a line @if (Auth::guest())
If I go searching though ...\vendor\laravel\framework\src\Illuminate\Auth there's heaps of methods all over the place....
Is there any cheat sheet / summary? The documentation online at laravel doesn't seem to have any.

A: Check this LINK1
and here watch last four videos LINK2
You will get full idea :)


text:
Q: Getting two different result from same xpath HTML Code:

Hello  World

Each  element, the Link text contains double space as "Hello  World"
Retrieving information, in List
List<WebElement> findAllUserName = driver.findElements
                (By.xpath("//div[@class='deviceName truncate']//a[text()]"));

        for (WebElement webElement : findAllUserName) {
            String findUSerText = webElement.getText();
            System.out.println(findUSerText);
        }

Its gives list Result with single space, "Hello World"
How should overcome to this situation ? To compare text,
Concern behind this, wants to compare list element with given string :
driver.findElement(By.xpath("//div[@class='deviceName truncate']//a[contains(text(),'" + name + "')]"))

And its considering double space,

A: If you just check how you browser renders the link you will realize that it is also having a single space. See this discussion: Do browsers remove whitespace in between text of any html tag
So you either should to add a style to your page like this
a {
   white-space: pre;
}

That will make all your links unformatted.
or try to inject the style of the particular element on the fly like it is shown here: How can i set new style of element using selenium web-driver
Here is the example having two identical links but with different styles set.


text:
Q: Slick slider ().slick not a function with Wordpress PHP I am stumped on the cause of this error. I am getting "uncaught TypeError: $(...).slick is not a function" when using Slick Slider. I am using the code in WordPress and have added it as a plugin with PHP generated data. The slider has been working perfectly until I updated WordPress to version 5.8. It seem like slick.js is not being found but from what I can tell the script is being called correctly. I am guessing this has something to do with WordPress PHP more then the jQuery for the slider? I am not quite sure. If you have any ideas I would appreciate hearing it!

$(document).ready(function(){
    $('.center').slick({
  centerMode: true,
  centerPadding: '60px',
  slidesToShow: 3,
  responsive: [
    {
      breakpoint: 768,
      settings: {
        arrows: false,
        centerMode: true,
        centerPadding: '40px',
        slidesToShow: 3
      }
    },
    {
      breakpoint: 480,
      settings: {
        arrows: false,
        centerMode: true,
        centerPadding: '40px',
        slidesToShow: 1
      },
    },
    {
        lazyLoad: 'ondemand',
        slidesToShow: 3,
        slidesToScroll: 1
      }
  ]
});

});
      <link rel="stylesheet" type="text/css" href="wp-content/plugins/custom-carousel/slick.css"/>
      <link rel="stylesheet" type="text/css" href="wp-content/plugins/custom-carousel/slick-theme.css"/>
      <link rel="stylesheet" type="text/css" href="wp-content/plugins/custom-carousel/custom-carousel.css"/>

         <?php if ($wc_query->have_posts()) : ?>
         <?php while ($wc_query->have_posts()) : $wc_query->the_post(); ?>

             <a class="product_link" href="<?php the_permalink(); ?>">
                 <?php the_post_thumbnail(); ?>
                 <?php the_title(); ?>

         <?php endwhile; ?>
         <?php wp_reset_postdata(); ?>
         <?php else:  ?>

<?php _e( 'No Products' ); ?>

         <?php endif; ?>

A: try this:
jQuery(document).ready(function(){
jQuery('.center').slick({
   centerMode: true,
   centerPadding: '60px',
   slidesToShow: 3,
   responsive: [
{
  breakpoint: 768,
  settings: {
    arrows: false,
    centerMode: true,
    centerPadding: '40px',
    slidesToShow: 3
  }
},
{
  breakpoint: 480,
  settings: {
    arrows: false,
    centerMode: true,
    centerPadding: '40px',
    slidesToShow: 1
  },
},
{
    lazyLoad: 'ondemand',
    slidesToShow: 3,
    slidesToScroll: 1
  }
  ]
 });
});

Since wordpress uses jQuery instead of $
if u would want to change that here is a article about it: https://digwp.com/2011/09/using-instead-of-jquery-in-wordpress/


text:
Q: Function breaks with generated buttons I'm building a jQuery function that allows users to add additional fields to a form. The form has four buttons, for different donation values. When you click on one, it generates the appropriate form fields, and adds an option for an additional donation.
For some reason, the additional donation buttons don't work. The code for the buttons is exactly the same, so this makes no sense to me.
Here's the HTML:

Donation Information

    5" – $500
    4" – $250
    3" – $100
    2.5" – $50

And here's the jQuery:
$(".button").click(function(e) {
    e.preventDefault();
    if ($(this).hasClass("clicked")) {
        // do nothing
    } else if ($(this).hasClass("disabled")) {
        // do nothing
    } else {
        $(this).addClass("clicked");
        $(".button:not(.clicked)").addClass("disabled");
        var counter = $(".donation").length;
        var amount = $(this).attr("data-value");
        if (amount == 500) {
            var size = 5;
        } else if (amount == 250) {
            var size = 4;
        } else if (amount == 100) {
            var size = 3;
        } else if (amount == 50) {
            var size = 2.5;
        }
        $("#donationTarget").before("
<input maxlength=\"60\" name=\"inscription" + counter + "\" placeholder=\"Inscription (60 character maximum)\" type=\"text\" />
Color Preference (subject to availability):

<input id=\"color-blue" + counter + "\" type=\"radio\" name=\"color" + counter + "\" />Blue

<input id=\"color-orange" + counter + "\" type=\"radio\" name=\"color" + counter + "\" />Orange

<input id=\"color-red" + counter + "\" type=\"radio\" name=\"color" + counter + "\" />Red

<input id=\"color-yellow" + counter + "\" type=\"radio\" name=\"color" + counter + "\" />Yellow

<input id=\"color-green" + counter + "\" type=\"radio\" name=\"color" + counter + "\" />Green

Additional Donation

5\" – $5004\" – $2503\" – $1002.5\" – $50
");
    }
});

Also, is there a way to clean up the super long line of jQuery towards the end of the function? I can't figure out how to keep the HTML on multiple lines without breaking the script.
Thanks.
jsFiddle: http://jsfiddle.net/aptwt/2/

A: For dynamically added elements, you'll need to use delegated events with the on function:
HTML

    5" – $500
    4" – $250
    3" – $100
    2.5" – $50

jQuery
$(function() {
    $("#button-container").on('click', ".button", function(e) {
    ...
    });
});

A: The issue here is that those new buttons don't have event listeners attached to them. When you write $('.button').click(...), jQuery goes through and attaches an onClick event listener to each element with the button class. Those new elements weren't present on the page when that happened, though.
So, you have to options here. One, you can add the event listener again, but that's not DRY or optimal. Two, you can attach the event listener to a parent element and take advantage of event bubbling using jQuery.on() like so:

 /* ... */

$('#additional-donation').on('click', '.button', function(e) {
    var amount = $(e.target).data('value');
    /* ... */
});

Edit: Looks like I was beaten to the punch here. As for your additional questions about formatting that better, you can build the element incrementally by creating the parent, appending child elements, and inserting the parent into the page. Just be sure to do all of that work in JavaScript before inserting the whole thing into the page in one step. That minimizes the amount of DOM manipulation.
var additional = $('div#additional-donation');
additional.append(/* ... */);
$('#donationTarget').before(additional);


text:
Q: Partial derivative of a distribution as a directional limit I would like to show that $$\lim_{h\to 0}\frac{\tau_{he_j}T-T}{h}=\partial_{x_j}T$$ for every distribution $T\in\mathcal{D}'(\mathbb{R})$, where $\tau_{he_j}\varphi(x)=\varphi(x-he_j)$ and $e_j$ is an element of the canonical basis of $\mathbb{R}^n$.
Taking a function $\varphi\in C_0^\infty(\mathbb{R})$, we have $$\lim_{h\to 0}\left\langle\frac{\tau_{he_j}T-T}{h},\varphi\right\rangle=\lim_{h\to 0}\left\langle T,\frac{\tau_{-he_j}\varphi-\varphi}{h}\right\rangle,$$ but the continuity is only guaranteed over $C_K^\infty(\mathbb{R})$ for $K$ compact, so I don't know how to exchange the limit and the distribution.

A: For distributions acting on $\mathcal{D}(\Omega)=\mathcal{C}^\infty_c(\Omega)$ (smooth functions with compact support in $\Omega$, one may appeal to the mean value theorem.
Since
$$\lim_{h\to 0}\left\langle\frac{\tau_{he_j}T-T}{h},\varphi\right\rangle=\lim_{h\to 0}\left\langle T,\frac{\tau_{-he_j}\varphi-\varphi}{h}\right\rangle,$$
It is enough to show that $h^{-1}(\tau_{he_j}\phi-\phi)$ converges to $\partial_{x_j}\phi$ in $\mathcal{C}^\infty_c(\Omega)$ for any $\phi\in\mathcal{C}^\infty_c(\Omega)$.
The mean value theorem implies that every $\psi\in\mathcal{D}(\Omega)$ is Lipschitz. Another application of the mean value theorem show that there is a constant $C=C(\phi,\alpha)$ such that
\begin{align*}
    \Big|\frac{\partial^\alpha\phi(x)-\partial^\alpha\phi(x-he_j)}{h} - \partial_{x_j}\partial^\alpha\phi(x)\Big| &=|\partial_{x_j}\partial^\alpha\phi(x-t\theta h)-\partial_{x_j}\partial^\alpha\phi(x)|\\
    &\leq C|h|\xrightarrow{h\rightarrow0}0
  \end{align*}
where $\theta=\theta(h,x)\in (0,1)$.
For distributions acting on the Schwartz space, the proof is similar but a little more involved.


text:
Q: SKSpriteNode showing up in iOS 8, not in iOS 7 I have a SKSpriteNode named ship, it's created like so :
ship = [SKSpriteNode spriteNodeWithTexture:[SKTexture textureWithImageNamed:@"Spaceship"]];
ship.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:ship.frame];
ship.xScale = .5;
ship.yScale = .5;
ship.alpha = 1.0f;
ship.position = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
[self addChild:ship];

The ship shows up fine on the iOS 8 simulator and on my iPhone 5 running iOS 8, but is invisible on iOS 7.
In the update method I put these logs :
NSLog(@"Ship : %@", ship);
NSLog(@"Image : %@", ship.texture);
NSLog(@"Alpha : %.2f", ship.alpha);
NSLog(@"Parent : %@", ship.parent);

And I get this output :
Ship : <SKSpriteNode> name:'(null)' texture:[<SKTexture> 'Spaceship' (100 x 100)] position:{160, 284} size:{25, 25} rotation:0.00
Image : <SKTexture> 'Spaceship' (100 x 100)
Alpha : 1.00
Parent : <SKScene> name:'(null)' frame:{{0, 0}, {320, 568}}

Everything there seems to be in order, and this same log gets repeatedly called every update until the ship, which is not visible at all, flies off screen and code is called to remove it and everything else.
Without any user interaction, on iOS 8, what happens with the ship is it appears in the middle of the screen, moves up, then when it exits the frame the game is over. As far as I can tell, the exact same thing is happening on iOS 7, except the ship is invisible. The frame's correct, it responds to user interaction, it's just not showing up.

A: XCode 6 is in beta right now. It could possibly be an issue. You should try running the same code on XCode 5 with the iOS 7 simulator or a device.
Also, you can file a bug report with Apple here.


text:
Q: Converting matrix into im object from package spatstat - rows are in reverse first time user here. I am converting matrix into im object from package spatstat. However, top left value from the matrix mat[1,1] is written in the down left corner of the image e.g. the im function reads the rows of the matrix from top to bottom but writes them into im starting from bottom. Tried to specify yrow argument of im() to be seq() in reverse order but still same result.Suggestions how to fix this?
    require(spatstat)

    mat <- matrix(seq(1,20, by=1), nrow=4, ncol=5)
    print(mat)
    im <- im(mat, xcol = seq(1,5), yrow = seq(4,1))
    plot(im, axes = T)

A: There are two ways around this. In the latest development version of spatstat from github you can transform between different layouts. See help(transmat) for details. The layout you are providing is called 'European' and the layout used for spatstat is called 'spatstat', so you can do:
require(spatstat)
mat <- matrix(seq(1,20, by=1), nrow=4, ncol=5)
m <- transmat(mat, from = 'European', to = 'spatstat')
i <- im(m)
plot(i, axes = TRUE)

If you don't have the development version of spatstat you can simply do:
require(spatstat)
mat <- matrix(seq(1,20, by=1), nrow=4, ncol=5)
m <- mat[4:1,]
i <- im(m)
plot(i, axes = TRUE)


text:
Q: What happens to a single quark in lattice QCD simulations? I understand that if a pair quark/antiquark, out of the vacuum, tries to separate then the energy increases, another pair is produced, and we finish with two mesons or generically two hadron jets. But in numerical simulations we can just put a single quark and calculate the field, can we? What does it happen, does the total energy diverge? Or does it increases up to, say, some "constituient" mass?

A: As usual with these things, the presence of QFT and a non-Abelian gauge theory makes life hard, so let's take the prototypical theory that we can actually calculate with easily: Maxwell's equations.
The question is then something like "what happens if I put a single electron in a (classical) lattice simulation?". Immediately, one realises that this question is nonsense because Maxwell's equations only define the time evolution of physical states, which in this case implies things that satisfy Gauss' law (which is a constaint!): $$\nabla \cdot E = \rho.$$ In other words, in a simulation one must start with a physical state before one can run it. The Gauss constraint can be solved in this case, and gives the obvious $1/r^2$ decaying $E$ field.
At this point, we can zoom back out to QCD, and think about what changes. Solving for the Gauss constraint (i.e. finding an element of the physical Hilbert space) is now highly non-trivial, but heuristically we can have a guess at what might go wrong. The basic problem (as Scott Carnahan points out in the comments) is anti-screening. The colour field self-interacts and gets stronger at larger $r$ --- so the total energy diverges, which does not correspond to any element of the physical Hilbert space.
Incidentally, this general problem of needing to solve a constraint equation before being able to start a simulation is quite hard, and numerically one has to be quite clever to avoid instabilities --- many time evolution codes are only stable if you start them with things that satisfy the gauge constraints. Apart from gauge field simulations, simulations of GR also have this problem.

A: The total energy diverges, but you can't simulate a single static colored source because this conflicts with periodic boundary conditions. You need to have the box color neutral. The easiest way to do this is to put a color source and antisource far apart, and this was the situation in the earliest lattice QCD simulations.
The color fields in these simulations run in a narrow tube from the source to the antisource. The energy diverges as a linear function of the separation, and the coefficient of the divergence is the QCD string tension. In a simulation with dynamical quarks, quarks will pop out of the vacuum to screen the two sources, so that they will be noninteracting at long distances.


text:
Q: jQuery ajax is not working when send post request i try to use ajxt to send post request to my restful service
here is my ajax code
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
//xmlhttp.open("GET","http://192.168.1.100:8080/MapDemo/service/add?name=hieugie333&longitude=123&latitude=321",true);
//xmlhttp.send();
//document.getElementById("message").innerHTML=xmlhttp.responseText;
var JSONObject= {"name":name, "longitude":lng,"latitude":lat };
var jsonData = JSON.parse( JSONObject );

var request = $.ajax({
  url: "http://192.168.1.100:8080/MapDemo/service/add",
  type: "POST",
  contentType: "application/json; charset=utf-8",
  data: jsonData,
  dataType: "json"
});

can anyone help me in this case ?

A: var JSONObject= {"name":name, "longitude":lng,"latitude":lat };

That is a JavaScript object, not a JSON text.
var jsonData = JSON.parse( JSONObject );

That will error (or return null) because you aren't passing it a string containing a JSON text.
Your later code is expecting a string containing a JSON text though.
You want JSON.stringify not JSON.parse.

A: You need to change your "JSON.parse" to "JSON.stringify". You called the opposite function that you should have.


text:
Q: Change JavaScript in TypeScript I would like to translate this code into actual TypeScript. Could you help me there?
import mongoose, { Promise } from 'mongoose';
Promise = global.Promise;

const db = {};

db.mongoose = mongoose;

db.user = require("./user.model");
db.role = require("./role.model");

db.ROLES = ["user", "admin", "moderator"];

export default db;

A: It would be great if you'd provide us with what you have tried and achieved so that it is easier to modify your code.
A  way to do this would be to type this in a TypeScript file in an editor that provides linting for TypeScript like Visual Studio Code. Then check all the errors and fix them.


text:
Q: PHP function to detect real browser Is there any way to detect if the user is using a real browser?
I am able to get user agent string from $_SERVER['HTTP_USER_AGENT']. But I am not sure if it was a real browser . Can we do anything at the php side to see if its real browser?

A: No, you cannot reliably detect if a request was sent be a "real browser". (Assuming with "real browser" you mean something as a chrome/firefox/safari installed on a standard consumer OS and not something like curl, an ajax call or a crawler etc.)
Thats because the user-agent is nothing but a http header field. You can easily fake it. E.g. sending the following request using curl would look on your server as if I used a regular Chrome 44 on a Mac:
curl -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36" http://your-website.com

But apart from the fact that the user-agent header is not reliable: You can of course use the field to decide whether the request was issued by an "expected" client. In 99.9% of all requests you will find the "real" client in the user agent header. But you shouldn't make any security-sensitive functions dependent on it.


text:
Q: VueJS Best Approach to Random Slug Based URLs I have a Vue component that renders blog posts. It currently just loads a collection of posts and renders them to the UI. This all works great.
Each of these posts has a slug, i.e. the-best-post-ever.
I'd like to enable my blog component to be able to read that value (or be passed it) and render that individual post instead of the list.
So visiting the blog would be something like http://example.com/blog whereas an individual post would be http://example.com/blog/the-best-post-ever.
What's the best way of handling this?

A: So it turns out this is extremely simple.
I updated my router:
name: 'blog',
title: 'Blog',
path: '/blog/:slug?',
component: () => import(/* webpackChunkName: "blog" */ './views/Blog.vue'),
meta: {
    isMain: true,
    public: true,  // Allow access to even if not logged in
    requireAdmin: false,
},

And now in the Blog component:
mounted() {
    console.log(this.$route.params.slug);
},

I can now ping the slug off to the server API and get this post.
In my Blog component I store this in a local variable:
created() {
    this.slug = this.$route.params.slug;
},

And pass this onto the actual blog rendering component like this:
<BlogReaderComponent category="news" :slug="slug" />

The blog reader component can then simply ignore any category variable and render a single post as opposed to a collection of posts.
I switched from mounted() to created() as in order for this data to be available early enough in the life-cycle so that when the <BlogReaderComponent is created this value is properly initialised.


text:
Q: Obtain the number of occurrences a decision tree path has been used when classifying data I am trying to obtain the number of occurrences a decision tree path is used to classify an instance.
For example, suppose I have the following rules (not sure if they make sense):

*

*Rule 1: [x<3 and y<5 => 'Low']

*Rule 2: [x<3 and x>1 and y<5 => 'Low']

*Rule 3: [x<3 and y>2 and y<5 => 'Low']

*Rule 4: [x<6 and y<8 => 'Medium']

*Rule 5: [x<10 and y<10 => 'High']

Now, suppose I have 10 test set samples. I want something like this given this test set and the above rules:

*

*Rule 1 has been used 2 times,

*Rule 2 has been used 2 times,

*Rule 3 has been used 1 times,

*Rule 4 has been used 3 times,

*and  Rule 5 has been used 2 times

How to tackle this using Python?

A: Do you want something like this:
import random

x_num=[random.randint(1,11) for _ in range(10)]
y_num=[random.randint(1,11) for _ in range(10)]

def func(xn,yn):
    rule_1=0
    rule_2=0
    for x,y in zip(xn,yn):
        if x>2 and y<3:
            rule_1+=1
        elif x<4 and y>2:
            rule_2+=1
    return rule_1,rule_2

print(func(x_num,y_num))

?

A: If you're not familiar with it, I recommend using the sklearn Python package and more precisely, the sklearn.tree.DecisionTreeClassifier class. Here are the API Documentation and the user guide.
This page should help you solve your problem as it gives more detail about the decision process and how to retrieve the path used to classify a sample.
Sorry if this answer doesn't solve your problem right away but it should get you on the way :)


text:
Q: segmentation result to image I performed training for segmentation, and the result of the prediction was as follows.

675124 6 675635 8 676146 11 676657 13 677168 16 677679 17 678191 18
678703 19 679214 20 679726 21 680238 21 680749 22 681261 23 681773 23
682284 24 682796 24 683308 24 683820 24 684332 24 684845 23 685357 24
685869 23 686381 23 686894 20 687406 19 687919 17 688432 16 688944 15
689457 14 689970 11 690485 6 1195831 2 1196338 13 1196847 18 1197358
21 1197869 23 1198380 25 1198892 26 1199403 28 1199915 29 1200427 29
1200938 30 1201449 31 1201961 32 1202473 9 1202488 17 1202985 8
1203002 15 1203496 8 1203515 14 1204008 7 1204034 7 1204520 7 1204548
5 1205032 6 1205061 4 1205544 6 1205573 4 1206056 6 1206085 4 1206568
6 1206598 3 1207080 7 1207110 3 1207592 7 1207621 4 1208104 8 1208133
4 1208616 9 1208645 3...

How do I save this result as an image?
I'm working on python + pytorch.
The code with the result output is as follows.
for test_input in [test_input_files1, test_input_files2, test_input_files3]:
        preds = np.zeros((len(test_input), 2, 512, 512), dtype=np.float32)
        for augmentation in [0,1,3,5]: #[0,1,2,3,4,5]
            model = smp.UnetPlusPlus(encoder_name='timm-efficientnet-b8', encoder_weights='imagenet', in_channels=1, classes=3).to(device)
            model= nn.DataParallel(model)
            for weight_path in weight_paths:
                model.load_state_dict(torch.load(weight_path)['model'])
                model.eval()
                test_dataset = BodyDataset(X=test_input, y=None, mode='test', augmentation=augmentation)
                test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False, num_workers=8, pin_memory=True)

                for idx, X in enumerate(tqdm(test_loader, total=len(test_loader))):
                    X = torch.tensor(X, dtype=torch.float16).cuda()
                    with torch.cuda.amp.autocast():
                        pred = F.softmax(model(X)).detach().cpu().numpy()[:,1:]
                        if augmentation == 1:
                            pred = np.flip(pred, axis=2).copy()
                        elif augmentation == 2:
                            pred = np.flip(pred, axis=3).copy()
                        elif augmentation == 3:
                            pred = np.rot90(pred, -1, (2,3))
                        elif augmentation == 4:
                            pred = np.rot90(pred, -2, (2,3))
                        elif augmentation == 5:
                            pred = np.rot90(pred, -3, (2,3))
                        preds[idx*batch_size:(idx+1)*batch_size] += pred
        for i in tqdm(range(0, len(preds), 64)):
            cnt = cnt+1
            name = test_input_files[cnt-1]
            name = name[-9:]
            for label_code in [1,2]:
                sample = preds[i:i+64].copy()/40
                if label_code == 1:
                    sample = np.where(sample[:,0]>=threshold, 1,0)
                elif label_code == 2:
                    sample = np.where(sample[:,1]>=threshold, 2,0)
                tmp=[]
                for s in sample:
                    s = np.equal(s, label_code).flatten()*1
                    tmp+=s.tolist()
                enc = rle_to_string(rle_encode(np.array(tmp)))
                preds_string.append(enc)


text:
Q: Http 1.1 protocol validation Is there any service or library that can validate an http1.1 server?
I implemented a simple http server, and over a year or so I've been extending it as I need to such that I've got a pretty complete and functional http1.1 web/app server.
As a practical matter it works really well - e.g. it seems to serve things robustly to all the browsers I've tried, cUrl etc, but there are a million corner cases when you read the specs for http1.1. I'm sure I have all kinds of odd gremlins in there.
Is there a service that can make http requests to a server to validate the protocol, or a library that does this?

A: Jigsaw is the W3C's reference implementation of HTTP 1.1 http://www.w3.org/Jigsaw/
You can probably use that to compare responses between your server and Jigsaw. If it doesn't have its own blackbox test suite, you might have to go through the RFC and create your own suite.
There are further resources here: http://www.w3.org/Protocols/HTTP/Forum/#Sample
This includes a reference to at least one HTTP 1.1 client library. You might use that, or any other one with good compliance to build your own black box tests.

A: I haven't found anything comprehensive, but REDbot is useful for testing some of the subtleties of HTTP caching.


text:
Q: NuGet: what should go into TFS? I'm working on a customer project; they are hosting the TFS server.
I started work on an existing body of code, in particular one library which is a member of a solution and has been bound to TFS version control. (Little padlock icons appear on this project.)  I added a unit test project to go with it.  I believe that when I added the test project, I did not specify "bind to version control," and so I manually added the project to TFS.  That's all been fine.
I added NuGet package dependencies to both the library and the unit tests. In both cases, the only change in the TFS repo was a new packages.config file.  When the customer's build server builds, it grabs the packages from NuGet.  Customer is happy with this; perhaps they shouldn't be?
Then I created another application project, with its own solution, sharing some of the projects in the original solution.  When I created the new project, I did "bind to version control." I added the same package dependencies, but this time the solution got a new packages folder containing the package DLLs, and all were added to TFS; there was no packages.config file.
I found a link telling me how to "enable package restore" for the solution, and tried it; now I have the .nuget directory added to the solution; a repositories.config added to packages; and changes to the shared .csproj files, and I still have the package binaries queued up for checkin.
I think I'll need to start over with this new solution, but I want to do the right thing.  It's not clear to me if managing packages using only a packages.config is the right thing to do. I found a post discouraging the use of package restore.
I'm working with the Express edition of VS2013, if that makes a difference.

A: You should checkin the .nuget directory having the nuget.config file ,package.config file in the project, packages folder with repositories.config and the project file changes.
You should not checkin the binaries in package folder they will be downloaded during the build from nuget.


text:
Q: When I try to open a sheet from an android emulator , I get Unable to access document. Please make sure that you are connected to the internet I created the sheet and can append to it using the app in the emulator.  I am using an ACTION_VIEW intent with an url.  Seems to work on a real device.  If I try an intent to another address in the emulator it works.
 String url = "https://docs.google.com/spreadsheets/d/" + mSpreadsheetId + "/edit#gid=0";
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i);

I suspect the code does not clarify much.  I have enough security to create and add to the sheet in the same app with an emulator. I obviously have internet.  Am I missing a setting on Google sheets or something?
All I am trying to do is test on older sdk's.  this test is on api level 24 with the latest playstore libraries and the google sheets api.  But none of that has anything to do with this intent.

A: The issue is that the emulator needed the Google sheets app installed.  Whatever was launched for this intent was using the wrong url. For some reason I was under the impression that the intent launched a browser window.


text:
Q: How to enforce a second run for defining missing references? Extending the solution to my previous question I would like to tell LaTeX to run multiple times until the variable is defined. In the demo example, I want section A and C to be identical in output. Any idea?
\documentclass{article}

\usepackage{hyperref}
\usepackage{varioref}

\newcounter{mycounter}
\makeatletter
\newcommand{\defineAndPrintXX}[3]{%
  \refstepcounter{mycounter}%
  \begingroup\edef\x{\endgroup\noexpand\@namedef{#1@id}{FSR \themycounter}}\x
  \@namedef{#1@definition}{#2}

  \hypertarget{#1}{%
  \subsection{\csname#1@id\endcsname}\label{#1}}
  % use the definition, i.e. #2
  \csname#1@definition\endcsname

  #3
}

\newcommand{\referToXX}[1]{
    \protect\hyperlink{#1}{\csname#1@id\endcsname} (see section \vref{#1}) \newline
    \csname#1@definition\endcsname
}

\begin{document}

\section{A}
Test before definition: \referToXX{test-1}

\section{B}
\defineAndPrintXX{test-1}{Definition 1}{Bla bla}
\defineAndPrintXX{test-2}{Definition 2}{Bla bla}

\section{C}
Test after definition: \referToXX{test-1}

\end{document}

A: Using the package zref you can specify your own properties (not just page-number, value of counter that was incremented via \refstepcounter, etc) whose values are to be recorded when placing a (zref-)label for cross-referencing.
As long as each of your XX-thingies both creates another subsection and places a label for cross-referencing you don't need to specify a \hypertarget/\hyperlink as the hyperref-package will automatically create a target/destination for each subsection which—in case of placing a cros-referencing-label—can be accessed for creating a hyperlink via \hyperref[{⟨cross-referencing-label⟩}]{⟨text of the hyperlink⟩}.
\documentclass{article}

\usepackage{zref}
\usepackage{varioref}
\usepackage{hyperref}

\newcounter{XXcounter}

\makeatletter
\zref@newprop{XXid}{}%
\zref@newprop{XXdefinition}{}%
\newcommand{\defineAndPrintXX}[3]{%
  \refstepcounter{XXcounter}%
  \zref@setcurrent{XXid}{FSR\protect~\theXXcounter}%
  \zref@setcurrent{XXdefinition}{#2}%
  \par
  \subsection{FSR~\theXXcounter}%
  \@bsphack
  \begingroup
  \let\@bsphack\relax
  \let\@esphack\relax
  \label{#1}%
  \zref@labelbyprops{#1}{XXid,XXdefinition}%
  \endgroup
  \@esphack
  #2\par#3%
}%
\newcommand{\referToXX}[1]{%
  \zifrefundefined{#1}{\nfss@text{\reset@font\bfseries??}}{%
    \hyperref[{#1}]{%
      \zref@extractdefault{#1}{XXid}{}%
    } (see section \vref{#1})\newline
    \zref@extractdefault{#1}{XXdefinition}{}%
  }%
}%
\makeatother

\begin{document}

\section{Tests before definitions}

\noindent\verb|\referToXX{test-1}|:\\
\referToXX{test-1}

\noindent\verb|\referToXX{test-2}|:\\
\referToXX{test-2}

\section{Place of definitions}
\defineAndPrintXX{test-1}{Definition 1}{Bla bla}
\defineAndPrintXX{test-2}{Definition 2}{Bla bla}

\section{Tests after definitions}

\noindent\verb|\referToXX{test-1}|:\\
\referToXX{test-1}

\noindent\verb|\referToXX{test-2}|:\\
\referToXX{test-2}

\end{document}

If (for whatever reason) you insist in having another target/destination whose name corresponds to the name of the cross-referencing-label/to the first argument of \defineAndPrintXX, you can handle this via a zref-property as well:
\documentclass{article}

\usepackage{zref}
\usepackage{hyperref}
\usepackage{varioref}

\newcounter{XXcounter}

\makeatletter
\zref@newprop{XXid}{}%
\zref@newprop{XXdefinition}{}%
\zref@newprop{XXdestination}{}%
\newcommand{\defineAndPrintXX}[3]{%
  \refstepcounter{XXcounter}%
  \zref@setcurrent{XXid}{FSR\protect~\theXXcounter}%
  \zref@setcurrent{XXdefinition}{#2}%
  \zref@setcurrent{XXdestination}{#1}%
  \par
  \hypertarget{#1}{\subsection{FSR~\theXXcounter}}%
  \@bsphack
  \begingroup
  \let\@bsphack\relax
  \let\@esphack\relax
  \label{#1}%
  \zref@labelbyprops{#1}{XXid,XXdefinition,XXdestination}%
  \endgroup
  \@esphack
  #2\par#3%
}%
\newcommand{\referToXX}[1]{%
  \zifrefundefined{#1}{\nfss@text{\reset@font\bfseries??}}{%
    \hyperlink{\zref@extractdefault{#1}{XXdestination}{}}{%
      \zref@extractdefault{#1}{XXid}{}%
    } (see section \vref{#1})\newline
    \zref@extractdefault{#1}{XXdefinition}{}%
  }%
}%
\makeatother

\begin{document}

\section{Tests before definitions}

\noindent\verb|\referToXX{test-1}|:\\
\referToXX{test-1}

\noindent\verb|\referToXX{test-2}|:\\
\referToXX{test-2}

\section{Place of definitions}
\defineAndPrintXX{test-1}{Definition 1}{Bla bla}
\defineAndPrintXX{test-2}{Definition 2}{Bla bla}

\section{Tests after definitions}

\noindent\verb|\referToXX{test-1}|:\\
\referToXX{test-1}

\noindent\verb|\referToXX{test-2}|:\\
\referToXX{test-2}

\end{document}


text:
Q: Define arrays within array in Angular 2 and Typescript In Angular 2 I was wondering if it was possible to define an array that has multiple other arrays in it. It is probably easier to just show what I mean:
I started out using this:
export class PaymentDetails {
     account: any[];
     bpNumber: number;
}

but this gave me the problem that when I populated it I couldn't really access the data in the account array, as I want more arrays inside of it.
So now i would like to define my class like this:
export class PaymentDetails {
    account: [
        debitAccount: [
            {
                debitAccountId: string;
                debitBankCode: string;
                debitBankName: string;
                debitCountryCode: string;
                debitAccountNumber: string;
                debitAccountHolder: string;
                debitContinous: string;
                debitDueDate: string;
                iban: string;
                bic: string;
            }
        ],
        ccAccount: [
            {
                ccAccountId: string;
                ccCompanyCode: string;
                ccNumber: string;
                ccStart: string;
                ccExpiry: string;
                ccDsbTransactionId: string;
                ccCardholderName: string
            }
        ]
    ];
    bpNumber: number;

}

Is this at all possible?
The class is getting populated with this InMemoryDataService
export class InMemoryDataService {
  createDb() {
let paymentDetailsDB = [
      {
        account: [
          {
            debitAccount: [
              {
                debitAccountId: '8736583',
                debitBankCode: '45345',
                debitBankName: 'KSK HGTT',
                debitCountryCode: 'DE',
                debitAccountNumber: '123453463',
                debitAccountHolder: 'A Berg',
                debitContinous: '',
                debitDueDate: '',
                iban: 'DE12344235',
                bic: '324645',
              },
              {
                debitAccountId: '6567456',
                debitBankCode: '55463453',
                debitBankName: 'GRDFE',
                debitCountryCode: 'DE',
                debitAccountNumber: '000123492',
                debitAccountHolder: 'A Berg',
                debitContinous: '',
                debitDueDate: '',
                iban: 'DE43523453',
                bic: '123547665',
              }
            ],

            ccAccount: [
              {
                ccAccountId: '23413',
                ccCompanyCode: '254345',
                ccNumber: '238857827368837',
                ccStart: '2010-10-05',
                ccExpiry: '2018-10-05',
                ccDsbTransactionId: '235231',
                ccCardholderName: 'Anne Berg',
              }
            ],
          }
        ],
        bpNumber: 4711,
      }
    ];
    return {paymentDetailsDB};
  }
}

A: Your definition should look like this:
anonymous type variant:
export class PaymentDetails {
  accounts:
  {
    debitAccounts:
    {
      debitAccountId: string;
      debitBankCode: string;
      debitBankName: string;
      debitCountryCode: string;
      debitAccountNumber: string;
      debitAccountHolder: string;
      debitContinous: string;
      debitDueDate: string;
      iban: string;
      bic: string;
    }[],

    ccAccounts:
    {
      ccAccountId: string;
      ccCompanyCode: string;
      ccNumber: string;
      ccStart: string;
      ccExpiry: string;
      ccDsbTransactionId: string;
      ccCardholderName: string
    }[],

    bpNumber: number;
  };
}

named types (you should use this! :])
export class DebitAccount {
  Id: string;
  BankCode: string;
  BankName: string;
  CountryCode: string;
  Number: string;
  Holder: string;
  Continous: string;
  DueDate: string;
  iban: string;
  bic: string;
}

export class CcAccount {
  Id: string;
  CompanyCode: string;
  Number: string;
  Start: string;
  Expiry: string;
  DsbTransactionId: string;
  CardholderName: string
}

export class Account {
  debitAccounts: DebitAccount[];
  ccAccounts: CcAccount[];
  bpNumber: number;
}

export class PaymentDetails {
  account: Account[];
}

A: Nested array could be defined as the following:
  items = [
     {name:'xyz', subMenuItem:[{name:'abc'}, {name:'cde'}], icon:'home'},
     {name:'pqr', subMenuItem:[{name:'abc'}, {name:'cde'}], icon:'home'},
    ];


text:
Q: Using Float instead of float (Primitive type) when implementing Parcelable Requirement: Find out if price is null. Since a primitive float data type cannot be checked for null since its always 0.0, I opted out to use Float instead, as it can be checked for null.
public class QOptions implements Parcelable {
    public String text;
    public Float price;
}

protected QOptions(Parcel in) {
    text = in.readString();
    unit_price = in.readFloat();
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(this.text);
    parcel.writeFloat(this.price);
}

However, since the class also implements Parcelable, the writeToParcel crashes with the following exception:

Attempt to invoke virtual method 'float java.lang.Float.floatValue()' on a null object reference

And the exception points to this line:

parcel.writeFloat(this.price);

How can I use the Float data type along with writeToParcel and not cause the exception? Or is there a better way to accomplish my requirement? I just need the price to be null if it's null.

A: You can handle it in the below manner.
@Override
public void writeToParcel(Parcel dest, int flags) {
    if (price == null) {
        dest.writeByte((byte) (0x00));
    } else {
        dest.writeByte((byte) (0x01));
        dest.writeFloat(price);
    }
}

To read the value of float -
unit_price = in.readByte() == 0x00 ? null : in.readFloat();

A: Decimal types have a number of special values: NaN, negative and positive infinities. You can use those values to indicate null:
if (price == null) {
  parcel.writeFloat(Float.NaN);
} else {
  parcel.writeFloat(price);
}

And when reading:
float p = parcel.readFloat();
if (Float.isNaN(p)) {
  price = null;
} else {
  price = p;
}

NaN means "not a number", so it kind-of fits thematically for serializing things.
Unlike the solution, provided by @Kapil G, this approach does not waste additional 4 bytes for nullability flag (each call to writeByte() actually stores entire int in Parcal for performance reasons).

A: For parceling Float these two method calls are safe:
dest.writeValue(price);
in.readValue(null);

For parceling any parcelable type you can use this:
SomeType value; // ...
dest.writeValue(value);
in.readValue(SomeType.class.getClassLoader());

List of parcelable types can be found in Parcel docs.
Pros

*

*One line for each read and write.

*You don't have to worry about manually differentiating between null and a float when parceling and unparceling. It's done for you internally.

*Can express NaN and infinities.

How it works
Here's the relevant part of Parcel source code:
public class Parcel {
    private static final int VAL_NULL = -1;
    private static final int VAL_FLOAT = 7;

    public final void writeValue(Object v) {
        if (v == null) {
            writeInt(VAL_NULL);
        } else if (v instanceof Float) {
            writeInt(VAL_FLOAT);
            writeFloat((Float) v);
        } // ...
    }

    public final Object readValue(ClassLoader loader) {
        int type = readInt();

        switch (type) {
            case VAL_NULL:
                return null;

            case VAL_FLOAT:
                return readFloat();

            // ...
        }
    }
}

Note that for Float (and other boxed primitives) the loader parameter is unused so you can pass null.
Explore the source here: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/os/Parcel.java


text:
Q: TypeError: '>=' not supported between instances of 'datetime.date' and 'str' My pandas df3 looks like this:
df3 = pd.DataFrame([['23.02.2012', '23.02.2012', 'aaa'], ['27.02.2014', '27.02.2014', 'bbb'], ['17.08.2018', '17.08.2018', 'ccc'], ['22.07.2019', '22.07.2019', 'ddd']], columns=['date', 'period', 'text'])

I want to make column period display the following periods if the dates correspond. Since some date values were formatted with timestamp and some not, it didnt create the correct (without timestamp) period values. That is why i did df3['question_date'].dt.date
df3['date'] = pd.to_datetime(df3['date'], errors = 'coerce')
df3['question_date'] = df3['question_date']
df3['period'] = df3['date']
col_name = 'period'
strt_col = df3.pop(col_name)
df3.insert(5, col_name, strt_col)

date1 = pd.Timestamp('1990-10-14').date()
date2 = pd.Timestamp('1994-11-10').date()
date3 = pd.Timestamp('1999-10-1').date()
date4 = pd.Timestamp('2004-6-13').date()
date5 = pd.Timestamp('2009-8-30').date()
date6 = pd.Timestamp('2014-10-14').date()
date7 = pd.Timestamp('2019-11-26').date()
date8 = pd.Timestamp('2021-9-20').date()
mask1 = (df3['question_date'] >= 'date1') & (df3['question_date'] < 'date2')
mask2 = (df3['question_date'] >= 'date2') & (df3['question_date'] < 'date3')
mask3 = (df3['question_date'] >= 'date3') & (df3['question_date'] < 'date4')
mask4 = (df3['question_date'] >= 'date4') & (df3['question_date'] < 'date5')
mask5 = (df3['question_date'] >= 'date5') & (df3['question_date'] < 'date6')
mask6 = (df3['question_date'] >= 'date6') & (df3['question_date'] < 'date7')
mask7 = (df3['question_date'] >= 'date7') & (df3['question_date'] < 'date8')
df3.loc[mask1, 'leg_per'] = '1990-1994'
df3.loc[mask2, 'leg_per'] = '1994-1999'
df3.loc[mask3, 'leg_per'] = '1999-2004'
df3.loc[mask4, 'leg_per'] = '2004-2009'
df3.loc[mask5, 'leg_per'] = '2009-2014'
df3.loc[mask6, 'leg_per'] = '2014-2019'
df3.loc[mask7, 'leg_per'] = '2019-2021'
.
.
.

At mask1 it throws error
TypeError: '>=' not supported between instances of 'datetime.date' and 'str'

Original question: preventing timestamp creation in to_datetime() formatting in order to group by periods

A: Here's a slighly modified version of your example,
import pandas as pd

df3 = pd.DataFrame([['23.02.2012', 'aaa'], ['27.02.2014', 'bbb'],
                    ['17.08.2018', 'ccc'], ['22.07.2019', 'ddd']],
                   columns=['date', 'text'])

# ensure datetime64[ns] type
df3['date'] = pd.to_datetime(df3['date'], dayfirst=True)

Note that for given date/time format in the example, you need to specify that the day comes first if you don't provide a format. Also, use errors='coerce' only if you're know what you're doing - I always prefer errors to be raised first.
Now let's create a mask for a certain date range. Note that pandas is clever enough that you can use dates as strings (see also Indexing, can be applied to comparisons as well):
date1 = '2010-10-14'
date2 = '2014-11-10'
m = (df3['date'] >= '2010-10-14') & (df3['date'] < '2014-11-10')

df3.loc[m, 'leg_per'] = '2010-2014'

The dummy df then looks like
df3
        date text    leg_per
0 2012-02-23  aaa  2010-2014
1 2014-02-27  bbb  2010-2014
2 2018-08-17  ccc        NaN
3 2019-07-22  ddd        NaN

In general, if you work with date/time in pandas, and want to save yourself some trouble: use the datetime64 data type pandas has to offer. Avoid Python's datetime, date and time class. It will cause issues as the one you're experiencing and reduce functionality you have at hand.


text:
Q: Flot jQuery start xaxis label NOT located below first tick In xAxis labels,  I have a set the graph to display the labels every 3 days by setting below in xaxis:
 xaxis: {
        mode: "time",
        tickSize: [1.9, "day"],

Here is the jsfiddle.
The problem is the first label '01 Jun' is NOT located under the first tick but on the second tick instead.
Is there a way to force the label under the first tick?
I have tried changing the grid option 'minBorderMargin' to no avail.
Thank you for your help in advance!

A: First of all, the labels are under the ticks. You can see that when you change the ticklength:
tickLength: 5,

Do you mean the ticks (and therefore ticklabels) are not under the bars? Of course they are not, because you have one bar every day and one tick every 1.9 days.
If you want a label every three days, you have to set the ticksize to three days:
tickSize: [3.0, "day"],

And if you want the first tick to be under the first bar, you have to set a minimum value for the axis:
min: gd(2018, 6, 1)

See this updated fiddle for a full example.


text:
Q: Call to a member function links() on array in laravel 5.7 I am using pagination in Laravel 5.7 to build an application. However, when I add a pagination link on view, it shows an error Call to a member function links() on array.
This is what the array looks like when i try to echo it in the view:
{
  "current_page": 1,
  "data": [
    {
      "stk_id": 7,
      "stk_name": "shafi",
      "stk_last_name": "razai",
      "stk_email": "shafi@gmail.com",
      "stk_phone": "1234567890",
      "stk_gender": "male"
    },
    {
      "stk_id": 9,
      "stk_name": "ali",
      "stk_last_name": "ahmadi",
      "stk_email": "ali@gmail.com",
      "stk_phone": "0987654321",
      "stk_gender": "male"
    }
  ],
  "first_page_url": "http://localhost/accountingLaravel/countings?page=1",
  "from": 1,
  "last_page": 2,
  "last_page_url": "http://localhost/accountingLaravel/countings?page=2",
  "next_page_url": "http://localhost/accountingLaravel/countings?page=2",
  "path": "http://localhost/accountingLaravel/countings",
  "per_page": 2,
  "prev_page_url": null,
  "to": 2,
  "total": 4
}

This is my controller index fuction
public function index(){

    $countings = DB::table('countings')
                ->join('stackholders', 'countings.stk_id', '=', 'stackholders.stk_id')
                ->orderBy('countings.c_date', 'desc')
                ->select('stackholders.*')
                ->paginate(2);

    $countings = DB::select('SELECT countings.* , stackholders.stk_id , stackholders.stk_name ,stackholders.stk_last_name FROM countings INNER JOIN stackholders ON countings.stk_id = stackholders.stk_id order by c_id desc');

    $stackholders = Stackholder::orderBy('stk_name')->get();

    $a = array(
        'countings' => $countings ,
        'stackholders' => $stackholders
    );
    return view('countings.index')->with($a);

}

And this is in my view page where I loop through the code
@if (count($countings)> 0 )
    @foreach ($countings as $counting)

           {{$counting->stk_name . " " . $counting->stk_last_name}}
           {{$counting->c_desc}}
           {{$counting->c_date}}
           {{$counting->c_state}}
           {{$counting->c_value}}

     @endforeach

     {{ $countings->links() }}

Can someone please suggest how to solve this issue?


text:
Q: Kivy Progress-Bar will not update until after 100% completion Kivy's Progress-bar is only graphically updating once the function that is updating its internal values is fully finished (100% completion).  I am using it to update a database of names and values, and want it to show the progress of the update.
As per other similar problems, all the below methods have been tried and failed:
(Clock.schedule_interval,Clock.schedule_once,Clock.create_trigger,@mainthread,Clock.schedule_once(partial(func))

Their remnants can be seen in the commented out sections below
There is a button on another page that I press which triggers update_database().  update_database calls updateLoadingScreen to change the values on the progress bar and label of the numerical percent done.  In isolation, it appears this function works.  However, running it in the update_database() causes the UI updates to freeze, until it simply outputs 100% completion.  Clock.schedule_interval pauses until 100% is reached, both internally and externally to the update_database function, Clock.schedule_once also waits until 100% is reached before doing anything.  Clock.create_trigger appears to not call anything except when it is instantiated.  Functools partial() doesn't change any behaviors. @mainthread gives Error:'mainthread' is not defined.
It doesn't appear to be a timing issue, as 0.2 seconds is good enough for it to update values in other situations.  However, it really does appear to be locked into the process and unable to update the UI, even though the UI parameters are modified.
from kivy.uix.label import Label
from kivy.uix.progressbar import ProgressBar
from functools import partial

class UpdatePage(GridLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        #This part puts the series into a pandas dataframe
        self.df=getAllSeries()
        self.allserieslen=len(self.df)

        self.progress_bar=ProgressBar(max=self.allserieslen-1,value=0)
        self.add_widget(self.progress_bar)

        self.progress_label=Label(text='0%')
        self.add_widget(self.progress_label)

        #self.update_progress_trigger = Clock.create_trigger(self.updateLoadingScreen(self.currentseries,self.serieslen),-1)

        #Clock.schedule_interval(lambda x:self.updateLoadingScreen(self.currentseries,self.serieslen),.2)
        #This works, in a vaccum

    def update_database(self):
        #screenupdate=Clock.schedule_interval(lambda x:self.updateLoadingScreen(self.currentseries,self.serieslen),.2)
        for rownum in range(self.serieslen):
            chapters,name=findSingleSeriesChapter(self.df.at[rownum, 'URL'])
            self.currentseries=rownum

            #failed ways to update the screen (including the schedule and unscedule above and below)
            self.updateLoadingScreen(self.currentseries,self.serieslen)
            #Clock.schedule_once(lambda x:self.updateLoadingScreen(self.currentseries,self.serieslen),0.2)
            #self.update_progress_trigger()
            #Clock.schedule_once(lambda x:partial(self.updateLoadingScreen(self.currentseries,self.serieslen)),0.2)
            print('loop done',self.currentseries)
        #Clock.unschedule(screenupdate)

    #@mainthread
    def updateLoadingScreen(self,rownum,serieslen):
        print("Event has been triggered")
        self.progress_bar.value=rownum
        #self.remove_widget(self.progress_bar)
        #self.add_widget(self.progress_bar)
        percentage=str(round((rownum)/(serieslen-1)*100,1))

        self.progress_label.text=f"{percentage}%"
        #self.remove_widget(self.progress_label)
        #self.add_widget(self.progress_label)

A: Kivy code that updates the UI should run on the mainthread, else the app "freezes" till the current running action is done. Try adding the @mainthread decorator to your progress bar code
from kivy.clock import mainthread