text:
Q: How to group by every n minutes and also avoid leakage in pandas? I have got the dataset as below:
ID   Min_date                   Max_date                   time_diff_in_sec Name
1    2023-01-01 12:00:00.000    2023-01-01 12:00:01.000    1                A
2    2023-01-01 12:00:00.000    2023-01-01 12:00:10.000    10               A
3    2023-01-01 12:00:00.000    2023-01-01 12:10:00.000    600              A
4    2023-01-01 12:00:00.000    2023-01-01 12:15:00.000    900              A
5    2023-01-01 12:00:00.000    2023-01-01 12:15:01.000    901              A
6    2023-01-01 12:15:00.000    2023-01-01 12:16:00.000    60               A
7    2023-01-01 12:15:00.000    2023-01-01 12:17:01.000    121              A
8    2023-01-01 12:15:00.000    2023-01-01 12:15:02.000    2                A

I wanted to groupby every 10 mins for each Name and also take care of the residual time that has happened post 15 mins. The data after processing should look like:
Min_date                   Max_date                   time_diff_in_sec(sum)    Name   Count
2023-01-01 12:00:00.000    2023-01-01 12:09:59.999    1808(1+2+599+599+599)    A      5 (ID->1,2,3,4,5)
2023-01-01 12:10:00.000    2023-01-01 12:19:59.999    787(1+301+302+60+121+2)  A      6 (ID->3,4,5,6,7,8)


text:
Q: Check if the file is a valid CSV file I have a CSV file, which is converted from a UNICODE to CSV file. I did this to process UTF-8 character. So here is the problem, I have a CSV file but when I tried to upload it, seems like it is not accepted as a CSV file.  The csv file is somewhat read as a UNICODE from it's origin. When I used this condition to validate the file, it is bypass and generate an error, This condition works just fine on other instances.
 $mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
 if( !empty($_FILES['csv_attach']['tmp_name']) && in_array($_FILES['csv_attach']['type'],$mimes))
{
                          /* some codes */
}

Now the question is that, how can you validate if the file is a valid CSV file, not a UNICODE text file? Or how can you validate if the file is a UNICODE TEXT? That's what I am thinking for the solution, just to validate the file if it is a UNICODE text or not. Am I missing something?

A: Unicode is standard of encoding text.
Mime types, like text/csv are a method of conveying what is in a file.
You're mixing up two ideas here and your question makes no sense.
There is no official standard for CSV files, though rfc4180 might help.
There might be services that can validate the content of your CSV as discussed in this question: known services to validate csv file

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spark ML Pipeline Logistic Regression Produces Much Worse Predictions Than R GLM I used ML PipeLine to run logistic regression models but for some reasons I got worst results than R. I have done some researches and the only post that I found that is related to this issue is this . It seems that Spark Logistic Regression returns models that minimize loss function while R glm function uses maximum likelihood. The Spark model only got 71.3% of the records right while R can predict 95.55% of the cases correctly. I was wondering if I did something wrong on the set up and if there's a way to improve the prediction. The below is my Spark code and R code-
Spark code
partial model_input
label,AGE,GENDER,Q1,Q2,Q3,Q4,Q5,DET_AGE_SQ
1.0,39,0,0,1,0,0,1,31.55709342560551
1.0,54,0,0,0,0,0,0,83.38062283737028
0.0,51,0,1,1,1,0,0,35.61591695501733

def trainModel(df: DataFrame): PipelineModel = {
  val lr  = new LogisticRegression().setMaxIter(100000).setTol(0.0000000000000001)
  val pipeline = new Pipeline().setStages(Array(lr))
  pipeline.fit(df)
}

val meta =  NominalAttribute.defaultAttr.withName("label").withValues(Array("a", "b")).toMetadata

val assembler = new VectorAssembler().
  setInputCols(Array("AGE","GENDER","DET_AGE_SQ",
 "QA1","QA2","QA3","QA4","QA5")).
  setOutputCol("features")

val model = trainModel(model_input)
val pred= model.transform(model_input)
pred.filter("label!=prediction").count

R code
lr <- model_input %>% glm(data=., formula=label~ AGE+GENDER+Q1+Q2+Q3+Q4+Q5+DET_AGE_SQ,
          family=binomial)
pred <- data.frame(y=model_input$label,p=fitted(lr))
table(pred $y, pred $p>0.5)

Feel free to let me know if you need any other information. Thank you!
Edit 9/18/2015 I have tried increasing the maximum iteration and decreasing the tolerance dramatically. Unfortunately, it didn't improve the prediction. It seems the model converged to a local minimum instead of the global minimum.

A:
It seems that Spark Logistic Regression returns models that minimize loss function while R glm function uses maximum likelihood.

Minimization of a loss function is pretty much a definition of the linear models and both glm and ml.classification.LogisticRegression are no different here. Fundamental difference between these two is the way how it is achieved.
All linear models from ML/MLlib are based on some variants of Gradient descent. Quality of the model generated using this approach vary on a case by case basis and depend on the Gradient Descent and regularization parameters.
R from the other hand computes an exact solution which, given its time complexity, is not well suited for large datasets.
As I've mentioned above quality of the model generated using GS depends on the input parameters so typical way to improve it is to perform hyperparameter optimization. Unfortunately ML version is rather limited here compared to MLlib but for starters you can increase a number of iterations.


text:
Q: returning a string from askopenfilename() to a entry box I have seen many postings on the use of askopenfilename(), however I still can't seem to find anything to help me display the full file path in an entry box once I have selected said file.  below I have included where I have left off.
from tkinter import *
from tkinter.filedialog import askopenfilename

global a

def browse():
    a = askopenfilename(title='select new file')

root = Tk()

a = StringVar()

l = Label(root, text="new file: ")
l.pack()

e = Entry(root, width=25, textvariable=a)
e.pack()

b = Button(root, text="Browse", command=browse)
b.pack()

root.mainloop()

A: Inside your browse function the local variable a does indeed contain the full path to your file. THe issue is that you have to call the StringVar's .set() method, you can't just assign to the variable you bound to the StringVar. Replace a = askopenfilename(title='select new file') with a.set(askopenfilename(title='select new file')) and you will see the filename appear in the StringVar in your interface.
Please note that your program is not well-structured for a GUI interface task, but I presume at present your major difficulty is learning to use the primitives.


text:
Q: How do I check required fields using 'empty' in a field whose value is an integer? I'm trying to run a check of my required fields where i use the empty function. Unfortunately empty considers 0 to be empty and my values could be 0 and one in the radio button. I've tried to use !is_int(myvalue) and yet it didn't work.
Here is my code:
  <?php   $required_fields = array('menu_name', 'position', 'visible');
    foreach($required_fields as $fieldname) {
        if(!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && !is_int($_POST[$fieldname]))) {
            $errors[] = $fieldname;
        }
    }
?>

A: It appears you want to test a string to see if it is an integer.
Try using is_numeric
http://www.php.net/manual/en/function.is-numeric.php

A: if(!isset($_POST[$fieldname])  // not in the post
   || (empty($_POST[$fieldname]) && 0 != $_POST[$fieldname]) // empty but not zero
   || (int) $_POST[$fieldname] == '')) // not an integer
) {
  $errors[] = $fieldname;
}


text:
Q: Consuming service in jar using webservice I have services in a jar file created by spring mvc.
My question is how to consume this services through rest api in an other spring boot project .
Any help is highly appreciate.
my AppConfig :
package com.Taco;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan({"org.DAO","org.Service"})
public class AppConfig {

}

A: *

*Declare your jar as a dependency in your other spring project.

*In config class declare your service in @ComponentScan


text:
Q: Ordinary Chain Rule Confusion
Let $f$ be the function defined in Q1, and let $g$ be a function such that $g^\prime(x)=\sin(\sin(x+1))$ and $g(0)=2$. Find $(f\circ g)^\prime(0)$ and $(g\circ f)^\prime(0)$.
For $x\neq0$, the rules of differentiation give $f^\prime(x)=2x\sin(1/x)-\cos(1/x)$, so by the chain rule, we have $$(f\circ g)^\prime(0)=f^\prime(g(0))g^\prime(0)=f^\prime(2)g^\prime(0)=\left[4\sin\dfrac12-\cos\dfrac12\right]\sin(\sin(1)).$$ And $(g\circ f)^\prime(0)=g^\prime(f(0))f^\prime(0)=0$ (since $f^\prime(0)=0$, as proved above).

I understand that the chain rule states that $[f(g(x))]'=g'(x)f'(g(x))$.
However in this example the solution differentiates with respect to $x$ and the evaluates at $g(0)$. I don't understand why you can do this.  The formula implies I have to differentiate $f$ with respect to $g(x)$.

A: Differentiate $f$ (with respect to $x$) and take the value of the derivative at $g(x)$. This gives you $$f'(g(x))$$
Evaluate the derivative of $g$ (with respect to $x$) in $x$: this gives $$g'(x)$$
Take the product : $f'(g(x))\,g'(x)$
Take $x=0$: $$f'(g(0))\,g'(0)$$
Reminder: $f$ is a function, $f(x)$ is a real number (in the present case).

A: There is an easier way to think about this in terms of differentials that.
$\dfrac{dy}{dx} = \dfrac{dy}{du} \dfrac{du}{dx}$
Define a function.
$h(x) = f(g(x)) $
Let $u = g(x)$
$\dfrac{dh}{dx} = \dfrac{dh}{du} * \dfrac{du}{dx} = f'(g(x))\times g'(x) $
You see here that $u = g(x)$ is still a function of x, so when you differentiate you differentiate to a function of $x$. $g(x)$ is a rather function, not an independent variable, so it cant be differentiated to.


text:
Q: Page redirect from modal popup I have a simple modal dialog box like below on a page, on click of Go button, the user should navigate to another page, based on selected option in the dropdown; which looks like mysite.com/<cfoutput>#product_name#</cfoutput>; I get an error and it is taking me nowhere. I tried couple different things, must be missing something real small. Any insights? thanks

                    <button aria-hidden="true" data-dismiss="modal" class="close" type="button">x</button>

Select a product:

                            <form class="reg-page" method="post">
                                <select name="pid" id="pid" class="form-control input margin-bottom-20">
                                <cfoutput query="products">
                             <option value="#pid#">#product_name#</option>
                     </cfoutput>
                                </select>
                             <a class="btn btn-lg btn-block btn-home-spec-choice light-blue-bg white bold rounded" href='mysite.com/<cfoutput>#product_name#</cfoutput>'>Go!
                            </form>

A: It's unclear what the problem is... whether you're getting a javascript error or cf error but it seems like you're trying to use a product name within the same instance of the same page as the population.
This is entirely possible, but not how you're doing it. It looks like you're trying to get the value of the box as it changes without submitting the page.
Add an id to the link, I chose mlink.
You can, on initial load, use cf to populate the value equal to the default selected option's value

    <button aria-hidden="true" data-dismiss="modal" class="close" type="button">x</button>

Select a product:

            <form class="reg-page" method="post">
                <select name="pid" id="pid" class="form-control input margin-bottom-20">
                <cfoutput query="products">
             <option value="#pid#">#product_name#</option>
     </cfoutput>
                </select>
             Go!
            </form>

And then use javascript like this
document.getElementById('mlink').onclick = function (e) {
    var pidselect = document.getElementById('pid')
    this.href = "http://somesite.com/"+ pidselect.options[pidselect.selectedIndex].innerHTML;
}

Here's a JSFiddle Demo with two more lines of the code in the function to catch the link before it fires, alert you with the href value, and stop the firing (so that you don't leave the jsfiddle page.
Note that the html in the jsfiddle is different than it is here (I removed cfoutputs and duplicated an option so there was something to demonstrate that it is working, so if you copy html, copy it from this page.


text:
Q: String Index Out Of Bounds Exception I am really stuck on this exception
private static void getUserComment(String s) {
    while(s.contains("author'>")){
        System.out.println(s.substring(s.indexOf("author'>"),
                                       s.indexOf("
")) +
                           s.substring(s.indexOf("<div id='"+9));

    }
}

A: You should use a proper parser or at least do some regular expression pattern matching (which is already "bad enough" for HTML or XML).
That said, your "offset" of 9 is likely the indirect cause of the exception:
s.indexOf("<div id='"+9)

This will make a literal string <div id='9 which is not found; indexOf then returns -1 and this causes the exception in the substring method. Maybe you wanted to actually add 9 to the index like this? s.indexOf("<div id='")+9
Note that the function is useless anyways, changing s will only change the local variable and not the original variable (parameters are by value in Java).


text:
Q: Python: How to sum values from a 3d array, where the last array is a dictionary using functional map and sum
(This is Advent Of Code day 4, I already have my stars, but I'd like to do it more efficiently)
I have a 3d matrix like this one:
[
    [
        [{22: 0}, {13: 0}, {17: 1}, {11: 1}, {0 : 1}],
        [{8 : 0}, {2 : 1}, {23: 1}, {4 : 1}, {24: 1}],
        [{21: 1}, {9 : 1}, {14: 1}, {16: 0}, {7 : 1}],
        [{6 : 0}, {10: 0}, {3 : 0}, {18: 0}, {5 : 1}],
        [{1 : 0}, {12: 0}, {20: 0}, {15: 0}, {19: 0}]
    ],

    [
        [{3 : 0}, {15: 0}, {0 : 1}, {2 : 1}, {22: 0}],
        [{9 : 1}, {18: 0}, {13: 0}, {17: 1}, {5 : 1}],
        [{19: 0}, {8 : 0}, {7 : 1}, {25: 0}, {23: 1}],
        [{20: 0}, {11: 1}, {10: 0}, {24: 1}, {4 : 1}],
        [{14: 1}, {21: 1}, {16: 0}, {12: 0}, {6 : 0}]
    ],

    [
        [{14: 1}, {21: 1}, {17: 1}, {24: 1}, {4 : 1}],
        [{10: 0}, {16: 0}, {15: 0}, {9 : 1}, {19: 0}],
        [{18: 0}, {8 : 0}, {23: 1}, {26: 0}, {20: 0}],
        [{22: 0}, {11: 1}, {13: 0}, {6 : 0}, {5 : 1}],
        [{2 : 1}, {0 : 1}, {12: 0}, {3 : 0}, {7 : 1}]
    ]
]

And I want to sum all values from one of those matrices using map/sum functions.
This is what I have now and works:
# z is one of those matrices, 0, 1 or 2
soma = 0
for line in matrices[z]:  # line is a list of dictionaries
    for dic in line:      # dic is a dictionary from the list
        valor = list(dic.values())[0]
        if valor == 0:
            soma += list(dic.keys())[0]

What I've tried to do:
print("soma = ", sum(map(sum, ( (value.values())[0] for value in matrizes[z]))))

which doesnt work, and I get this error:
Traceback (most recent call last):

File "day4.py", line 75, in <module>
print("part 1 = ", sum(map(sum, ((value.values())[0] for value in matrizes[z]))))
File "day4.py", line 75, in <genexpr>
print("part 1 = ", sum(map(sum, ((value.values())[0] for value in matrizes[z]))))
AttributeError: 'list' object has no attribute 'values'

I've found a post with 2d arrays, but couldnt understand how to make it for 3d arrays.
I've also found posts using "numpy", but I want to do with map and sum functions.

A: You can do one line like this:
m = [
    [
        [{22: 0}, {13: 0}, {17: 1}, {11: 1}, {0 : 1}],
        [{8 : 0}, {2 : 1}, {23: 1}, {4 : 1}, {24: 1}],
        [{21: 1}, {9 : 1}, {14: 1}, {16: 0}, {7 : 1}],
        [{6 : 0}, {10: 0}, {3 : 0}, {18: 0}, {5 : 1}],
        [{1 : 0}, {12: 0}, {20: 0}, {15: 0}, {19: 0}]
    ],

    [
        [{3 : 0}, {15: 0}, {0 : 1}, {2 : 1}, {22: 0}],
        [{9 : 1}, {18: 0}, {13: 0}, {17: 1}, {5 : 1}],
        [{19: 0}, {8 : 0}, {7 : 1}, {25: 0}, {23: 1}],
        [{20: 0}, {11: 1}, {10: 0}, {24: 1}, {4 : 1}],
        [{14: 1}, {21: 1}, {16: 0}, {12: 0}, {6 : 0}]
    ],

    [
        [{14: 1}, {21: 1}, {17: 1}, {24: 1}, {4 : 1}],
        [{10: 0}, {16: 0}, {15: 0}, {9 : 1}, {19: 0}],
        [{18: 0}, {8 : 0}, {23: 1}, {26: 0}, {20: 0}],
        [{22: 0}, {11: 1}, {13: 0}, {6 : 0}, {5 : 1}],
        [{2 : 1}, {0 : 1}, {12: 0}, {3 : 0}, {7 : 1}]
    ]
]

s = sum([k for y in m for x in y for z in x for k,v in z.items() if v == 0])
print(s)

A: You can do:
z = 0
soma = sum(map(lambda line: sum(k for d in line for k, v in d.items() if v == 0), matrices[z]))
print(soma) # 163


text:
Q: Alternate (intuitive) definition of Cardinality for Infinite Sets For cardinality of infinite sets, the definition commonly used in mathematics is in terms of injectivity and surjectivity. If a set has a one-to-one correspondence with another, both sets have the same cardinality. If not, one is "bigger" than the other. In the case of finite sets, this definition reduces to comparing the amount of elements in the sets.
A 'surprising' result of this definition is that the cardinality of the natural numbers and the odd numbers is the same. It's surprising because it goes against 'intuition'.
But if it goes against 'intuition', then there must be an alternative definition for infinite sets, one that is more 'intuitive'. I believe this alternative definition is based on the limit of the size of the finite set, as its size goes to infinity.
With this definition, the ratio of the size of the natural and odd numbers, inside a given range (1 to N, for example), when N goes to infinity, is either exactly 1/2, or a number that approaches 1/2. So by taking the limit of their size, as N goes to infinity, we find that the alternative-cardinality of the odds is exactly 1/2 that of the naturals.
My questions are: is this alternate definition recognized by mathematicians? Is it used somewhere?
P.S: If I say the size of the naturals is twice the size of the odds, would it really be incorrect? I feel that the concept of size, for infinite sets, is subjective and there is more than one acceptable answer.

A: One place where your construction is of fundamental use is geometric group theory.  You may have heard of the Banach-Tarski paradox: One can disassemble a ball in three dimensional space, into a finite number of pieces, and then move the pieces (through rotations and translations) and reassemble them as two balls, each the size of the original.
One of the key ideas is to consider a pair of rotations of the ball, $A,B$ such that each sequence of rotations (e.g. word in the letters $A,B$) results in a different rotation.  The point here is that we can split all words in the letters $A,B$ into those that begin $A$  and those that begin $B$.  Denote these sets of words $W_A,W_B$ respectively.  Then removing the first letter from each word in $W_A$, we get an entire copy of all words.  Similarly removing the first letter from each word in $W_B$ we get all words.
So far this is a very vague explanation, but let's look in more detail at why this does not work  for the punctured disk, and we will see how your idea is key to this.
Suppose we can partition the integers into a finite number of sets $A_1,\cdots,A_n,B_1,\cdots,B_m$ such that that we have integers $a_1,\cdots,a_n,b_1,\cdots,b_m$ and the transled sets $a_1+A_1, \cdots,a_n+A_n$ form a disjoint partition of the integers, as do the translated sets, $b_1+B_1, \cdots,b_m+B_m$.
Then let $\theta$ be an irrational number, so the $\{e^{2\pi ir\theta}|\,r\in \mathbb{Z}\}$ form a subgroup (isomorphic to the integers) of the unit complex numbers under multiplication. Let $X$ be a complete system of coset representatives for this subgroup (we need the axiom of choice to guarantee this exists).  Let $\hat{X}$ denote all complex numbers of the form $\lambda x'$ with $\lambda\in (0,1]$ and $x'\in X$.
Then every point on the punctured disk $\{z\in\mathbb{C}|\,\,0<|z|\leq 1\}$ can be uniquely written in the form $e^{2\pi ir\theta} x$, for some integer $r$ and $x\in \hat{X}$.
Then we can partition the punctured disk into pieces: $$D_j=\{e^{2\pi ir\theta} x|\,\, r\in A_j, x\in \hat{X}\},\,\,{\rm and}\,\,E_k=\{e^{2\pi ir\theta} x|\,\, r\in B_k, x\in \hat{X}\}.$$
Then rotating each $D_j$ by multiplication by $e^{2\pi ia_j\theta}$ and reassembling we get a complete copy of the punctured disk.  Similarly translating all the $E_k$ by adding say $3$ to each complex number in each $E_k$, and then rotating each $E_k$ by $e^{2\pi ib_k\theta}$, we get another copy of the punctured disk.
The point is that if we could split up the integers into the $A_j,B_k$ as above, then we could duplicate the punctured disk, the same way that we can duplicate a $3$ dimensional ball.  However it turns out that area behaves differently to volume, and cannot be doubled in this way.  In particular, the integers behave differently to words on two letters, and cannot be duplicated the same way.
The proof that the decomposition into $A_j,B_k$ is impossible is basically just your idea of "alternative cardinality".  Firstly, as we are now working with the integers, the ranges need to be $-N,\cdots,N$.  Also, as I mentioned in comments, the ratios will not always converge.  However the ratios  all lie in $[0,1]$ so by the Bolzano–Weierstrass theorem, they have convergent subsequences.  We use the notion of an ultralimit, to pick out a particular limit.
It turns out that with these modifications to your construction $|S_1 \cup S_2|=|S_1|+|S_2|$ for disjoint subsets $S_1,S_2$ of the integers, $|\mathbb{Z}|=1$ and $|S+k|=|S|$ for any subset $S$ of the integers, and integer $k$.
Then: \begin{eqnarray*}
1&=&|\mathbb{Z}|\\&=&\sum_{j=1}^n|A_j|+\sum_{k=1}^m|B_k|\\
&=&\sum_{j=1}^n|a_j+A_j|+\sum_{k=1}^m|b_k+B_k|\\
&=&|\mathbb{Z}|+|\mathbb{Z}|=1+1=2,
\end{eqnarray*}
giving the desired contradiction.
Here are some wiki links on the various ideas discussed:
Banach-Tarski paradox
Ultralimit
F$\emptyset$lner Sequence (these are a generalisation of range $-N,\cdots,N$)
Amenable group


text:
Q: LSF bsub: job always in PENDING state, not going to RUN state I stuck on a small problem.
I'm launching many bsub commands at the same time each one on a specified host:
bsub -sp 20 -W 0:5 -m $myhostname -q "myQueue" -J "mkdir_script" -o $log_file "script_to_launch param1 param2 param3"

all this inside a for, for each hostName.
The problem is that everything is OK for all hosts except one (always the same one). The job is always in PENDING state, and is not moving to RUN state.
The script to execute is a script that will check for a folder and creating it if is not there (so a very small task to do).
Is there a way to see what happens on that host  and why my job is not going to RUN state ?
PS: I just found the bjobs -p command and I have the following message:
 Not specified in job submission: 81 hosts;
 Closed by LSF administrator: 3 hosts;

What does this message mean?

A: The -m option limits you to a particular host, which excludes 81 hosts. The other three have been closed by your system administrator. You would have to contact them to find out why.


text:
Q: Data Class Context is required is ASP.NET Core 5 I am having an issue with creating views where context class / model class is required, since the viewmodel isn't an entity this doesn't work and I don't have time to create from scratch without a template.
Please note that model class is required after selecting template and it shouldn't be, went through many searches and didn't find an answer .
Please advise if you faced and solved the issue before.
PS  I am only facing this issue with 1 project only, others don't have it.
Thank you.


text:
Q: Proving inverse matrix with non-square matrices Suppose $C$$A$ = $I$. ($C$ and $A$ may not be square.) Show that the equation Ax = 0 has only the trivial solution. Why can $A$ not have more columns than rows?
I understand having only trivial solutions implies that there's linear independence, and the second part of the question most likely implies there can't be any free variables, but I can't pinpoint exactly the answer they are looking for.

A: Assume that $A$ has $n$ columns and $x = (x_1, x_2, \ldots,x_n)$ is a nontrivial solution to the equation $Ax = 0$. Then:
$$
Ax=0 \implies CAx = 0 \implies x = 0
$$
a contradiction, since we assumed $x$ was nontrivial. Thus there are no nontrivial solutions.
If $A$ has more columns than rows, then $A$ must have less than $n$ pivots. Since there is a unique solution only when the number of pivots is equal to $n$ this is not possible.


text:
Q: Trajectory of two charges in free space I am talking about the "two-body problem" for charges. Apparently, for two identical particles $\mathbf{x,y}$, each with charge $q$ and mass $m$, ignoring the gravitational force, the equations of motion are
$$
m\ddot {\mathbf x}=\frac{q^2}{4\pi \epsilon_0} \frac{\mathbf{y-x}}{|\mathbf{y-x}|^3}+\frac{\mu_0 q^2}{4\pi} \frac{\dot{\mathbf x}\times(\dot{\mathbf y}\times(\mathbf{x-y})) }{|\mathbf{x-y}|^3}
$$
and a similar equation for $\mathbf y$. This is apparently more complicated than the two body problem of gravitational forces, because there is an additional term about the magnetic field generated by one of the particles.
Question: is there an analytic general solution to this differential equation? Or are there good approximations?


text:
Q: VisualD/Visual Studio Cannot Open Premake Generated .visualdproj I've been trying out premake with D, and have found that Visual Studio cannot open the generated visualdproj files. Even the example given in the readme for the module does not work. However, a C project appears to work just fine even in the same solution. What is happening here?
This is my premake5.lua:
workspace "Test"
    configurations { "release", "debug" }

    project "app"
        language "D"
        kind "ConsoleApp"
        files "source/app.d"

    project "app2"
        language "C"
        kind "ConsoleApp"
        files "source2/app.c"


text:
Q: HttpClient Pass Multiple objects/variables to[HttpPost] Web API m I'm using HttpClient to connect .NET project with my Web API.
I wanted to know how to send multiple parameters to the webapi method in the PostAsJsonAsync() method.
Client Controller:
callbackUrl = Url.HttpRouteUrl("DefaultApiAction", new { controller = "Employee", action = "UpdateToleranceRangeByEmployeeId" });
responseMessage = await client.PostAsJsonAsync(callbackUrl, new { companyId = CompanyId, deptId = Depts, divId = Divs, empId = Emps, range = objToleranceRangeModel.ToleranceRange.Value, flag = objToleranceRangeModel.ToleranceFlag });
if (responseMessage.IsSuccessStatusCode)
{
    var responseData = responseMessage.Content.ReadAsStringAsync().Result;

}
else
{
    logger.Error("Error Inside UpdateToleranceRangeByEmployeeId:" + responseMessage.IsSuccessStatusCode);

}

API Method:
[AllowAnonymous]
[HttpPost]
[Route("UpdateToleranceRangeByEmployeeId")]
public HttpResponseMessage UpdateToleranceRangeByEmployeeId(int companyId, List<int> deptId, List<int> divId, List<int> empId, double range, bool flag)
{
    logger.Info("Inside UpdateToleranceRangeByEmployeeId");
    HttpResponseMessage response;
    List<EmployeeModel> ObjEmployeeModelList = new List<EmployeeModel>();

    try
    {

        ObjEmployeeModelList = this._iEmployeeServices.UpdateToleranceRangeByEmployeeId(companyId, deptId, divId, empId, range, flag);
        if (ObjEmployeeModelList != null && ObjEmployeeModelList.Count() != 0)
        {
            response = Request.CreateResponse<List<EmployeeModel>>(HttpStatusCode.OK, ObjEmployeeModelList);
        }
        else
        {
            response = Request.CreateResponse(HttpStatusCode.NotFound);
        }
    }
    catch (Exception objEx)
    {
        logger.Error("Error Inside UpdateToleranceRangeByEmployeeId:" + objEx);
        response = Request.CreateResponse<Exception>(HttpStatusCode.ExpectationFailed, objEx);
    }
    return response;
}

I am getting error  :
responseMessage = {StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Pragma: no-cache
  X-SourceFiles: =?UTF-8?B?RjpcU0FUXFNBVC5BUElcYXBpXEVtcGxveWVlXFVwZGF0ZVRvbGVyYW5jZVJhbmdlQnlFbXBsb3llZUlk?=
  Cache-Contro...

A: Please double check whether you have the correct URL before making the request.
404 means that the resource was not found.


text:
Q: Как объединить 2 меню на мобильных устройствах Есть 2 меню. Нужно, чтобы при разрешении экрана <767px первое меню скрывалось, а выводилось 2-е, но к нему добавлялись все элементы первого, и к ним добавлялся класс additional-menu-item. Код, который использую ниже, работает только если при изменении ширины экрана каждый раз обновлять страницу. Подскажите, пожалуйста, как правильно сделать на чистом JavaScript (без jQuery).
HTML:

Top 1

Top 2

Top 3

Main 1

Main 2

Main 3

CSS:
@media (max-width: 767px) {
   .top-menu {
        display: none;
   }
   .main-menu {
        outline: 1px solid red;
    }
}

JS:
let mainMenuItems = document.querySelector(".main-menu");

const mediaQuery = window.matchMedia('(max-width: 767px)');

if (mediaQuery.matches) {

    let topMenuItemsNew = document.querySelectorAll(".top-menu li");

    for (let liElement of topMenuItemsNew) {
        liElement.className += " additional-menu-item";
    }

    let topMenuItems = document.querySelector(".top-menu");

    mainMenuItems.insertAdjacentHTML('beforeend', topMenuItems.innerHTML);
}

A: Не надо измерять экран, браузер умеет распознавать mobil\desktop.
Это в typescript+react, на чистом js почти всё то же самое.
let os: string;
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
    os = "mobile";
} else {
    os = "not mobile";
}

Потом в зависимости от os что-то типа
contents = (os === "mobile") ? this.mobileLayout() : this.desktopLayout();

Имитировать mobile можно нажав f12 + иконка наверху слева.


text:
Q: C++ no instance of function template This is what in my .h file, DbQuery class:
template<typename T>
void showResults(Query<T>::Keys& keys, std::ostream& out = std::cout)
{
    out << "\n  ";
    for (auto key : keys)
    {
        out << key << " ";
    }
}

This is what in my .cpp file:
bool testR6a()
{
    Utilities::title("Demonstrating Requirement #6a - query for value");
    DbP dbp;
    Query<std::string> query;
    Query<std::string>::Keys result = query.qKeys(dbp.db(), "a");
    showResults(query.qKeys(dbp.db(), "a"));
    return true;
}

I can't figure out what is the problem of my instance.
E0304: no instance of function template "DbQuery::showResults" matches the argument list
argument types are:
(std::vector>)
Does anyone know?
I feel bad that I don't think I can make a simple example to compile. This is a small part of a big program and I don't know how to simplify it.
I don't know whether this image can make you understand better:

A: The problem is that you are relying on template argument deduction, while your function template is written in a way that doesn't support it. To put simply, the C++ standard defines several "non-deduced contexts". When a template parameter appears in one of those, it will not be deduced from a corresponding function argument. One of those contexts is on the left of scope resolution.
What I'm saying is that the compiler can't use Query<T>::Keys& keys to deduce T. That's why you are getting an error. You need to specify it explicitly:
showResults<std::string>(query.qKeys(dbp.db(), "a"));

Well, not really. There's still the issue of your code not being const correct. Unless query.qKeys(...) returns a non-const lvalue reference (I doubt it), your code is ill-formed on any standard conforming C++ compiler. MSVC allows binding non-const lvalue references to temporary objects as an extension. But it's not portable C++. You seem to be somewhat aware of that already, because you declare result. So the proper call when going with the approach above:
showResults(result);

Or alternatively, if your function doesn't need to ever modify the passed argument, is to accept by a const reference.

A: The answer of StoryTeller is good (the automatic deduction does not work). Theoretically, you can simplify your function into this. Now the deduction should happen automatically, so you do not need to give the compiler further hints.
template<typename T>
void showResults(T& keys, std::ostream& out = std::cout)
{
    out << "\n  ";
    for (auto key : keys)
    {
        out << key << " ";
    }
}


text:
Q: Python dictionary value assignment from variable I have this routine:
def _get_files_download_list(self, proj):
    tmp = {}

    # get the global file download list
    global_files = self.config['projects']['global']['server_group']['global']['file_download']

    for k in proj['server_group'].keys():
        # create the array for each server group
        # add the global stuff to each server group
        tmp_keys = global_files
        try:
            if 'file_download' in proj['server_group'][k]:
                # loop the server groups and add the file_download to that array
                for key in proj['server_group'][k]['file_download']:
                    # this way if something overrides the global, so be it, but the global is added to everything
                    tmp_keys[key] = proj['server_group'][k]['file_download'][key]
        except KeyError as e:
            pass

        if len(tmp_keys) > 0:
            tmp[k] = tmp_keys
    return tmp

the problem is at the end of the routine, the different tmp[k] values all have the same value.  I suspect the problem has to do with the way python links variables to the dictionary in memory. im thinking python assigns a pointer to an object location in memory instead of creating a new instance of the object on the tmp_keys = global_files line.  If im correct, whats the syntax to create a new instance of the object instead of just updating the existing one.

A: How about:
import copy
tmp_keys = copy.copy(global_files)

Depending on what kind of data is in global_files, it may only pass in a reference.


text:
Q: upload and process user selected file in html, javascript and php I want to have a user select a file and then have php put the contents in db. Now the last part (processing the file in php) is easy. But is there a way I can process a user selected file whithout a new page load?
If I use the following:
<FORM ACTION="upload.php" METHOD="post" ENCTYPE="multipart/form-data">
<INPUT TYPE="file" NAME="somefile">

<INPUT TYPE="submit" NAME="submit" VALUE="Upload">
</FORM>

Page upload.php automaticaly loads after which I can insert the uploaded file in a database.
I would like to use a combination of javascript, php and xajax to process the file. I don't think something like this is possible:
<FORM ACTION="javascript:xajax_proces_file()" METHOD="post" ENCTYPE="multipart/form-data">
<INPUT TYPE="file" NAME="somefile">

<INPUT TYPE="submit" NAME="submit" VALUE="Upload">
</FORM>

Because the file is not uploaded when function xajax_process_file() is called. Or is it? I think I do not fully grasp the principle of uploads with javascript, html and php.
Any help and or clarification is much appreciated.

A: It may help to think of this as a two step process.
First, the user fills in the form and submits it - step one.
Second ( which is the default action ) the specified target file takes the input from the form and uses it to do whatever. You can almost think of a form "action" as a link - the default action of a link click is to display the result of the link. The same goes for a form action - display the result of a form action.
Now, it's possible via JavaScript to disable the default action of an element for a particular event. It is also possible via JavaScript to access a browsers HTTP mechanism to send/receive HTTP request (which is what every page request is - whether from your URL bar or a page link or a Google search result).
And that is what AJAX in simple terms is - using JavaScript to use a browsers HTTP mechanism to send requests to a web server and possible receive a response back without the use of a traditional click event. You then combine this with the use of JavaScript to "turn off" default actions and instead follow the action specified by you to get information from a server and add it to the page without ever having to refresh the page.
Many times to prevent the defualt action from taking place for a certain element, you return false in your code. The same goes for your form. Using javascript:
form.onSubmit = function() {
  blah blah blah.....Use ajax to send the information to the form handler
  return false; //Prevents the defualt action of the submit event
}

If you are really new to AJAX, I suggest you check out this tutorial and then this one. Lastly, I would recommend using a Javascript framework like jQuery to help you - it is awesome and does alot of great stuff, but also has easy and built in functionality for AJAX.
Here is another tutorial to do a form submit with no page refresh (uses jquery).

A: an alternative is to make the form directs the action to an iframe, after processing the query in the iframe, proceed by JS to clear the form of the father


text:
Q: How to create dynamic sidebar links in vue.js? I am completely new to vue.js and trying to learn how to leverage this framework to build a frontend for my API.  I am using the vue-admin theme and there is a sidebar with some nav links in it, that looks like below.
store/modules/menu/index.js
const state = {
  items: [
    {
      name: 'Dashboard',
      path: '/dashboard',
      meta: {
        icon: 'fa-tachometer',
        link: 'dashboard/index.vue'
      },
      component: lazyLoading('dashboard', true)
    },
    charts,
    android,
  ]
}

then, in the same directory as index.js I have charts.vue and android.vue.
android.vue
import lazyLoading from './lazyLoading'

export default {
  name: 'Android',
  meta: {
    icon: 'fa-android',
    expanded: false
  },

  children: [
    {
      name: 'Jobs on Android',
      path: '/andr/android',
      meta: {
        label: 'android',
        link: 'android/Basic.vue'
      },
      component: lazyLoading('android/Basic')
    }
  ]
}

So in my sidebar, I now have 'dashboard', 'charts' and 'android'.  What I can't figure out is how to dynamically create links in my sidebar based on an API request.  the API request will return a simple list and I want to then build the sidebar links from the list.
Would I move the android.vue code back into the index.js and use a for loop to create each link?  I'm guessing everything should be consolidated into a single index.js for this?  Any help would be appreciated.

A: You can create a main component for the menu that will take care of getting all the links in the store and that will return the array items

// Create this component ./main.vue
//file main.vue

import lazyLoading from './lazyLoading'

/* I presume you have a field named items in your store
 and it has this architecture :

items: [{ name: 'Dashboard',path: '/dashboard',meta: {
        icon: 'fa-tachometer',link: 'dashboard/index.vue'},
        component: "dashboard"},
        { name: 'chart',path: '/chart',meta: {
        icon: 'fa-chart',link: 'chart/index.vue'},
        component: "chart"}, ...etc]
*/
var items = this.$store.state.items

for (i in items) {
items[i].component = lazyLoading(items[i].component, true)
}

export default items;

Then, you can import main.vue and insert it in index.js

//file index.js

import items from "./main"

const state = {
  items:items
}

I have not really tested it but I hope it will work and will help you


text:
Q: Unity - glossy blur material? Ok Im trying to do a standard blur material like this (the darkened beat saber menu)

Or
But on a 3D object, so not a camera effect or canvas material. I found some assets that provide a low quality blur but I need it glossy, and a nice Gaussian blur. The one I have has weird streaks:

// Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,)' with 'UnityObjectToClipPos()'
Shader "Custom/WaterBlur" {
    Properties {
    _blurSizeXY("BlurSizeXY", Range(0,10)) = 0
}
    SubShader {

        // Draw ourselves after all opaque geometry
        Tags { "Queue" = "Transparent" }

        // Grab the screen behind the object into _GrabTexture
        GrabPass { }

        // Render the object with the texture generated above
        Pass {

CGPROGRAM
#pragma debug
#pragma vertex vert
#pragma fragment frag
#ifndef SHADER_API_D3D11

    #pragma target 3.0

#else

    #pragma target 4.0

#endif

            sampler2D _GrabTexture : register(s0);
            float _blurSizeXY;

struct data {

    float4 vertex : POSITION;

    float3 normal : NORMAL;

};

struct v2f {

    float4 position : POSITION;

    float4 screenPos : TEXCOORD0;

};

v2f vert(data i){

    v2f o;

    o.position = UnityObjectToClipPos(i.vertex);

    o.screenPos = o.position;

    return o;

}

half4 frag( v2f i ) : COLOR

{

    float2 screenPos = i.screenPos.xy / i.screenPos.w;
    float depth= _blurSizeXY*0.0005;

    screenPos.x = (screenPos.x + 1) * 0.5;

    screenPos.y = 1-(screenPos.y + 1) * 0.5;

    half4 sum = half4(0.0h,0.0h,0.0h,0.0h);
    sum += tex2D( _GrabTexture, float2(screenPos.x-5.0 * depth, screenPos.y+5.0 * depth)) * 0.025;
    sum += tex2D( _GrabTexture, float2(screenPos.x+5.0 * depth, screenPos.y-5.0 * depth)) * 0.025;

    sum += tex2D( _GrabTexture, float2(screenPos.x-4.0 * depth, screenPos.y+4.0 * depth)) * 0.05;
    sum += tex2D( _GrabTexture, float2(screenPos.x+4.0 * depth, screenPos.y-4.0 * depth)) * 0.05;

    sum += tex2D( _GrabTexture, float2(screenPos.x-3.0 * depth, screenPos.y+3.0 * depth)) * 0.09;
    sum += tex2D( _GrabTexture, float2(screenPos.x+3.0 * depth, screenPos.y-3.0 * depth)) * 0.09;

    sum += tex2D( _GrabTexture, float2(screenPos.x-2.0 * depth, screenPos.y+2.0 * depth)) * 0.12;
    sum += tex2D( _GrabTexture, float2(screenPos.x+2.0 * depth, screenPos.y-2.0 * depth)) * 0.12;

    sum += tex2D( _GrabTexture, float2(screenPos.x-1.0 * depth, screenPos.y+1.0 * depth)) *  0.15;
    sum += tex2D( _GrabTexture, float2(screenPos.x+1.0 * depth, screenPos.y-1.0 * depth)) *  0.15;

    sum += tex2D( _GrabTexture, screenPos-5.0 * depth) * 0.025;
    sum += tex2D( _GrabTexture, screenPos-4.0 * depth) * 0.05;
    sum += tex2D( _GrabTexture, screenPos-3.0 * depth) * 0.09;
    sum += tex2D( _GrabTexture, screenPos-2.0 * depth) * 0.12;
    sum += tex2D( _GrabTexture, screenPos-1.0 * depth) * 0.15;
    sum += tex2D( _GrabTexture, screenPos) * 0.16;
    sum += tex2D( _GrabTexture, screenPos+5.0 * depth) * 0.15;
    sum += tex2D( _GrabTexture, screenPos+4.0 * depth) * 0.12;
    sum += tex2D( _GrabTexture, screenPos+3.0 * depth) * 0.09;
    sum += tex2D( _GrabTexture, screenPos+2.0 * depth) * 0.05;
    sum += tex2D( _GrabTexture, screenPos+1.0 * depth) * 0.025;

    return sum/2;

}
ENDCG
        }
    }

Fallback Off
}

How can I accomplish a glossy, or even just a highqaulity gaussian blur material for a mesh?

A: If you want to include a gloss onto your surface, here is one way to do it, based on the shader in the Glossy Textures article in the Unity Community wiki copied below:

Shader "Cg per-pixel lighting with texture" {
   Properties {
      _MainTex ("RGBA Texture For Material Color", 2D) = "white" {}
      _Color ("Diffuse Material Color", Color) = (1,1,1,1)
      _SpecColor ("Specular Material Color", Color) = (1,1,1,1)
      _Shininess ("Shininess", Float) = 10
   }
   SubShader {
      Pass {
         Tags { "LightMode" = "ForwardBase" }
            // pass for ambient light and first light source

         CGPROGRAM

         #pragma vertex vert
         #pragma fragment frag

         #include "UnityCG.cginc"
         uniform float4 _LightColor0;
            // color of light source (from "Lighting.cginc")

         // User-specified properties
         uniform sampler2D _MainTex;
         uniform float4 _Color;
         uniform float4 _SpecColor;
         uniform float _Shininess;

         struct vertexInput {
            float4 vertex : POSITION;
            float3 normal : NORMAL;
            float4 texcoord : TEXCOORD0;
        };
         struct vertexOutput {
            float4 pos : SV_POSITION;
            float4 posWorld : TEXCOORD0;
            float3 normalDir : TEXCOORD1;
            float4 tex : TEXCOORD2;
        };

         vertexOutput vert(vertexInput input)
         {
            vertexOutput output;

            float4x4 modelMatrix = unity_ObjectToWorld;
            float4x4 modelMatrixInverse = unity_WorldToObject;

            output.posWorld = mul(modelMatrix, input.vertex);
            output.normalDir = normalize(
               mul(float4(input.normal, 0.0), modelMatrixInverse).xyz);
            output.tex = input.texcoord;
            output.pos = mul(UNITY_MATRIX_MVP, input.vertex);
            return output;
         }

         float4 frag(vertexOutput input) : COLOR
         {
            float3 normalDirection = normalize(input.normalDir);

            float3 viewDirection = normalize(
               _WorldSpaceCameraPos - input.posWorld.xyz);
            float3 lightDirection;
            float attenuation;

            float4 textureColor = tex2D(_MainTex, input.tex.xy);

            if (0.0 == _WorldSpaceLightPos0.w) // directional light?
            {
               attenuation = 1.0; // no attenuation
               lightDirection =
                  normalize(_WorldSpaceLightPos0.xyz);
            }
            else // point or spot light
            {
               float3 vertexToLightSource =
                  _WorldSpaceLightPos0.xyz - input.posWorld.xyz;
               float distance = length(vertexToLightSource);
               attenuation = 1.0 / distance; // linear attenuation
               lightDirection = normalize(vertexToLightSource);
            }

            float3 ambientLighting = textureColor.rgb
               * UNITY_LIGHTMODEL_AMBIENT.rgb * _Color.rgb;

            float3 diffuseReflection = textureColor.rgb
               * attenuation * _LightColor0.rgb * _Color.rgb
               * max(0.0, dot(normalDirection, lightDirection));

            float3 specularReflection;
            if (dot(normalDirection, lightDirection) < 0.0)
               // light source on the wrong side?
            {
               specularReflection = float3(0.0, 0.0, 0.0);
                  // no specular reflection
            }
            else // light source on the right side
            {
               specularReflection = attenuation * _LightColor0.rgb
                  * _SpecColor.rgb * (1.0 - textureColor.a)
                     // for usual gloss maps: "... * textureColor.a"
                  * pow(max(0.0, dot(
                  reflect(-lightDirection, normalDirection),
                  viewDirection)), _Shininess);
            }

            return float4(ambientLighting + diffuseReflection
               + specularReflection, 1.0);
         }

         ENDCG
      }

      Pass {
         Tags { "LightMode" = "ForwardAdd" }
            // pass for additional light sources
         Blend One One // additive blending

          CGPROGRAM

         #pragma vertex vert
         #pragma fragment frag

         #include "UnityCG.cginc"
         uniform float4 _LightColor0;
            // color of light source (from "Lighting.cginc")

         // User-specified properties
         uniform sampler2D _MainTex;
         uniform float4 _Color;
         uniform float4 _SpecColor;
         uniform float _Shininess;

        struct vertexInput {
            float4 vertex : POSITION;
            float3 normal : NORMAL;
            float4 texcoord : TEXCOORD0;
        };
         struct vertexOutput {
            float4 pos : SV_POSITION;
            float4 posWorld : TEXCOORD0;
            float3 normalDir : TEXCOORD1;
            float4 tex : TEXCOORD2;
        };

         vertexOutput vert(vertexInput input)
         {
            vertexOutput output;

            float4x4 modelMatrix = unity_ObjectToWorld;
            float4x4 modelMatrixInverse = unity_WorldToObject;

            output.posWorld = mul(modelMatrix, input.vertex);
            output.normalDir = normalize(
               mul(float4(input.normal, 0.0), modelMatrixInverse).xyz);
            output.tex = input.texcoord;
            output.pos = mul(UNITY_MATRIX_MVP, input.vertex);
            return output;
         }

         float4 frag(vertexOutput input) : COLOR
         {
            float3 normalDirection = normalize(input.normalDir);

            float3 viewDirection = normalize(
               _WorldSpaceCameraPos - input.posWorld.xyz);
            float3 lightDirection;
            float attenuation;

            float4 textureColor = tex2D(_MainTex, input.tex.xy);

            if (0.0 == _WorldSpaceLightPos0.w) // directional light?
            {
               attenuation = 1.0; // no attenuation
               lightDirection =
                  normalize(_WorldSpaceLightPos0.xyz);
            }
            else // point or spot light
            {
               float3 vertexToLightSource =
                  _WorldSpaceLightPos0.xyz - input.posWorld.xyz;
               float distance = length(vertexToLightSource);
               attenuation = 1.0 / distance; // linear attenuation
               lightDirection = normalize(vertexToLightSource);
            }

            float3 diffuseReflection = textureColor.rgb
               * attenuation * _LightColor0.rgb * _Color.rgb
               * max(0.0, dot(normalDirection, lightDirection));

            float3 specularReflection;
            if (dot(normalDirection, lightDirection) < 0.0)
               // light source on the wrong side?
            {
               specularReflection = float3(0.0, 0.0, 0.0);
                  // no specular reflection
            }
            else // light source on the right side
            {
               specularReflection = attenuation * _LightColor0.rgb
                  * _SpecColor.rgb * (1.0 - textureColor.a)
                     // for usual gloss maps: "... * textureColor.a"
                  * pow(max(0.0, dot(
                  reflect(-lightDirection, normalDirection),
                  viewDirection)), _Shininess);
            }

            return float4(diffuseReflection
               + specularReflection, 1.0);
               // no ambient lighting in this pass
         }

         ENDCG
      }
   }
   Fallback "Specular"
}

The final Pass of your blur shader will need to be merged into the first and second Passes in the above shader.
Shader Properties
Add these properties in the blur shader if they don't already exist (you may need to rename things if they do):
  _MainTex ("RGBA Texture For Material Color", 2D) = "white" {}
  _Color ("Diffuse Material Color", Color) = (1,1,1,1)
  _SpecColor ("Specular Material Color", Color) = (1,1,1,1)
  _Shininess ("Shininess", Float) = 10

The first gloss pass
Set the tag to match the glossy shader: "LightMode" = "ForwardBase"
Add these variables to the pass if they don't already exist (you may need to rename things if they do):
 uniform sampler2D _MainTex;
 uniform float4 _Color;
 uniform float4 _SpecColor;
 uniform float _Shininess;

Include float3 normal : NORMAL; in your vertex input structure.
Include float4 posWorld : TEXCOORD0; and float3 normalDir : TEXCOORD1; in your vertex output structure.
In the vert function, set output.posWorld and output.normalDir the same way the glossy shader vert does.
Then, in the frag function, take what your blur shader is already returning, and instead of returning it, use it as the textureColor variable in the 1st frag function in the glossy shader, and then do the rest of the 1st glossy frag.
You will probably have to rename other things in the code to make it work with the pass you already have. I don't know what your blur shader looks like, so it's impossible for me to list every step in merging the two passes together.
The second gloss pass
Repeat the same process as the first gloss Pass, but using the code from the 2nd gloss Pass (especially important is the different tag "LightMode" = "ForwardAdd")


text:
Q: what is the need for importing libraries multiple times in most code examples I see people doing this.
import javax.swing.*; // for the frame
import java.awt.*; // for the checkBox and the label
import java.awt.event.*; // for the checkBox listener

If I am correct when we say import java.awt.* it imports everything inside it, so there wont be a need to say import java.awt.event.*; or is there a speed improvement? can anyone also explain what importing a library does, is it importing a simple text class to be included in the source or telling jvm to include the byte code of whatever is imported? so importing in java does nothing but switch the namespace, so I dont have to type long class names?

A: Forget the term subpackage. Do it quick. It does not exist in java world.
java.awt is a package (namespace), java.awt.event is another one and they have nothing in common. Their names share some characters, but the packages are totally unrelated. The import statements imports a class or some classes from exactly one package (namespace). If you need classes from a different package (namespace), then you have to add another import statement.

BTW, in response to a comment to another answer: You do not have to use import statements. If you don't use them, you simply have to use the fully qualified classnames in your java source file (except: classes from java.lang and the current package are imported automatically). So import could be considered as a convenient way to keep the code readable.
Importing is not required in order to use a class in your source file.

A: The line...

import java.awt.*;

...doesn't mean that all subpackages will also be imported. You have to explicitly import every package. As an example, importing java.* doesn't give you the entire java library.
For what it's worth, I recommend importing the specific classes only unless you have good reason to use *.

A: Importing a package doesn't import its subpackages.
Importing is about switching the namespace, too.
If you only had import java.awt.* and you were to use the class java.awt.Outer.Inner, everywhere in your code you have to refer to it as Outer.Inner.
By contrast, when you say import java.awt.Outer.*, you can refer to the inner class as just Inner.

A: Importing is just a compile time feature, in bytecode you will find only direct references to specific classes, everytime its instance is used.
"import" constructs exist just to eliminate use of full class name everytime.


text:
Q: SQL Syntax NOT IN for Google BigQuery The Google SQL syntax guide found here
https://developers.google.com/bigquery/docs/query-reference
does not seem to address use of the NOT IN terminology.
I get the error
Query Failed
Error: Encountered "" at line 0, column 0. Was expecting one of:

(and then Google lists nothing after the words 'one of')
when my query is
SELECT ageinmonths,amountborrowed,borrowerrate,creationdate,creditgrade,
       debttoincomeratio,groupkey,key,lenderrate,listingkey,modifieddata,
       originationdate,prosperrating,status,term
FROM prosperloans1.loans2 as big,
     prosperloans1.dupelistingkeysinloans2 as small
WHERE big.listingkey NOT IN small.listingkey

the table 'small' has 14 rows.  The table big has 57K rows.
Any ideas?
Not sure if Google SQL supports NOT IN.
Thanks
Shawn

A: Semijoins and antijoins use the following syntax:
SELECT field
FROM table
WHERE field [NOT] IN (SELECT other_field FROM other_table WHERE foo = 'bar')
So your updated query with the subselect is the correct version.


text:
Q: Write to multiple tables using data obtained from a view in postgreSQL? I'm new to SQL and I have a large database that needs some cleanup. The way it is formatted is like this:  each table has a column containing an ID number and a second column containing some other type of information like so.

*

*Names: ID# Name

*Emails: ID# Email

*Phones: ID# Phone

*Notes: ID# Note

I have a view that shows the information from all of these tables (in the actual database there are about 90 of them) and some code that takes each 'Note' and processes it into its individual components.  The notes are basically a jumble of all the other information combined, with a typical note reading:

First M. Last, Position Title, Phone 123-456-7890, Email abc@def.com

What I have now is code that iterates over all the notes in the view (~3 million) and identifies each element (phone, email, etc), but now I need to take these elements and write them to their respective columns in the other tables in the database.  I know that you can't write to a view as you can to a table and I'm not sure what the best strategy is for this seeing as I have so many notes to process. Can anyone help?

A: Actually, you can write to a view if you define an appropriate DO INSTEAD trigger (newer Pg versions) or RULE (older versions).
In this case, though, I'd recommend extracting the data from the view that you wish to change into a new table (UNLOGGED if using PostgreSQL 9.1+). I'd then write a series of UPDATE ... FROM statements, one for each table to be updated, that join against the change info table.
If that's not viable, another way that's much slower but more amenible to being done in small chunks is to do it with a PL/PgSQL procedure, where you grab a few rows from the view or a temp table created from the view, update them in all associated tables, grab a few more rows, and repeat.


text:
Q: How to reduce time between activities in android studio I have an app with 3 activities. I noticed there is a slight delay when going from 1 activity to the next (~0.3sec). My Java code is pretty simple, my XML are a little less simple. My XMLs on average contain: 4 TextView, 1 list view and 4 buttons. I removed the animation effect in the manifests xml. But still i notice this 0.3 sec delay between activities. Is there a way to reduce that delay between activities Or my xmls are simply too heavy?

A: You can try to use the Fragments instead of Activities. You can dynamically show them, without delay, because they will be always loaded in a memory. The delay between Activities start is because the system must at first check intent, for other application that can make this action, and after that create new Activity.

A: Written a code in Run time for 3 activities and try it.


text:
Q: CLIPS family tree expert system I am trying to create a CLIPS program that describes family relations. I am completely lost, I don't even know where to start.
Given the following deftemplates for facts describing a family tree.
    (deftemplate father‐of (slot father) (slot child))
    (deftemplate mother‐of (slot mother) (slot child))
    (deftemplate male (slot person))
    (deftemplate female (slot person))
    (deftemplate wife‐of (slot wife) (slot husband))
    (deftemplate husband‐of (slot husband) (slot wife))

Write rules that infer the following relations. Describe the deftemplates you use to solve
the problem.
      a) Uncle, aunt
      b) Cousin
      c) Grandparent
     d) Grandfather, grandmother
     e) Sister, bother
Run the expert system for your own family tree.
I have looked up similar examples and tried doing something similar but I am still struggling to understand what I need to do

A: Here's how you could do it for determining the sister:
         CLIPS (6.31 6/12/19)
CLIPS> (deftemplate father-of (slot father) (slot child))
CLIPS> (deftemplate mother-of (slot mother) (slot child))
CLIPS> (deftemplate male (slot person))
CLIPS> (deftemplate female (slot person))
CLIPS>
(deffacts info
   (father-of (father Bill) (child Mary))
   (mother-of (mother Jane) (child Mary))
   (father-of (father Bill) (child John))
   (mother-of (mother Jane) (child John))
   (male (person Bill))
   (male (person John))
   (female (person Jane))
   (female (person Mary)))
CLIPS>
(defrule sister-of
   (or (male (person ?person))
       (female (person ?person)))
   (female (person ?sister&~?person))
   (father-of (father ?father) (child ?person))
   (father-of (father ?father) (child ?sister))
   (mother-of (mother ?mother) (child ?person))
   (mother-of (mother ?mother) (child ?sister))
   =>
   (printout t ?sister " is the sister of " ?person crlf))
CLIPS> (reset)
CLIPS> (run)
Mary is the sister of John
CLIPS>


text:
Q: Join Tables in .NET DataSet to Display in DataGridView I have two tables in a DataSet in .NET. I want to join them on an ID column. Then I want a DataGridView to display two columns from the first table and one column from the second table.
If it makes it easier, the relation between the two tables is one-to-one.
Can it be done?

A: Well, is it read only? In .NET 3.5 / C# 3.0 you could probably use a LINQ join and an anonymous output type pretty easily:
        DataTable left = new DataTable
        {
            Columns = { {"PK", typeof(int)}, {"Name", typeof(string)}},
            Rows = {{1,"abc"},{2,"def"}}
        }, right = new DataTable
        {
            Columns = { { "FK", typeof(int) }, { "Value", typeof(decimal) } },
            Rows = { { 1, 123.45M }, { 2, 678.9M } }
        };
        var qry = from x in left.Rows.Cast<DataRow>()
                  join y in right.Rows.Cast<DataRow>()
                  on x.Field<int>("PK") equals y.Field<int>("FK")
                  select new
                  {
                      Name = x.Field<string>("Name"),
                      Value = y.Field<decimal>("Value")
                  };
        var data = qry.ToList();

You can then bind to "Name" and "Value" of data. Note it is easier with typed data-sets, since you can lose the Cast<> and Field<> rubbish.

A: Why not to use the designer?
You place both tables in the dataset, you establish the relationship, and change the Fill/Get methods, to something like this (with the "inner join"):

SELECT        Productos.idProducto,
  Productos.Nombre, Precios.Precio,
  Tiendas.idTienda,
  Zonas.Zona,Productos.idZona FROM
  Productos INNER JOIN
                           Precios ON Productos.idProducto =
  Precios.idProducto


text:
Q: `docker run` output to bash variable - strange behaviour I'm seeing some strange behaviour getting the output from docker run into a bash variable.
Simple example:
#!/bin/bash

PWD=$(docker run --rm -ti ubuntu pwd 2>&1)
# also tried with PWD=`docker run ...` with same behaviour
echo $PWD
echo abc $PWD
echo abc $PWD xyz

output
/
abc /
 xyz/

The problem is on the last echo...

A: you need to modify the docker run --rm -ti ubuntu pwd 2>&1 with docker run --rm ubuntu pwd 2>&1
probabilly the interactive and tty mode doesn't work fine in a shell variables

A: Dockers -t option allocates a pseudo terminal for the process to output to. A TTY uses a CRLF for a line ending unlike the usual LF in unix.
The " xyz" in your example output is overwriting the rest of the text from the start of the line due to the carriage return stored in the variable.
The od utility can dump the hex or octal values.
$ docker run -t busybox pwd | od -b
0000000   057 015 012
0000003

057 = / 015 = CR 012 = LF
Then the normal output.
$ docker run busybox pwd | od -b
0000000   057 012
0000002

Remove the -t and possibly check for errors rather than redirecting stderr to stdout. -i is not required unless the process requires stdin.
PWD=$(docker run --rm ubuntu pwd)
[ "$?" == "0" ] || exit 1
echo "[$PWD]"

A: The characters \r\n are present in the output:
$ docker run --rm -ti ubuntu pwd 2>&1 > /tmp/docker.out
$ cat -A /tmp/docker.out
/^M$
$ python -c "import sys; print repr(sys.stdin.read())" < /tmp/docker.out
'/\r\n'

Also, don't rely on the output for docker run, because if the ubuntu image is not already present, it will also be pulled and the messages of "Pulling image" will be part of the output.


text:
Q: Select duplicate by youngest date I have run into a snag.
A got a DB with employees with multiple startdates.
Employees can start and can get a new contract later.
FE.
ID   NAME  DATEEMPLOYED FUNCTION
1    Paul  01/01/2016   Director
2    Paul  01/01/2015   Staff Member
3    Jeff  02/05/2016   Director
4    Jeff  01/05/2015   Employee
5    Jeff  01/05/2014   Employee
6    Eric  05/06/2015   Employee

Now I need to get the ID from the latest and the youngest date.
I want to copy the function of the row with the latest date to the oldest date and then delete all but the oldest.
The oldest I can find by:
SELECT * FROM [database].[dbo].[Personel] t WHERE DATEEMPLOYED NOT IN      (SELECT MAX(DATEEMPLOYED)  AS LastUpdate FROM [database].[dbo].[Personel] GROUP BY Naam,Voornaam)

This returns 10 rows...
Now to find the youngest...
I thought, it would be as easy as changing MAX(DATEEMPLOYED) to MIN(DATEEMPLOYED)...
But I guess not because this only returns 6 rows...
I'm running a live DB so no sample date...
The expected output of the query for the max date per employee is ID 1 and 3 ... The expected output for min date is ID 2 and 5 ...
No number 6
I'am running MS SQL trough an ASP.net application...
The query posted I'm running on the SQL server itself for testing...
Later I'll adapt for the ASP.Net
I want to automatize the deletion of duplicate employees.
Where did i go wrong?

A: DEPENDING on your version, you could use the window function
    Declare @YourTable table (ID int,NAME varchar(50),  DATEEMPLOYED Date, [FUNCTION] varchar(50))
    Insert Into @YourTable values
    (1,'Paul','01/01/2016','Director'),
    (2,'Paul','01/01/2015','Staff Member'),
    (3,'Jeff','02/05/2016','Director'),
    (4,'Jeff','01/05/2015','Employee'),
    (5,'Jeff','01/05/2014','Employee'),
    (6,'Eric','05/06/2015','Employee')

;with cteBase as (
    Select Distinct Name
          ,Times   = count(*) over  (Partition By Name)
          ,MinID   = min(ID) over (Partition By Name)
          ,MaxID   = max(ID) over (Partition By Name)
          ,MinDate = min(DATEEMPLOYED) over  (Partition By Name Order By DATEEMPLOYED)
          ,MaxDate = max(DATEEMPLOYED) over  (Partition By Name Order By DATEEMPLOYED Desc)
     From @YourTable
)
Select * from cteBase where Times>1

Returns
Name    Times   MinID   MaxID   MinDate     MaxDate
Jeff    3       3       5       2014-01-05  2016-02-05
Paul    2       1       2       2015-01-01  2016-01-01

A: Does your DB have NULL dates, if so you need to check for those.


text:
Q: Как управлять градиентов в SVG через CSS? Мне нужно чтобы при наведении на блок, у SVG появлялся градиент. Как это реализовать?

.container {
 width: 100px;
 height: 100px;
  background-color: #000;
          fill: #fff;
}
.container:hover .ico {
         fill: red;
  }
.ico {

}

  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid" width="58" height="58" viewBox="0 0 58 58">
    <path d="M0.000,57.999 L0.000,52.199 L58.000,52.199 L58.000,57.999 L0.000,57.999 ZM40.020,31.899 L18.009,31.899 L11.600,46.399 L5.075,46.399 L26.100,-0.001 L31.900,-0.001 L52.925,46.399 L46.400,46.399 L40.020,31.899 ZM29.000,6.988 L20.561,26.099 L37.439,26.099 L29.000,6.988 Z"
    class="cls-1" />
  </svg>

A: Думаю, по примеру все будет ясно. Плавность можно задать через transition.

.container {
 width: 100px;
 height: 100px;
  background-color: #000;
}
.container:hover .right {
         stop-color: orangered;
  }

  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid" width="58" height="58" viewBox="0 0 58 58">
    <defs>
        <linearGradient id="Gradient-1"
             x1="0" y1="0" x2="100%" y2="0">
            <stop offset="0%" stop-color="#fff" />
            <stop offset="100%" stop-color="#fff" class="right" />
        </linearGradient>
    </defs>
    <path d="M0.000,57.999 L0.000,52.199 L58.000,52.199 L58.000,57.999 L0.000,57.999 ZM40.020,31.899 L18.009,31.899 L11.600,46.399 L5.075,46.399 L26.100,-0.001 L31.900,-0.001 L52.925,46.399 L46.400,46.399 L40.020,31.899 ZM29.000,6.988 L20.561,26.099 L37.439,26.099 L29.000,6.988 Z"
    class="cls-1" fill= "url(#Gradient-1)" />
  </svg>


text:
Q: How can I echo "pass" or "fail" after a bash, curl, grep sequence? I'm big fan of elegant one-liners. I am trying to write a one-line test that outputs "pass" or "fail" after doing an http request and a search. I've tried something like this:
curl "http://haystack.io" | sed 's/.*?needle.*/PASS/' || echo FAIL

...but this doesn't fail properly.
Also tried:
curl "http://haystack.io" | if [$(grep -oE "needle") = "needle"]; then echo PASS; else echo FAIL; fi

...but I can't get the syntax quite right.
How can I do this?

A: If you're just looking for the needle, you can use grep -q to get an exit code:
if curl "http://haystack.io" | grep -q needle
then
  echo "PASS"
else
  echo "FAIL"
fi

The problem with your approach:
curl "http://haystack.io" | sed 's/.*?needle.*/PASS/' || echo FAIL

is that sed always returns success when the expression is valid, even when the replacement doesn't trigger. Plus, it uses BRE while your regex is PCRE.
In this one:
curl "http://haystack.io" | if [$(grep -oE "needle") = "needle"]; then echo PASS; else echo FAIL; fi

you're missing quotes and spacing (shellcheck will help out with that), and it also doesn't work if there are multiple matches.


text:
Q: How to watch for vuex state? I need do fire a function within component when my vuex state data change, but it does not work , is there any wrong usage about watch hook for vuex?
const state = {
     currentQueryParameter:[],

 };

 const mutations = {
    currentQueryParameter(state,info){
         state.currentQueryParameter[info.index]=info.value
          Vue.set(info, info.index,   info.value);
}
}

in component
  watch: {
       '$store.state.currentQueryParameter': function() {
        console.log("changed")
        this.getData()
  }
 },

A: What you are doing is technically correct and will work.
However several thing are still going wrong:

*

*If you want your state to be reactive you need to fill Arrays with native array methods (.push(), .splice() etc). Vue.set() is only used to set Object properties.

*You are watching currentQueryParameter, which is an Array. Its value does not change through your mutation - it stays the same Array. If you want to watch nested elements as well, you need to use the deep flag in your watcher, like so:
watch: {
  '$store.state.currentQueryParameter': {
    deep: true,
    handler(newVal) {
      console.log('queryParameter changed');
    }
  }
}

*I don't know what you are trying to do with this one in your mutation:
Vue.set(info, info.index,   info.value); but you should not mutate the properties you pass to a function.


text:
Q: Not every finite metric space embeds in an $\mathbb{R}^{k}$ This problem is present in "Supplements to the Exercises in Chapter 1-7 of Walter Rudin's Principles of Mathematical analysis" by Prof. George M. Bergman, which states as follows,
Let $X$ be a $4$-element set $\{w, x, y, z\}$, and let $d$ be the metric on $X$ under which the distance from $w$ to each of the other points is $1$, and the distance between any two of those points is $2$.

*

*Show that no function $f$ of $X$ into a space $\mathbb{R}^{k}$ is distance-preserving, i.e., satisfies $|f(p) - f(q)| =  d(p, q)$ for all $p, q \in X$.

*The above example has the property that every $3$-point subset of $X$ can be embedded (mapped by a distance-preserving map) into space $\mathbb{R}^{k}$ for some $k$, but the whole $4$-point space cannot be so embedded for any $k$. Can you find a $5$-point metric space, every $4$-point subset of which can be so embedded but such that the whole $5$-point space cannot?

I searched on the internet about this topic and found the Cayley-Menger determinant may be helpful to part 2. However, here is a concrete $5$-point case and I was wondering if there are some intuitive counterexamples? And I also have no clue about part 1, can anyone give me some hints on it. Thanks in advance.

A: *

*Suppose that $f$ exists. Without loss of generality, we may set $f(w) = 0$. Thus, $f(x)$, $f(y)$ and $f(z)$ must be the vertices of an equilateral triangle inscribed on the unit sphere, whose sides have length $2$. Alas, the largest equilateral triangles that you can inscribe on a unit sphere have sides of length $\sqrt 3$.

*In general, let $X = \{ w, x_1, \dots, x_n \}$. Turn $X$ into a metric space by setting $d(w, x_i) = 1$ and $d(x_i, x_j) = \lambda$, where $\lambda$ is just large enough that you can inscribe a regular simplex with $n-1$ vertices on the unit sphere, but not a regular simplex with $n$ vertices.

A: It is easy to prove that every $3$-point of $\{w, x, y, z\}$ can be embedded into $\mathbb{R}^{k}$ for $k=3$ by an equilateral triangle with vertex $x,y,z$ or straight lines $\{w,x,z\}$, $\{w,x,y\}$ and $\{w,y,z\}$.
A counterexample of $5$-point case is as follows, let $\{v^{\prime},w^{\prime},x^{\prime},y^{\prime},z^{\prime}\}$ be the image of $\{v, w, x, y, z\}$ under $f$. Assume, without loss of generality, $v^{\prime}$ is the origin, and we follow the same idea of part 1, and construct the $4$-point set $\{w^{\prime},x^{\prime},y^{\prime},z^{\prime}\}$ as an equilateral figure with length of side $1$ in $\mathbb{R}^{k}$, e.g., a regular $4$-simplex in $\mathbb{R}^{3}$. Let the distance between $v^{\prime}$ and other points are all equal to $r$. By the Jung's theorem\index{Jung's theorem}, the upper bound of radius of the minimum ball enclosing these $4$ points is $\sqrt{\frac{k}{2(k+1)}}$ and this bound is attained by the regular $k$-simplex in $\mathbb{R}^{k}$. Suppose the $5$-point set is Euclidean, then we can always find a regular $k$-simplex in $\mathbb{R}^{k}$ with vertices $\{w^{\prime},x^{\prime},y^{\prime},z^{\prime}\}$ and the center at origin $v^{\prime}$. Then the regular $k$-simplex can be enclosed by a closed ball $\overline{B}(v^{\prime},r)$. Since for $3 \leq k < +\infty$, we have
\begin{equation*}
    \sqrt{\frac{3}{8}} \leq r = \sqrt{\frac{k}{2(k+1)}} <\sqrt{\frac{1}{2}}
\end{equation*}
by letting $\sqrt{\frac{1}{3}} = r < \sqrt{\frac{3}{8}}$, such $v^{\prime}$ does not exist. Note that every $4$-points set is Euclidean since $\{w^{\prime},x^{\prime},y^{\prime},z^{\prime}\}$ can be a tetrahedron and $\{v^{\prime},x^{\prime},y^{\prime},z^{\prime}\}$ can be a equilateral triangle with center at $v^{\prime}$.


text:
Q: factory girl does not load a relation I'm using factory girl to test a rails app.
A user belongs_to Adresse.
I want to test a user with an adresse, here is my user factory :
# encoding: utf-8
require 'faker'

FactoryGirl.define do

  factory :user do
    nom_proprietaire    { Faker::Name.first_name }
    email    { Faker::Internet.email}
    raison_sociale    { Faker::Company.name}
    password               "password"
    password_confirmation  "password"
    adresse
  end

  factory :user_with_recurring_order_to_generate, parent: :user do
    after(:build) {|u| FactoryGirl.create(:contrat_with_active_product, :user=>u)}
  end
end

Here is my adresse factory :
# encoding: utf-8
require 'faker'

FactoryGirl.define do

  factory :adresse do
    nom_prenom   "qfsd"
    #{ Faker::Name.first_name }
    adresse_ligne_1    { Faker::Address.street_address}
    ville { Faker::Address.city}
    code_postal { Faker::Address.zip_code}
    pays { Faker::Address.country}
    telephone { Faker::PhoneNumber.phone_number}
  end
end

However when i use user in a test i have the following error :
ActiveRecord::RecordInvalid:
   La validation a échoué : Ville doit être rempli(e)

Meaning that i do not respect validate presence of ville for my adresse. How can i tell to factory girl to use my adresse factory when i want to create an adresse ?
EDIT : My code is fine, it's the faker gem who is broken for french...

A: My code is fine, it's the Faker gem that is broken for french.


text:
Q: Greedy UITabBarController? I'm making a custom UIViewController which holds to sub view controllers. They are put inside the main view controller this way:
- (void) setHeaderViewController:(UIViewController *)vc
{
    [self setViewController:vc isHeader:YES];
    _headerViewController = vc;
}

- (void) setDetailViewController:(UIViewController *)vc
{
    [self setViewController:vc isHeader:NO];
    _detailViewController = vc;
}

- (void) setViewController:(UIViewController*) viewController isHeader:(BOOL)isHeader
{
    UIViewController* viewControllerRef = ((isHeader) ? _headerViewController : _detailViewController);

    if(viewControllerRef == viewController)
         return;

    const CGSize selfSize = self.view.frame.size;

    CGRect viewFrame;

    if (isHeader)
    {
        viewFrame = CGRectMake(0, 0, selfSize.width, 150);
    }
    else
    {
        viewFrame = CGRectMake(0, 150, selfSize.width, selfSize.height-150);
    }

    UIView* viewControllerView = viewController.view;

    [viewControllerView setFrame:viewFrame];
    [viewControllerView setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | ((isHeader) ? UIViewAutoresizingFlexibleBottomMargin : UIViewAutoresizingFlexibleTopMargin))];

    [self.view addSubview:viewControllerView];
}

If I put two UIViewControllers inside of each sub view controller slot, the sizes defined in the method is respected. However, when putting a UITabBarController, it gets greedy and occupies the whole space:
UIViewController *vc = [[WIFCustomerDetailHeaderViewController alloc] initWithNibName:@"WIFCustomerDetailHeaderViewController" bundle:nil];
[self setHeaderViewController:vc];

UIViewController *vc1 = [[UIViewController alloc] init];
vc1.title = @"Personal Data";
vc1.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Personal Data" image:nil tag:0];
vc1.view.backgroundColor = [UIColor redColor];
vc1.view.frame = CGRectMake(0,400,100,100);

UIViewController *vc2 = [[UIViewController alloc] init];
vc2.title = @"Diagnosis";
vc2.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Diagnosis" image:nil tag:0];
vc2.view.backgroundColor = [UIColor purpleColor];
vc2.view.frame = CGRectMake(0,500,50,50);

NSArray *tabs = [[NSArray alloc] initWithObjects:vc1, vc2, nil];

WIFCustomerDetailTabViewController *tvc = [[WIFCustomerDetailTabViewController alloc] init];
[tvc setViewControllers:tabs];

[self setDetailViewController:tvc];

Does anyone knows what can be happening here? I can't find the cause...
Images below..

A: Documentation for the UITabBarController class says, "you must install this view as the root of your window. Unlike other view controllers, a tab bar interface should never be installed as a child of another view controller".
It seems that you're attempting a design that's specifically not supported.


text:
Q: javascript sort of HTML elements in-place in continuation for javascript sort of HTML elements
I want to sort elements in different
( eventually in
)
the sort should preferably be in-place and not to unwrap(),sort() and wrap
HTML

I

IXX

I

I

I

I

I

I

IXX

I

I

I

I

I

st

st

st

javascript
var sort_by_name = function(a, b) {
    return a.innerHTML.toLowerCase().localeCompare(b.innerHTML.toLowerCase());
}

var list = $(".table > li").get();
list.sort(sort_by_name);
for (var i = 0; i < list.length; i++) {
    list[i].parentNode.appendChild(list[i]);
}

the result I look for is

I

I

I

I

I

I

I

I

I

I

I

I

IXX

IXX

st

st

st

let a,b be DOM elements, and a appear lower on the list than b (lower is position in the document ) and value(a) > value(b) then a and b will be switched in the document. no matter that a and b may not be siblings.
http://jsfiddle.net/yqd3w/7/

A: To speed the task up by doing less comparisons, you can do:
$(".table").each(function(){
    var list = $(this).children().get().sort(sort_by_name);
    for (var i = 0; i < list.length; i++)
        this.appendChild(list[i]);
});

...although it does not affect the result.

EDIT: OK, I got you:
var $t = $(".table");
var list = $t.children().get().sort(sort_by_name);
$t.map(function() {
    return {t:this, l:this.childNodes.length};
}).each(function(i, o) {
    $(o.t).append(list.splice(0, o.l));
});


text:
Q: Is this a bad wireless card? I have been having a weird wifi card issue.
First, the hardware details from lshw:

*

*product: Intel(R) Core(TM) i5-2450M CPU @ 2.50GHz

*wifi card: Intel(R) Centrino(R) Wireless-N + WiMAX 6150

*computer maker: Asus

I have a Wireless router which other computers can easily connect to. The router has WPA personal security on it. When I was bringing up the computer on Ubuntu 14.04 LTS, here's what I have observed in /var/log/syslog.
Can I do something without the card replacement? Or am I out of luck?
Update: I tried the suggesting given by @karel. Some more info on the wireless card now being identified properly
$> lshw -c network
*-network
   description: Wireless interface
   product: Centrino Wireless-N + WiMAX 6150
   vendor: Intel Corporation
   physical id: 0
   bus info: pci@0000:02:00.0
   logical name: wlan0
   version: 67
   serial: 40:25:c2:c2:4b:c0
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress cap_list ethernet physical wireless
   configuration: broadcast=yes driver=iwlwifi driverversion=3.13.0-24-generic firmware=41.28.5.1 build 33926 ip=192.168.0.111 latency=0 link=no multicast=yes wireless=IEEE 802.11bg
   resources: irq:51 memory:de800000-de801fff

Update 1: $> iwconfig

wmx0      no wireless extensions.

eth0      no wireless extensions.

lo        no wireless extensions.

wlan0     IEEE 802.11bg  ESSID:off/any
      Mode:Managed  Access Point: Not-Associated   Tx-Power=15 dBm
      Retry  long limit:7   RTS thr:off   Fragment thr:off
      Encryption key:off
      Power Management:off

Update 2: I did:

*

*modprobe -r iwlwifi

*modprobe iwlwifi

and then observed this log in /var/log/syslog.

Update 3:
modinfo iwlwifi is here. I did an rmmod on iwldvm and then modprobe iwldvm.

A: It's not yet clear what fixed my problem but it seems to work. There are a bunch of things that appear to have to come together for it to work well. I am somewhat puzzled why this has to be this hard.

*

*It seems that having options iwlwifi 11n_disable=1 in /etc/modprobe.d/iwlwifi helps.

*Suggestions in this thread seem to help, given that we started having these issues since Trusty.

*Experimenting with country regulatory domain (as explained here) seems to have helped.

*I also tried with a few kernels, not sure if that helped. Right now, I am using the kernel that Trusty comes with (3.14.1-031401-generic)

All of this is empirical, as you can see. But it seems to help. I am updating this answer using the same wireless card that was not working at all.


text:
Q: Copy cell (A1) of sheet VN to the first open cell in column F of sheet VL, then A2 to the next open cell in F I'm trying to write a macro to copy the contents of cell A1 of sheet wsVN to the first open cell in column F of sheet wsVL, then copy A2 to the next open cell in F, then A3 to the next and so on up to A305. Sheet VL has a header row with the first open cell being F2. That's where I'm trying to past A1. Then I have a couple rows with data then another open cell where I'd like to past A2. Then 5 rows of data before the next open cell where A3 should go. Here is as close as I have made it so far:
Sub Data_Transfer()
 '
 ' Data_Transfer Macro
 ' Transfers VariableNames Data to the next available row of sheet VariableList.

    Dim lastRow As Integer
    Dim wsVN As Worksheet
    Dim wsVL As Worksheet
    Dim sourceRange As Range
    Dim targetRange As Range

    Set wsVN = Worksheets("VariableNames")
    Set wsVL = Worksheets("VariationList")

    If Len(wsVL.Range("F1").Value) > 0 Then

        lastRow = wsVL.Range("F2").End(xlDown).Row
    Else

        lastRow = 2
    End If

    Set sourceRange = wsVN.Range("A1")
    Set targetRange = wsVL.Range("F" & lastRow).Offset(1, 0)

    sourceRange.Copy
    targetRange.PasteSpecial _
        Paste:=xlPasteValues, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False

    Application.CutCopyMode = False

 End Sub

Hopefully someone will offer some guidance on this. It would be appreciated very much!
Thanks

A: Try this, adjusting sheet names to suit.
Sub x()

Dim r As Range

With Worksheets("Sheet1") 'source sheet
    For Each r In .Range("A1", .Range("A" & Rows.Count).End(xlUp))
        Worksheets("Sheet2").Range("F:F").SpecialCells(xlCellTypeBlanks)(1).Value = r.Value 'destination sheet
    Next r
End With

End Sub

More on SpecialCells.


text:
Q: Why are borrows not allowed in mutable function's argument Title is probably a bit confusing, what I mean is that when I try to compile:
if folder_file_paths.len() > compressed_data.len() {
    compressed_data.reserve(folder_file_paths.len() - compressed_data.len() );
}

I get this error:
error[E0502]: cannot borrow `compressed_data` as immutable because it is also borrowed as mutable
   --> src/ImageMatching/main.rs:33:59
   |
33 |         compressed_data.reserve(folder_file_paths.len() - compressed_data.len() );
   |         ---------------                                   ^^^^^^^^^^^^^^^       - mutable borrow ends here
   |         |                                                 |
   |         mutable borrow occurs here                        immutable borrow occurs here

But I can't think of a reason why this is a problem, as shouldn't the argument be processed first, the resulting usize value be copied, and then the reserve function run?
When would the argument of a function be calculated after the actual function starts executing?
Edit: folder_file_path is a Vec, and compressed_data is a HashMap


text:
Q: Display range when user clicks or enter textbox and validate in asp.net How to display a popup with a textbox range when the user tabs into the textbox or clicks it and validate it if the user enters a non-range value in asp.net? Currently i'm using js and css to display a panel using z-index, but no validation. Is there a better way?
I tried the Ajax Validator controls but it seems they only popup when the user leaves the textbox. And also, the textbox's are dynamically created.

A: If the range for the textbox is fixed you have to use only javascript. Incase you need validation for dynamic content you must call web methods or webservices using ajax.
The Markup will be like this
<asp:ScriptManager ID="ScriptManager1" runat="server"
  EnablePageMethods="true" />
<script language="javascript">
 function UpdateTime() {
   PageMethods.GetCurrentDate(OnSucceeded, OnFailed);
 }

 function OnSucceeded(result, userContext, methodName) {
   $get('Label1').innerHTML = result;
 }

 function OnFailed(error, userContext, methodName) {
   $get('Label1').innerHTML = "An error occured.";
 }
</script>
<asp:Label runat="server" ID="Label1" Text="Update Me!" /><br />
<input type="button" id="Button2" value="Web Method Update"
  onclick="UpdateTime();" />

You must enable the page methods of the script manager and call the method written in page back as PageMethods.YourMethodName(JavascriptMethodIfCallingSuccess,JavascriptMethodOnError);
You can write the page back code in c# as below
[WebMethod]
public static string GetCurrentDate()
{
  return DateTime.Now.ToLongDateString();
}

Now you will get the return value from server in your javascript. Don't use this method if your validation is always fixed and if server side validation not required. It may cause unwanted load for your page and server.


text:
Q: Remove a particular variable from session variable In my web application in some point, I save to the session an object.
session.setAttribute("product", product);

How can I delete this particular variable? I searched it and i find only HttpSession.invalidate(). However this will kill my session.

A: Just as there is
session.setAttribute("foo", foo);

there is also
session.removeAttribute("foo");

You wouldn't want to use session.invalidate() because that would kill your session and you wouldn't be able to use it afterwards.

A: Try this:
session.removeAttribute("product")

A: There is a removeAttribute("name") in the session, you can use that.


text:
Q: How to make it clear when laptop is on battery in 18.04? In Ubuntu 18.04, the default icons showing whether the laptop is on battery or plugged in, are quite similar:

*

* → Plugged in

*  → Battery

Its really easy to miss when the laptop accidentally unplugs.
Is there a way to make the  icons different, or to make it more prominent when the laptop is on battery?

A: I solved this by going to Tweaks → Top Bar → Turn on Battery Percentage.

Now the battery percentage is shown as a number, so if unplugged, the number shows as declining which is more attention grabbing than the icons.

A: From the attached pics in your Question gives clue that those icons are named as
battery-good-charging-symbolic.svg and
battery-good-symbolic.svg

There are similar Images with naming which can be understood easily.
First determine which icon theme is being used.
And then copying this Icon theme into ~/.icons directory and replacing the image with your preferred one but with same name of icon will change the symbol.
There is a good documentation here.


text:
Q: отрисовка через DrawString с разными цветами Как мне отрисовать строку разными цветами?
    RectF origin(250.f, 50.f, 500.3f, 100.0f);
    Font myFont(L"Arial", 16);
    StringFormat sf(StringFormatFlagsNoClip);
    sf.SetLineAlignment(StringAlignment::StringAlignmentNear);
    SolidBrush white(Color(255, 100, 116, 123));
    SolidBrush blackBrush(Color(255, 255, 255, 255));

            wchar_t buff[100];
            swprintf(buff, 100, L"Зеленый Красный");
            gt->DrawString(
                buff,
                -1,
                &myFont,
                origin,
                &sf,
                &blackBrush);

Как мне нарисовать слово "Зеленый" Зеленым, а "Красный" Красным?


text:
Q: Angular 9: Using Modal in ngFor loop I have a list of varieties generated by a for loop. Each item in that list has a button beside it so that particular list item can be updated. Each button will open up a modal where you can enter new informations. I don't want an unlimited amount of modals on the page, so I put the modal inside the for loop and want to pass the a iterator to the modal but always it displays the value 0 which is the first value of a.
<tr *ngFor="let a of list; ; let i=index" >
    <td> {{ i }} </td>
    <td> <button data-toggle="modal" data-target="#editproject">Update</button> </td>
    <div class="modal fade" id="editproject">
       <input type="text" id="edit-contact-name" class="form-control" placeholder="{{ a }}" >
    </div>
</tr>

A: I am not sure you can use {{}} inside input element .
You can create a modal component .
and pass the value of 'a' to the component as an attribute .
<modal-component [a]="a"></modal-component>


text:
Q: Form post to Wordpress page = wrong template I'm using permalinks and I have a page with a slug like this:
http://www.mysite.com/jobs/

The page uses a specific template for itself.
On another page I have a form that I submit as POST to http://www.mysite.com/jobs/. However, when the form is submitted, it takes me to the proper /jobs/ page, but the template is not correct. Even though the url is correct. I appears to use maybe the index or default template for some reason. If I click in the address bar of the browser and press enter to re-visit the same page, then the proper template appears.
It's like submitting a POST form to this page makes it use the wrong template even though the permalink slug is exactly the same as when I visit it normally.
Any clues?

A: Make sure your form elements aren't using any names that WordPress uses, like name or s, this will cause the behavior you describe because it changes the type of query. Give them all names you are certain are unique.


text:
Q: Add a span tag to certain characters in a string with javascript/jquery I have output from a CMS where I need to add a style to a certain character in the string. For instance, my output is:

12 // 14 // 2013

How can I add:

to the two double slashes so that my result would be:

12 // 14 // 2013

A: Try this:
var original = $('.date').text();
var new_version = original.split('//').join('//');
$('.date').html(new_version);

Fiddle
If you have many div like the example you posted, you can use this:
$('.date').each(function () {
    var original = $(this).text();
    var new_version = original.split('//').join('//');
    $(this).html(new_version)
});

Fiddle

A: var elements = document.getElementsByClassName('date');
for (var i = 0, e; e = elements[i++]; ) {
   e.innerHTML = e.innerHTML.replace(/\/\//g, '//');
}

or the jQuery way:
$('.date').each(function () {
  $(this).html($(this).html().replace(/\/\//g, '//'));
}


text:
Q: Drop event not firing in jQuery UI. I am trying to create a small program that allows a user to put pieces of equipment together to construct a picture of a device. the end product will look and function like this: http://oliverdjones.com/learning/nebulizer.swf
here's the current version: http://oliverdjones.com/learning/dragtester.html
I am using jQuery UI. The drag events are working as expected but I have not yet been able to make the drop event fire and I am completely out of ideas. Here's the code:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>drag test</title>

Please Assemble

A: This is being caused by the margin applied to the draggable node.  If you remove these CSS declarations this should work as expected.
 .part1 { margin-top:15%; margin-left:57%; }

This is a known jQuery UI bug, see http://bugs.jqueryui.com/ticket/6876.


text:
Q: Google Sheets: Add 200 to new rows "after" number format change I'm continually adding new rows to Google Sheets with numerical values in Column C. I need a script (not a formula!) to do 2 things with those numbers.

*

*Change the number format to remove commas from any numbers

*Add 200 to each number

I've got the script for part 1...
function setFormat(){SpreadsheetApp.getActiveSheet().getRange("C2:C").setNumberFormat('##########0');}

But I need help with part 2.
Both scripts need to occur immediately upon creation of the number in Column C.
I can't use formulas for these changes. I need to use scripts.
Thank you!

A: You can write whole code within onEdit() function
like this:
function onEdit(e){
  var range = e.range;
  if(range.getColumn() == 3){  //Column C is 3rd column
    SpreadsheetApp.getActiveSheet().getRange("C2:C").setNumberFormat('##########0');
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getActiveSheet();
    var  r = e.source.getActiveRange();
    var cell = r.getA1Notation();
    var tempval = sheet.getRange(cell).getValue();
    var numval = parseFloat(tempval)+200;
    sheet.getRange(cell).setValue(numval);
  }
}

Hope this will help you.
Thanks.


text:
Q: Scroll function executes also when page loads I made a jsfiddle as an answer to How to build fullscreen slider like this? (now on hold)
I know scrolling too fast bugs it and that scrolling both ways does the same thing, but my problem is that when the page loads, it automatically scrolls once
Code I used is
var leftImg = document.getElementsByClassName('left');
var rightImg = document.getElementsByClassName('right');
var cur = 0;
for (i=0; i<3; i++){
    leftImg[i].style.zIndex = rightImg[i].style.zIndex = -(i+1);
}

window.onmousewheel = changeImage();

function changeImage() {
  leftImg[cur].style.top= "-100%";
  rightImg[cur].style.top= "100%";
  setTimeout(function(){
    window.onmousewheel = changeImage;
  leftImg[cur].style.zIndex=rightImg[cur].style.zIndex=-(cur+4);
  leftImg[cur].style.top=rightImg[cur].style.top="0";
  cur++;
  if(cur === 3) {
    cur = 0;
for (i=0; i<3; i++){
    leftImg[i].style.zIndex = rightImg[i].style.zIndex = -(i+1);
}
  }
}, 3000);
  window.onmousewheel = preventDefault;
}

Why?

A: EDITED #2
No need for the loop nor TimeOut
var cur = 2;
var zIndex = -1;

window.onmousewheel = changeImage;
function changeImage() {

    var leftImg = document.getElementsByClassName('left');
    var rightImg = document.getElementsByClassName('right');
    leftImg[cur].style.top = "-100%";
    rightImg[cur].style.top = "100%";
    if (leftImg[(cur + 1) % 3].style.top === "-100%") {
        leftImg[(cur + 1) % 3].style.zIndex = rightImg[(cur + 1) % 3].style.zIndex = (zIndex);
        leftImg[(cur + 1) % 3].style.top = rightImg[(cur + 1) % 3].style.top = "0%";

    }
    zIndex--;
    cur--;
    if (cur === -1) {
        cur = 2;
    }

}

See fiddle