text:
Q: Confused About Objects and Classes in CodeIgniter? I'm fairly new to CodeIgniter and have a question. I'm a bit confused about Classes, Libraries and Objects.
Does CodeIgniter replace the normal PHP way of usings objects i.e. $var = new car(); with libraries i.e. $this->load->library('some_library'); $this->some_library->some_function(); ?
If both are valid, is there a difference? If so, what are the differences and when do I use one over the other?  Which is more common/proper?
I am asking because I created a class, but I'm not certain what is the correct manner in which to instantiate it.
Thanks in advance

A: I am not familiar with CodeIgnitier. But familiar with other PHP frameworks. Most of frameworks use this way for performance improvements, registering things, executing certain events, and making things simpler for developer...
For example if you want to create class "car" with is somewhere in library directory you would have to include the file first before you can create object of that class (miltiple lines of code, more room for error). The framework will create the class and includes related files in 1 line of code (easier and safer).
Framework way also works as a factory. Instead of recreating an object, it will create object only once and every time you call the method again it will return the reference to existing object.
More things are happening behind the scenes when you use framework. Things are getting registered, etc...

A: CI doesn't replace class behavior per se, it simply adds functionality that allows access to custom libraries/models/views as singleton objects via the core object for simplicity.
Nothing is stopping you from creating (as I have in one of my projects) additional files with classes for non-singleton entities and require them in a model for further use. On hindsight, I should probably have used helpers for this.
What the loader ($this->load) class does, among other things, is it creates a single object of the specified class (model, library or view - not helpers though, see below) and attaches it as a property of the core class that is normally accessible via $this.
Helpers are a bit different. They are not attached, but instead simply 'read' into the global namespace from the point where they are loaded.
To answer your question, it would be more proper to use the loader class in instances where you don't need more than one instance of a class created. If you need 'entity' classes, your best CI-compliant bet would be to create them as helpers.

A: Given only this context, this looks like Inversion of Control (maybe I'm wrong, I haven't looked too closely at CodeIgniter).
You don't want to rely on the type car as in new car(). What if later you want to make $var a racecar? $var can still do the same things, but it is forced to be a car because you constructed it directly. Or what if you are testing this class, but car is some complex object which calls some external service. You want to test your logic, but don't care if the car service isn't working. So you should be able to change $var to actually load a mockcar. You can't do that if you do $var = new car().
What is Inversion of Control?


text:
Q: Sending foreign characters in c I tested this but it won't work. The foreign characters get lost.
char message [] = "stringtobesendedwithforeigncharacters도쿄";

t = 39;

while(curler < t) {
    r = send(sockfd, message, t, 0);
    if(r > 0) {
        curler += r;
    }
}

What's the easiest way to do this?

A: Try
char message[] = "stringtobesendedwithforeigncharacters도쿄";
t = sizeof(message)-1;

for starters.

A: You have a typo in message declaration and you assign incorrect size to t as other guys have already pointed out.
This article will maybe help you: Unicode in C and C++: What You Can Do About It Today

A: Use wchar_t instead of char and functions for this type.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Waterfall chart on echarts4r? Hi and thanks for reading me
I'm working with a bar chart on R with the Echarts4r package, but I want to do a waterfall chart and I don't find an option to do a plot like the following on the image:

It's possible to do this chart type? The code I'm using for now is the following:
library(echarts4r)

df <- data.frame(

  var = sample(LETTERS, 5),
  value = rnorm(5, mean = 200, sd = 100)
)

df |>
  e_charts(var) |>
  e_bar(value)

A: Not sure whether echarts4r offers an option out of the box but with some data wrangling you could achieve your result as a stacked bar chart like so:
Disclaimer: I borrowed the basic idea from here.
library(echarts4r)
library(dplyr)

set.seed(42)

df <- data.frame(
  var = sample(LETTERS, 5),
  value = rnorm(5, mean = 200, sd = 100)
)

df |>
  mutate(bottom = cumsum(dplyr::lag(value, default = 0)),
         bottom = ifelse(value < 0, bottom + value, bottom),
         top = abs(value)) |>
  e_charts(var) |>
  e_bar(bottom, stack = "var", itemStyle = list(color = "transparent", barBorderColor  = "transparent")) |>
  e_bar(top, stack = "var")


text:
Q: Lifetime of the object returned by std::string::substr I need to know whether the following is valid in general.
string s = "some value";
string v = s.substr(0, 50).c_str();

Is the assignment to v always valid? Can there be any issues due to the temporary lifetime of object returned by substr().

A: It's valid here. The temporary returned by substr is destroyed after the full expression; which includes the initialization of v.

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation. This is true even if that evaluation ends in throwing an exception.

BTW: This is not assignment but initialization (construction) of v.

A: The assignment to v is valid. Temporary objects are not destroyed until the end of the whole statement is finished (when the ; is reached), which is after the assignment is complete.
However, in this particular example, the use of c_str() is redundant and inefficient. It requires iterating the char data to determine its length, which the temp string returned by substr() already knows, so just assign the returned string as-is:
string v = s.substr(0, 50);

A:
substr returns a newly constructed string object with its value
  initialized to a copy of a substring of this object.

So you are safe

A:
Once you've assigned a variable, it is under the protection of the
  scope of the variable. It will not change till you change it, or it
  loses scope, as I said. There is only a "temporary lifetime" if you
  have the instantiation nested.

My own quote above. All you're asking about is "How or when does the .substr function look in the memory for it, and does it stay in memory?" The answer is its copy is in the assignment to the left value. Considering that, the .substr function's action on the memory is lost. So yes it is temporary. But as I vaguely asserted already, that is temporal to the scope of the variable.


text:
Q: Inspect value of a tensor in Tensorflow 2.0 I struggle to apply answers to similar questions, with Tensorflow 2.6.0.
I would like to inspect the values in my tensor during debugging. If I do a Python print
predicted_ids=tf.random.categorical(predicted_logits, num_samples=1)
predicted_ids=tf.squeeze(predicted_ids, axis=-1)
print(predicted_ids)

I get
Tensor("Squeeze:0", shape=(1,), dtype=int64)

I then try to
(1)
print(tf.Print(predicted_ids, [predicted_ids], message="This is predicted_ids: "))

(2)
with tf.Session() as sess:  print(predicted_ids.eval())

(3)
sess = tf.InteractiveSession()
a = tf.Print(predicted_ids, [predicted_ids], message="This is predicted_ids: ")

All of which will throw errors. It seems to me this is a very common question, and there must be an elegant robust simple answer, in TF 2.6.0.

A: It is fairly simple:
For example:
tf.random.categorical(tf.math.log([[0.5, 0.5]]), 5).numpy()
Output:
array([[0, 1, 1, 0, 0]])
In your case:
predicted_ids.numpy()

A: I think you don't need to create a session as .eval() function is compatible with TensorFlow v1.
The code which works for me fine is to use tf.print() function. Here's a quick demo:
c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
d = tf.constant([[1.0, 1.0], [0.0, 1.0]])
e = tf.matmul(c, d)
print(tf.print(e))


text:
Q: understanding container template parameter of `std::stack` What exactly does the second template parameter of std::stack represent? For example, in the following code, what does std::vector<int> imply?
std::stack<int, std::vector<int>> fourth(myvector);

A: std::vector<int>

specifies the container used by std::stack<int> to store the values internally.
The template signature of std::stack is
template<
    class T,
    class Container = std::deque<T>
> class stack;

Check the explanations on the Container template parameter here please.
You can specify container classes that fulfil the requirements of a Sequence Container there. The default container type is std::deque<T>, if you omit the template parameter specification.

NOTE:
To avoid any misconceptions from your side, about the wrapping done by std::stack<> around these container instances:
std::stack<int,std::vector<int> > fourth (myvector);

Matches the explicit stack( const Container& cont ); constructor signature, which

1) Copy-constructs the underlying container c with the contents of cont. This is also the default constructor (until C++11)

Thus, the myvector and the fourth instances are independent after the construction of fourth. Manipulating either of them does not affect the other.
The std::vector<int> instance used by fourth is managed internally.

A: Look at the template parameters for std::stack:
template< class T, class Container = std::deque<T>> class stack;

std::stack is a container adapter and it default wraps std::deque. This code changing it so that fourth wraps an std::vector instead.


text:
Q: AngularJS and php array data I recently started learning AngularJS. When I getting data from the database an array, I using function foreach, so my code is

     <?php foreach($Items as $Item):?>

<?php echo $Item['name'];?>

     <?php endforeach;?>

I use AngularJS because I need sortable list elements. And my code with AngularJS roughly the

{{position.name}}

Is it possible to do so? If not, how to get the data received from server, If not use $http.post/get?

A: You can use ng-init to keep your model in a separate file:
<ul ng-init="positions = <?php echo htmlspecialchars(json_encode($Items)); ?>">

{{position.name}}


text:
Q: Precision Lost for Simultaneous NonLinearModelFit I am having trouble with the below code. I have two data sets, dataf and datag, which are exponential decays. datag decays faster than dataf. These two data sets are then later joined to make datah. I would like to simultaneously fit these two data sets with the functions f[x] and g[x], respectively. In the NonLinearModelFit of datah I use suitable initial conditions for the values of a and b, but as can be seen from the below plot the fits are not good. If I don't use initial conditions, I get the following error message: "General::munfl: Exp[-1.25177*10^10] is too small to represent as a normalized machine number; precision may be lost", and other similar error messages.
dataf = Table[{x, Exp[-x/250]}, {x, 0, 500, 50}];
datag = Table[{x, Exp[-x/100]}, {x, 0, 500, 50}];

datah = Join[{1, Sequence @@ #} & /@ dataf, {2, Sequence @@ #} & /@
    datag];

f[x_] := Exp[-47000^2 ((a (4 a^2 + 21 a b + 9 b^2))/(
     30 (a + b) (4 a + b))) x];
g[x_] := Exp[-130000^2 ((a (4 a^2 + 21 a b + 9 b^2))/(
     30 (a + b) (4 a + b))) x];

h[\[Omega]_, x_] :=
  KroneckerDelta[\[Omega] - 1]*f[x] +
   KroneckerDelta[\[Omega] - 2]*g[x];

Clear[a, b]

nlmf = NonlinearModelFit[datah,
   h[\[Omega], x], {{a, 10^-12}, {b, 10^-12}}, {\[Omega], x}];

Show[ListPlot[{dataf, datag}, PlotMarkers -> {\[FilledCircle], 10},
  Joined -> False], Plot[{nlmf[1, x], nlmf[2, x]}, {x, 0, 500}]]

nlmf["ParameterConfidenceIntervalTable"]

If the exponential decays are quicker and the values inside the exponentials are smaller then the fits become reasonable. If anyone has any suggestions about how to resolve this issue then that would be greatly appreciated. Thanks.

A: There's a very simple answer to your question: you have only one free parameter in your fitting function.
You may think you have two of them, $a$ and $b$, but in reality, you only have one, let's name it $c$:
$$c = \frac{a (4 a^2 + 21 a b + 9 b^2)}{ (a + b) (4 a + b)}$$
The functions you are trying to fit are then:
$$f(x) = e^{-\alpha c x}, \quad g(x) = e^{-\beta c x}, \quad \alpha=\frac{220900000 }{3}, \beta=\frac{1690000000}{3}.$$
This means that the two exponentials have a predefined ratio of their decays. That is:
$$\frac{\text{decay rate of }f(x)}{\text{decay rate of }g(x)} = \frac{\alpha c}{\beta c} = \frac{\alpha}{\beta}= \frac{2209}{16900}\approx 0.13.$$
Therefore, when you decide about the decay rate of $f(x)$, you also fix the other one. But look at your data! dataf decays with the rate $-1/250$ and datag with $-1/100$. Their ratio is $2/5 = 0.4$.
\[Alpha] = 220900000/3;
\[Beta] = 1690000000/3;
f[x_, c_] := Exp[-\[Alpha] c x];
g[x_, c_] := Exp[-\[Beta] c x];
h[\[Omega]_, x_, c_] :=
 KroneckerDelta[\[Omega] - 1]*f[x, c] +
  KroneckerDelta[\[Omega] - 2]*g[x, c]

Manipulate[
 Show[Plot[Evaluate[{h[1, x, c], h[2, x, c]}], {x, 0, 500},
   PlotRange -> {0, 1}], ListPlot[{dataf, datag}]], {c, 0, 1*^-10}]

I don't really know what the underlying model is and why you are trying to simultaneously fit both of the curves. You can, of course, fit each of them separately with their own $c$ (or $a$ and $b$, if you want).
nlmf = NonlinearModelFit[#[[1]], Exp[-#[[2]] c x], {{c, 1*^-10}},
    x] & /@ {{dataf, \[Alpha]}, {datag, \[Beta]}}

Show[ListPlot[{dataf, datag}],
 Plot[Evaluate@Through[nlmf[x]], {x, 0, 500}]]


text:
Q: How to arrange tabular in alphabetical order I have this code, which I want to arrange in alphabetical order:
\section{Abbreviations}
\doublespacing
\begin{tabular}{p{4cm}p{12cm}}
\textbf{AD}  & Alzheimer's disease \\
\textbf{FAD}  & Familial Alzheimer's disease \\
\textbf{LOAD}  & Late-onset Alzheimer's disease \\
\textbf{A\textbeta\ }  & Amyloid- \textbeta\  \\
\textbf{APP}  & Amyloid precursor protein \\
\textbf{GWAS}  & Genome-wide-association studies \\
\textbf{SNP}  & Single nucleotide polymorphisms \\
\textbf{CXCL10}  & C-X-C motif chemokine 10 \\
\textbf{OAS1}  & 2'-5'-oligoadenylate synthase 1\\
\textbf{TREM2}  & Triggering receptor expressed on myeloid cells 2 \\
\textbf{R47H KI}  & \textit{Trem2} R47H knock-in mice \\
\textbf{APP KI}  & \textit{APP\textsuperscript{NL-G-F}} knock-in mice \\
\textbf{WT}  & Wild type  \\
\textbf{HO}  & Homozygous \\
\textbf{HET}  & Heterozygous \\
\textbf{P1-P3}  & Postnatal day 1-3\\
\textbf{RT-qPCR}  & Real-time Quantitative PCR  \\
\textbf{CT}  & Cycle threshold \\
\textbf{IHC}  & Immunohistochemistry \\
\textbf{PBS}  & Phosphate-buffered saline \\
\textbf{PBST}  & Phosphate-buffered saline 0.3\% Triton \\
\textbf{TBS}  & Tris-buffered saline \\
\textbf{TBST}  & Tris-buffered saline 0.1\% Tween-20 \\
\end{tabular}

How can I do that? Help is hugely appreciated. Thanks!

A: First, remove all \textbf{}. Load array and use the command >{\bfseries} to make the first column boldface.
Thereafter, see if your text editor has a line sorting function, mark all the lines that you want to sort, and sort them. If not, copy the lines to a word processor or spreadsheet, or save the lines as a text file and pipe it through a the sort filter at your operating system command prompt (Windowds command line sort < tobesort.txt > sorted.txt), and sort.
You have to check the ISO sorting rules for you language to decide where to place the Greek letter. In Norwegian, the Aβ was sorted as the last line starting with A.
Unless you have tens of similar tabulars to sort, this approach is the simplest and fastest, if not someone provide a sorting algorithm that can sort according to your language requirements.

\documentclass{article}
\usepackage{array}

\begin{document}

\section{Abbreviations}

\begin{tabular}{@{}>{\bfseries}p{4cm}p{12cm}@{}}
AD  & Alzheimer's disease \\
APP  & Amyloid precursor protein \\
APP KI  & \textit{APP\textsuperscript{NL-G-F}} knock-in mice \\
A\boldmath{$\beta$}\   & Amyloid-$\beta$\  \\
CT  & Cycle threshold \\
CXCL10  & C-X-C motif chemokine 10 \\
FAD  & Familial Alzheimer's disease \\
GWAS  & Genome-wide-association studies \\
HET  & Heterozygous \\
HO  & Homozygous \\
IHC  & Immunohistochemistry \\
LOAD  & Late-onset Alzheimer's disease \\
OAS1  & 2'-5'-oligoadenylate synthase 1\\
P1-P3  & Postnatal day 1-3\\
PBS  & Phosphate-buffered saline \\
PBST  & Phosphate-buffered saline 0.3\% Triton \\
R47H KI  & \textit{Trem2} R47H knock-in mice \\
RT-qPCR  & Real-time Quantitative PCR  \\
SNP  & Single nucleotide polymorphisms \\
TBS  & Tris-buffered saline \\
TBST  & Tris-buffered saline 0.1\% Tween-20 \\
TREM2  & Triggering receptor expressed on myeloid cells 2 \\
WT  & Wild type  \\

\end{tabular}

\end{document}


text:
Q: Why does Lubuntu not respect my keyboard preferences? I've just installed Lubuntu 14.04 on my laptop (replacing the previous dual boot Ubuntu 13.10 / Windows 7, which my poor little laptop really didn't have the space for). As part of the installation process, I was asked to select my keyboard layout. I selected Irish, and double-checked that the problematic keys (", @, €) worked correctly. Everything seemed fine.
Now that the installation is complete, however, I have a US keyboard with no obvious way to change it (and no obvious way to type the € symbol). I am, of course, interested in fixing this, but I'd also like to know why this happened in the first place.

A: Right click on the Keyboard Layout Handler icon in your LXPanel.  Choose Keyboard Layout Handler settings.  Untick Keep system layouts and then click add.  Choose Irish which I believe will show up as ie.  You can then move it to the top to have it be the default or keep it where it is and just toggle when you need it.  Check Keep system layouts.  I believe that it will not take effect until the next boot.


text:
Q: What's wrong with sorting this multidimensional array? So I have to display this array using Java GUI, it's for a basketball season. We have team name, wins, losses and status. There are 10 teams
I sort base on wins, descending order.I used bubble sort. The problem is when I tested the program, sometimes it only displayed 9 team names. 1 was missing and I don't know why, the wins,losses and statuses still displayed.
Here is the code:
int a,b,t;
String hTeam;
for(a=1;a<ConferenceSize;a++)
    for (b=ConferenceSize-1; b>=a;b--){
        if (Conference[b-1].wins<Conference[b].wins){

            t=Conference[b-1].wins;
            Conference[b-1].wins=Conference[b].wins;
            Conference[b].wins=t;

            hTeam = Conference[b-1].team;
            Conference[b -1].team=Conference[b].team;
            Conference[b].team=hTeam;

        }

    }

//OUTPUT
Team1name.setText(Conference[0].team);
Team2name.setText(Conference[1].team);
Team3name.setText(Conference[2].team);
Team4name.setText(Conference[3].team);
Team5name.setText(Conference[4].team);
Team6name.setText(Conference[5].team);
Team7name.setText(Conference[6].team);
Team8name.setText(Conference[7].team);
Team9name.setText(Conference[8].team);
Team10name.setText(Conference[9].team);

Team1win.setText(String.valueOf(Conference[0].wins));
Team2win.setText(String.valueOf(Conference[1].wins));
Team3win.setText(String.valueOf(Conference[2].wins));
Team4win.setText(String.valueOf(Conference[3].wins));
Team5win.setText(String.valueOf(Conference[4].wins));
Team6win.setText(String.valueOf(Conference[5].wins));
Team7win.setText(String.valueOf(Conference[6].wins));
Team8win.setText(String.valueOf(Conference[7].wins));
Team9win.setText(String.valueOf(Conference[8].wins));
Team10win.setText(String.valueOf(Conference[9].wins));


text:
Q: binding source declaration in xaml: object name of class name? Here is my code:
<ListView x:Name="monitorEventList" ItemsSource="{Binding Source=MonitorEventCollection}">

Actually MonitorEventCollection is a class name defined by me, I guess the Binding Source should be an object? am I right? So I guess a default constructor is called during the code initialization to create an object from a class. I set a breakpoint in the constructor, but it's not called.
So I'm confused. How does xaml run when it sees a class name in binding source?

A: Your object needs to have a property of that class. The object is created in code, in the XAML, you bind to the property name. So:
public MonitorEventCollection Foo { ... }

is bound to with
<ListView x:Name="monitorEventList" ItemsSource="{Binding Path=Foo}">

A: Sorry, but you are mistaken about how this works. You can use a class like this, but not in this way. To find out about how to use a class in this way, please take a look at the ObjectDataProvider Class page on MSDN.
To use your XAML example, you would need to change it slightly:
<ListView x:Name="monitorEventList" ItemsSource="{Binding Path=PropertyName}">

...where PropertyName is a public property from an instance of a class that is data bound as the DataContext of this (or a parent) control.


text:
Q: How to extend data in one column using xlsxwritter python How to extend data in one column seperated by commas in xlsxwriter.
for x in y:
   worksheet.merge_range("G"+str(row)+":"+"L"+str(row),x.multiple_values, centercell)
   row+=1

my data is dynamic for every loop i want to write values seperated by commas in particular column. for example
column A | column B

data     | 654654,649824,63928,624684

A: i solved by using an empty string something like this and it worked for me
array =''
for x in y:
   array = str(x)+','+str(array)
   worksheet.merge_range("G"+str(row)+":"+"L"+str(row), array , centercell)

row+=1


text:
Q: Loading new page after button is clicked (not duplicate) I am developing a web application (for learning purposes) and I am stuck at how to load another page after a particular button is clicked
I am using django 1.4.5 web framework along with python 2.7.4
I have already designed all the html pages and javascript and css files.
I have no idea about HttpRequests. And studying various tutorials i came across these three methods.
1)
xhr = new XMLHttpRequest();
xhr.open("GET","screen2/",false);
xhr.send(null);

2)
location.href="/screen2/"

3)
window.open("/screen2/","_parent");

all of 'em are kept inside the function setup(),the button's onclick is set to onclick="setup()"
Yes, I comment them out to keep only one of them "alive" at a time.
django urls.py file:
urlpatterns = patterns('',
    url(r'^screen1/$',screen1),
    url(r'^screen2/$',screen2),
)

django views.py file
def screen1(request):
    f = open(r"mysite/frontend/1st screen.html",'r')
    html = f.read()
    return HttpResponse(html)

def screen2(request):
    f = open(r'mysite/frontend/2nd Screen.html','r')
    html = f.read()
    return HttpResponse(html)

Second and third methods work the first doesn't. I don't understand why.
Also, How to send the corresponding scripts and css files with the request ?

A: The first is making an ajax request, using javacript.  The response is contained in javascript.  The other 2 are changing the location (url) of the webpage.
Additionally: Django provides a fully contained templating engine, and template loader that wraps all the loading of templates for you.  You should not have to manually open the file and read its contents and return it as a string like you are doing below:
def screen2(request):
    f = open(r'mysite/frontend/2nd Screen.html','r')
    html = f.read()
    return HttpResponse(html)

The django tutorial provides an exapmle of how to render templates using djangos built in functions
I am Assuming that you have not done any configuration to serve static files (How to send the corresponding scripts and css files with the request ?). Django provides examples of how to do this here


text:
Q: Why doesn't the keypress listener work correctly on react? In the app are letter elements, on which the user can click, then the addHandler function triggers. Also I added keydown listener to the window object, but it doesn't work as I expected. If I start with typing, the first letter will be added to the typedLetters array, but when I type another, then it will add 4 letters, for third time it adds 12, like
['e','r','r','r','r','w','w','w','w','w','w','w',w','w',w','w']

or something similar. The click events on the elements work just fine.
window.addEventListener('keydown', (e) => {
    addHandler(e, e.key);
  });

  const addHandler = (e, letter) => {
    if (e.target.tagName) {
      if (!e.target.tagName === 'SPAN') return;
    }
    if (!firstType) setFirstType(true);
    setTypedLetters((prev) => {
      return [...prev, letter];
    });
  };


text:
Q: Excel-VBA: What's the meaning of "&" in Range function What's the meaning and usage of "&" in the following piece of code?
Set Rng = Range("a1", Range("h" & Rows.Count).End(xlUp))

A: & is the string concatenation operator in VBA. So if Rows.Count = 10 then "h" & Rows.Count would produce a string that contains "h10".


text:
Q: How to count different values in a same column in mysql? i have a table like this
id(pk)|product_id(fk)|serial(varchar)|status(varchar)
  1   |    2         |      e098     | sold
  2   |    2         |      e008     | faulty

what i need to extract is:
array(faulty=>1,sold=>1)

i i can do it with a complex query, is there any SIMPLE query which can help?
i tried this:
SELECT COUNT(id) as product_details.status FROM product_details WHERE product_id=2 GROUP BY status which didn't work.

A: (ab)Use mysql's auto-typecasting:
SELECT SUM(status='sold') AS sold, SUM(status='faulty') AS faulty
FROM ...

the boolean result of status='sold' will be typecast to integer 0/1 and then summed up.
The other option is just to do a regular query and then do the pivoting in client-side code:
SELECT id, status, COUNT(status) AS count
FROM ...
GROUP BY id, status

and then
while(... fetch ...) {
   $results[$row['id']][$row['status']] = $row['count'];
}

A: You want to query status as well like this.
SELECT status, COUNT(id) as count FROM product_details WHERE product_id=2 GROUP BY status


text:
Q: Flexbox, занимающий 50% оставшегося места вне зависимости от содержимого Этот вопрос является продолжением темы Table-элементы: занять оставшееся место по высоте. Было предложено решение на основе flex-box для макета с одной колонкой фиксированной длины и ещё двумя, занимающими по 50% оставшегося места каждая:

Проблема, с которой я столкнулся: если внутри средней колонки поместить таблицу, то при больших размерах экрана она будет больше, чем незаполненная правая (пример кода). Это несмотря на то, что мы установили колонкам одинаковый flex-grow.

1

              Lamborgini Egoista

Concept year: 2013

Comment:

3

* {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color:#778899;
}

.container_columns {
  flex-grow: 1;
  display: flex;
  background: #FFB6C1;
}

.constant-width-column{
  width: 50px;
  padding: 5px;
}

.var-width-column {
  flex-grow: 1;
  padding: 5px;
  min-width: 450px;
}

.var-width-column:first-child{
    background: #87CEFA;
  }

.var-width-column:nth-child(2){
    background: #90EE90;
  }

.var-width-column >div{
    display: flex;
    flex-direction: column;
    height: 100%;
  }

.flex-container{
  table{
    background-color: #800080;
      tr{
        &:first-child{
          td{
            text-align: center;
            vertical-align: middle;
            width: 15%;
            padding: 3px 0;
            color: white;
            img{
              width: 80%;
            }
          }
        }
      }
    }
}

.flex-container table{
  background-color: #800080;
  color:white;
}

.flex-container table tr:first-child td{
  text-align: center;
  vertical-align: middle;
  width: 15%;
  padding: 3px 0;
  color: white;
}

.flex-container table tr:first-child td img{
  width: 80%;
}

Каким образом обеспечить одинаковый размер средней и правой колонки при любых ширинах экрана вне зависимости от содержимого? Напомню, что средняя и правая колонки должны занимать по половине оставленного левой колонкой пространства, но быть не меньше установленной минимальной ширины.
Заранее спасибо за ответы.

A:

.container {
  display: flex;
  flex-direction: row;
  align-content: flex-start;
}

.constant-width-column {
  flex-grow: 0;
  flex-shrink: 0;
}

.var-width-column {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: 0;
  min-width: 1px;
  overflow: auto;
}

.container > *:nth-child(1) {
  background-color: red;
}

.container > *:nth-child(3) {
  background-color: lightblue;
}

1

          Lamborgini Egoista

Concept year: 2013

Comment:

3

flex-basis: 0 и например min-width: 1px заставит делиться свободным пространством поровну. Главное придать колонкам одинаковую ширину, иначе ничего не получится.
overflow надо задать такой, чтобы большой контент на вылазил и не накрывал соседнюю колонку. auto, hidden - какой больше нравится.


text:
Q: WPF cascading comboboxes with LINQ I do have a number of combo boxes on a custom control as below
<Label Grid.Row="12" Grid.Column="0" Name="lblCombobox1">
    Select value from Combobox1
</Label>
<ComboBox Grid.Row="12" Grid.Column="1" Name="cbxCombobox1"
        SelectionChanged="cbxCostCentre_SelectionChanged" />
<Label Grid.Row="13" Grid.Column="0" Name="lblCombobox2">
    Select value from Combobox2</Label>
<ComboBox Grid.Row="13" Grid.Column="1" Name="cbxCombobox2"/>

This custom control I'm using on a main window as below
<StackPanel Background="LightCyan">
<views:NewAccount HorizontalAlignment="Center"
    Margin="30" FontSize="14"/>

I'd need to do populate combo boxes cascading to have a previous combo box selected value as a filter parameter for the next one.
It seems as the following code could do it. It's doing the filtering providing the Combobox2 with a list of values. However, I'm probably missing something as the LINQ query with "where" clause provides a result that is different if I ran it with T-SQL. It's very similar but a few more or less values in the Combobox2 that is different from T-SQL list.
using System.Linq;
namespace AccountsSetup.UserControls
{
    public partial class NewAccount : UserControl
    {
        public NewAccount()
        {
            InitializeComponent();

            using (SQL.DBDataContext db = new SQL.DBDataContext())
            {
                var allCombobox1s = from t in db.Table1
                                     select t.Name;
                cbxCombobox1.ItemsSource = allCombobox1s;
            }
        }

        private void cbxCombobox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            using (SQL.DBDataContext dbs = new SQL.DBDataContext())
            {
                string value = "";
                if (cbxCombobox1.SelectedIndex >= 0)
                    value = cbxCombobox1.SelectionBoxItem.ToString();
                var allCombobox2s = (from t in dbs.View1
                                       where t.Combobox1.Contains(value)
                                       select t.Name).Distinct();
                cbxCombobox2.ItemsSource = allCombobox2s;

            }

I did try to change the Combobox2 into the following code. But, it's the same result.
<ComboBox Grid.Row="13" Grid.Column="1" x:Name="cbxCombobox2"
    ItemsSource="{Binding}" SelectedValue="{Binding ElementName=cbxCombobox1,
    Path=SelectedItem.Name, Mode=OneWay}" />

Please, advise what corrections could be done in the code.
Thanks

A: You should compare the value of the SelectedItem property of the first ComboBox with the value of the Name column in the view.
Try this:
private void cbxCombobox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    using (SQL.DBDataContext dbs = new SQL.DBDataContext())
    {
        string value = cbxCombobox1.SelectedItem as string;
        if (!string.IsNullOrEmpty(value))
        {
            var allCombobox2s = (from t in dbs.View1
                                 where t.Name != null && t.Name.Contains(value)
                                 select t.Name).Distinct().ToList();
            cbxCombobox2.ItemsSource = allCombobox2s;
        }
    }
}


text:
Q: Java XML vs SQL vs custom data storage I am writing a piece of software for my girlfriend and I'm struggling to choose between ways of permanent storage.  Since the application revolves heavily around storing data, it's a fairly important issue.
My specific needs are:

*

*Small footprint for a constantly expanding dataset that could easily exceed 10,000 entries

*Easy to access from code, easy to port to other languages (in case I write a front-end in another language in the future)

*(Optional) Easy to access directly, so that manual editing can be performed

*File-based storage preferred, since it greatly increases the portability of the data.

I've considered XML, which fails mostly on the second and third points, but also a little on the first point (I'm not sure how scalable XML really is, I've not done any tests).
I've also considered SQLite, but it requires a third-party library to work properly with Java (as far as I'm aware) and also fails on the third point, since direct-access is impossible.
As far as bespoke is concerned, I'd really rather avoid it since re-inventing the wheel is generally considered a Bad Thing®, but if it really is the best option then I will consider it.
Note: I know this is a possible duplicate of Best data storage method for small personal application(SQL Database, XML, or other file type) but that one's favoured answer is SQLite, and there is a difference between C++ and Java where SQLite is concerned, so I figure this question is sufficiently different.  Correct me if I'm wrong.

A: For something like relational data I'd prefer H2 database engine. HSQLDB could also make it. It will be able to query the data more easily than XML or JSON. Think of it as an advanced SQLite that can run in a server mode and be accessed by external tools easily (actualy delivered with H2).
Look at neo4j if your data is graph-strucutred.

A: Accessing a db through ODBC makes the code less db-technology dependent, as most databases have ODBC drivers.

A: In the end, I opted for a bespoke JSON-like solution since it wasn't important to the project that the file use a standardised format.
I think any SQL-based solution would have been too heavyweight for this project, however the data is tabular in nature so I might consider switching storage modes in the future (the code is written such that the permanent storage method can easily be modified, which I would recommend as a modus operandi for other people who have a problem choosing between storage methods).


text:
Q: Xcode 11, Swift : Warning Can't end BackgroundTask on open URL I have just an application with 1 button and this the ViewController attached :

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func test(_ sender: Any) {
        UIApplication.shared.open(URL(string: "https://www.google.fr")!, options: [:], completionHandler: nil)
    }

}

When i click on the button, Safari open Google, i can come back to my app, but i have a warning message in the Xcode console :
2020-02-06 11:07:24.851814+0100 TabApp[6275:418659] Can't end BackgroundTask: no background task exists with identifier 1 (0x1), or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug.

Anyone know how to avoid this warning ?
Best regards

A: This should do the trick - this are typically logs from the OS.
Select your Scheme -> Edit Scheme -> Run -> set OS_ACTIVITY_MODE to disable


text:
Q: Python - Beautifulsoup | ValueError: Unsupported or invalid CSS selector: "I an trying to scrape an application off of the fareham.gov.uk web page and every time I try it returns an error instead of the reference number. Can somebody help me to fix this problem? I am new to web scraping and whenever I try to google a fix nothing worked.

Error:
Traceback (most recent call last):
  File "C:\Users\DBaldwin\Desktop\sel.py", line 39, in <module>
    div = soup.select('

Reference

')
  File "C:\Users\DBaldwin\Anaconda3\lib\site-packages\bs4\element.py", line 1477, in select
    'Unsupported or invalid CSS selector: "%s"' % token)
ValueError: Unsupported or invalid CSS selector: "<div"

Code:
import time
import urllib.request
from bs4 import BeautifulSoup
from selenium import webdriver

url = "http://www.fareham.gov.uk/casetrackerplanning/applicationsearch.aspx"

driver = webdriver.Chrome(executable_path=r"C:\Users\DBaldwin\Desktop\chromedriver.exe")
driver.get(url)

driver.find_element_by_id("lnkAllowCookies").click()

def rerun():
    driver.find_element_by_id("BodyPlaceHolder_uxLinkButtonShowAdvancedSearch").click()

    time.sleep(3)

    driver.find_element_by_id("uxStartDateDecisionTextBox").click()
    driver.find_element_by_id("uxStartDateDecisionTextBox").clear()
    driver.find_element_by_id("uxStartDateDecisionTextBox").send_keys("1/8/2018")

    driver.find_element_by_id("uxStopDateDecisionTextBox").click()
    driver.find_element_by_id("uxStopDateDecisionTextBox").clear()
    driver.find_element_by_id("uxStopDateDecisionTextBox").send_keys("308/2018")

    driver.find_element_by_id("BodyPlaceHolder_uxButtonSearch").click()

    time.sleep(3)

rerun()

elements = driver.find_elements_by_class_name("searchResultsCell")

for e in elements:
    e.click()
    newUrl = driver.current_url
    go = urllib.request.urlopen(newUrl)
    soup = BeautifulSoup(go.read(), "html.parser")
    div = soup.select('

Reference

')
    test = div[0].get_text()
    print(test)
    driver.back()
    rerun()
    print("Worked???")

A: Try to use below code to get required values
elements = driver.find_elements_by_css_selector(".searchResultsCell a")
links = [link.get_attribute('href') for link in elements]

for link in links:
    driver.get(link)
    print(driver.find_element_by_css_selector('div.docGridRow').text)


text:
Q: Scale down all children in widget by a factor based on the parent size In Flutter I am implementing "what's new" screens which will show a preview of the real screens in the app.
For that I reuse the screen Widgets in the "what's new" flow.
The preview will be shown in a smaller Container and not cover the whole screen.
I want to scale down the text sizes, line heights, etc. for all widgets within this Container to match the smaller bounds.
Is there a way to do this without individually adding a smaller style for every Widget separately?
e.g. scale down all fontSizes by 20% for a Widget child regardless of the size set in the theme

A: I found the solution. Wrapping the child widget tree with Transform.scale(...) will scale all the Widgets down the tree according to the supplied scale factor.
Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    Transform.scale(
      scale: 0.9,
      child: MyScaledWidgetTree(),
     ),
     Container(
      child: ...,
     ),
   ],
)


text:
Q: Google script: workaround for constantly asking permission Consider a template GoogleDocs named TGD with this content: <PATIENT_NAME>.
TGD contains a script TO_PDF accessible through the GoogleDocs menu which converts TGD into PDF.
There is another script called FILL (inside a GoogleSheet) which
a) creates a copy of TGD,
b) replaces <PATIENT_NAME> with a real name, let's say John Doe in this copy, and
c) saves the resulting GoogleDocs under a John_Doe_GD name.
When a user tries to access the TO_PDF functionality in John_Doe_GD it is presented with a "A script attached to this document needs your permission to run." although TO_PDF has already been granted access while part of TGD.
The question: is it there a Google configuration which automatically grants this permission?
Context. This is a real-world scenario from a small medical lab. Data is not directly exported into PDF from GoogleSheet because MDs might want to edit the exported GoogleDocs. However, this pestering with permissions is really annoying and should somehow be circumvented.


text:
Q: Normalizing this database: what would be ideal in this scenario? I'm designing a game where a character has many items and those items can be of many types.  There is a character table, and twelve different tables of possible items broken down by type (such as weapons, armors, and various other item types).
I want to make a table to hold instances of these item types (basically a characters' items table) every row will have a foreign key from the characters' table to indicate which character has ownership of that item.
At first I figured I'd make foreign keys in the characters' items table -- one key for each of the twelve item tables.  But since every item can be of only one "type," that would lead to eleven null fields in every row, and that seems wrong.
What would be the better approach?  I've yet to build the database, so I can entertain other inventory ideas that don't use twelve item tables, but know this:  the admin interface will allow a user to add/remove/modify items of each type as needed.
Also, I'd like to stick to the best normalization practice, so I'll ignore the inevitable "Who cares?  Just do what works and use null-able fields."

A: I'd first check if you could unify those twelve tables into one.  Start with Single-Table Inheritance, because it's simple and I bet it would be adequate in this case.
CHARACTER --<- CHAR_ITEMS  ->-- ITEM_TYPES_STI

If not, try Class Table Inheritance.  Basically, define a supertable for "item type" and the character's items reference that.  Each sub-table for the 12 individual item types also reference the item types supertable:
CHARACTER --<- CHAR_ITEMS  ->-- ITEM_TYPES_SUPER --- ITEM_TYPE_SWORDS

Re your comment: I've clarified the line above.  The relationship between item_types_super and item_type_swords should be 1:1.  That is, for each row in swords there should be a distinct row in super.  The way to do this is to make the foreign key in swords also its primary key.
But not every row in super has a row in swords.  The row in super could be referenced by a row in shield, or axes, or whatever.  But only by one subtype.  The idea is that columns common to all item types belong in super, and the columns that are subtype-specific go in each subtype table.

A: If you used the following tables (I only included the key values for columns).  The CHARACTERS_ITEMS table contains the list of items for each character.  The combination of ItemTypeID and ItemID would be used to reference a row in one of the 12 items tables.
CHARACTERS
----------
CharacterID (PK)

ITEMS
-----
ItemID (PK)

ITEM_TYPES
----------
ItemTypeID (PK)

CHARACTERS_ITEMS
----------------
CharacterID (FK)
ItemTypeID (FK)
ItemID (FK)

Here is the beginning of a view that may be helpful as well.  It demonstrates how the ItemTypeId can be used to reference the appropriate table.
CREATE VIEW v_character_items
AS
SELECT {list of columns}
FROM character_items
JOIN character_item_1 on character_items.ItemID = character_item_1.ItemID and character_items.ItemTypeID = 1

UNION
SELECT {list of columns}
FROM character_items
JOIN character_item_2 ON character_items.ItemID = character_item_2.ItemID and character_items.ItemTypeID = 2

UNION
{other tables...}

A: In your case I would try to merge all twelve tables back into one table.
The reason for this is not really anything to do with technical table design -- but rather it will alow your characters to reuse objects in unexpected ways.
You could for instance have a set of throwable attributes such as EFFORT, ACCURACY, DAMAGE, BREAKAGE so a dagger would be almost no effort to throw, and cause a great deal of injury if it stuck its target, on the other hand a goblet would be easy to throw but cause very little damage or a gold bar would be hard to throw but would cuase a reasonable amount of injury even though it is not strictly speaking a weapon.
 It would also allow you to have weapons which were also "treasure" objects of great value or magical use (dont know what sort of game you are planning so these examples may not be appropriate

A: I don't know if you're still looking for replies, but here is how I did mine very recently:
CHARACTER -> Char/Item Link Table -> ITEM

ITEM
----
ID
NAME
TYPE
etc.

This allows you to create base items which multiple characters can possess.  If you want to do individual character modification to items (i.e. gem slotting, enchantments, etc.) that can easily be done through an EFFECT table (or something similar):
ITEM -> Item/Effect Link Table -> EFFECTS

In this manner you can have characters customize their own weapons and still keep the base around.  You can also create a set of effects without having to repeat them over and over for every item in your game.


text:
Q: Comparing pushing data (1 million numbers) with and without prior resizing in std::vector Comparing pushing data (1 million numbers) with and without prior resizing into  std::vector. To my amusement , I found the later ( without resizing) to be faster , which is contrary to expectation. What happened ? I am using MS VC++ 2017 compiler.
double times = 1000000;

vector<double> vec1;
auto tp_start = chrono::high_resolution_clock::now();
for (double i=0; i < times; i++)
{
    vec1.push_back(i);
}
auto lapse = chrono::high_resolution_clock::now() - tp_start;
cout << chrono::duration_cast<chrono::milliseconds>(lapse).count() << " ms : push without prior resize  \n"; // 501 ms

vector<double> vec2;
vec2.resize(times);  // resizing
tp_start = chrono::high_resolution_clock::now();
for (double i = 0; i < times; i++)
{
       vec2[i]  = i; //fastest
      // vec2.push_back(i); //slower
}
lapse = chrono::high_resolution_clock::now() - tp_start;
cout << chrono::duration_cast<chrono::milliseconds>(lapse).count() << " ms : push with prior resizing  \n"; // 518 ms , shouldn't this be faster theoritically

Edited:
After this change: vec2.resize(times); it works faster
After this change: vec2.reserve(times); it works even faster
After this change: vec2[i] = i; becomes super fast
Any advise what is the best practice?
Edited 2  ( compiler in optimized mode)
10 million data :
 120ms : 41ms   reserve & pushback

 121ms : 35ms   resize & vec[i]

100 million data :
 1356ms : 427ms   reserve & pushback

 1345ms : 364ms   resize & vec[i]

vec[i] still wins

A:
After this change: vec2.resize(times); it works faster

I think maybe that's because after the resize the vec2 actually holds 2*times space,so it does not need reallocating in later push_back.

After this change: vec2.reserve(times); it works even faster

this version does not need reallocating,so it's better than the first one.

After this change: vec2[i] = i; becomes super fast

this directly place the element on its position,without any redundant operations compared with push_back

origin answer
You should do like:
vector<double> vec2;
vec2.resize(sizeof(double)* times);  // this directly chage the size(),with capacity() also changed.
tp_start = chrono::high_resolution_clock::now();
for (double i = 0; i < times; i++)
{
    vec2[i]=i;//not push_back
}

If you still use push_back in this situation,it does not have any efficiency.
And in your example with resize,the size of vec2 is larger than vec1,which needs more time to reallocate its memory,and takes more time to do push_back.By the way it's better to do reserve(n) in your case.


text:
Q: Read values from DB and save in a variable I'm trying to fix this problem but I don't understand how to do.
Basically I have a DB in which there are users's informations. These information could be modify throught a form. When a user want modify the values,  it is done a search in a DB with the user's FiscalCode.
When the user is find, I want to save the old data in a variable, because if I leave a field empty (or I don't change the data) the old data has been deleted. In this way I use the old data.
So the problem is that, If the user has just registered he has no data other than the FirstName, LastName and Email, in this way all the other fields are empty.
The problem is that when I go to read these data to be saved in the variable if they are empty, I am in error and therefore the change is impossible. (the error is in readUtente function)
I have tried this method adding an "If" but it doesn't work.
    componentDidMount(){
    this.readUtente(this.props.cf)
    console.log("this.props.cf: " + this.props.cf)
  }

  //Funzione di prova aggiunta
  readUtente(cf){
    let params = {};
    params = {
    //  "Person.FiscalCode": this.props.cf
        "Person.FiscalCode": cf
    };
    console.log("1. PARAMS IN MODIFICA PROFILO: " +JSON.stringify(params))
    global.utente.db.localdb().find({
        selector: params
      })
      .then(response => {
      let utente = response.docs[0];
        console.log("2. UTENTE: " + JSON.stringify(utente))
        console.log("3. Utente.Person.FirstName: " + utente.Person.FirstName)
        console.log("4. utente.Person.City: " + utente.Person.City)
        //ho aggiunto if
       if(utente.Person.FirstName !== undefined) {this.setState({ nome: utente.Person.FirstName })}
       if(utente.Person.LastName !== undefined) {this.setState({ cognome: utente.Person.LastName })}
       if(utente.Person.City !== undefined) {this.setState({ citta: utente.Person.City })}
       if(utente.Person.Address !== undefined) {this.setState({ indirizzo: utente.Person.Address })}
       if(utente.Person.DateOfBirth !== undefined) {this.setState({ dataNascita: utente.Person.DateOfBirth })}
       if(utente.Person.Country !== undefined) {this.setState({ paese: utente.Person.Country })}
       if(utente.Contacts.Email !== undefined) {this.setState({ email: utente.Contacts.Email })}

      })
      .catch(function(err) {
        console.log(JSON.stringify(err));
      })
  }

  findUtente(cf) {
    console.log("5. Codice fiscale Passato: " + cf)
    let params = {};

    params = {
      "Person.FiscalCode": cf
    };
    console.log("6. PARAMS della findUtente" + JSON.stringify(params))
    global.utente.db
      .localdb()
      .find({
        selector: params
      })
      .then(response => {
        let utente = response.docs[0];
        console.log("7. Utente: " + JSON.stringify(utente))
        console.log("8. this.state.City: " + this.state.citta)
        utente.Person.FirstName = this.state.FirstName == null ? this.state.nome : this.state.FirstName;
        console.log("9. utente.Person.FirstName: " + utente.Person.FirstName)
        utente.Person.LastName = this.state.LastName == null ? this.state.cognome : this.state.LastName;
        console.log("10. utente.Person.LastName: " + utente.Person.LastName)
        utente.Person.City = this.state.City == null ? this.state.citta : this.state.City;
        console.log("11. utente.Person.City: " + utente.Person.City)
        utente.Person.Address = this.state.Address == null ? this.state.indirizzo : this.state.Address;
        utente.Person.DateOfBirth = this.state.DateOfBirth == null ? this.state.dataNascita : this.state.DateOfBirth;
        utente.Person.Country = this.state.Country == null ? this.state.paese : this.state.Country;
        utente.Contacts.Email = this.state.Email == null ? this.state.email : this.state.Email;

        return global.utente.db.localdb().put(utente);
      })
      .catch(function(err) {
        console.log(JSON.stringify(err));
      })
      .finally(function() {
        Actions.homepageutente();
      });
  }

CONSOLE:
    1. PARAMS IN MODIFICA PROFILO: {"Person.FiscalCode":"ZMBNNZ91P16F364F"}
ModificaProfilo.js:34 this.props.cf: ZMBNNZ91P16F364F
ModificaProfilo.js:51 2. UTENTE: {"DocumentType":"GeneralData","Person":{"FirstName":"Nunzio","LastName":"Zambrotti","FiscalCode":"ZMBNNZ91P16F364F"}
ModificaProfilo.js:52 3. Utente.Person.FirstName: Nunzio
ModificaProfilo.js:53 4. utente.Person.City: undefined
ModificaProfilo.js:67 {}
ModificaProfilo.js:72 5. Codice fiscale Passato: ZMBNNZ91P16F364F
ModificaProfilo.js:78 6. PARAMS della findUtente{"Person.FiscalCode":"ZMBNNZ91P16F364F"}
ModificaProfilo.js:86 7. Utente: {"DocumentType":"GeneralData","Person":{"FirstName":"Nunzio","LastName":"Zambrotti","FiscalCode":"ZMBNNZ91P16F364F"}
ModificaProfilo.js:87 8. this.state.City: undefined
ModificaProfilo.js:89 9. utente.Person.FirstName: Nunzio
ModificaProfilo.js:91 10. utente.Person.LastName: Zambrotti
                      11. utente.Person.City: Rome

A: The problem could be that the empty data isn't valorised as null but could be an empty string or undefined.
Try changing the if statements in these ways:
if(utente.Contacts.Email !== undefined )

or
if(utente.Contacts.Email !== "" )

or
if(utente.Contacts.Email)


text:
Q: Build CAML query by value from ClientPeoplePicker I use these lines of code:
<SharePoint:ClientPeoplePicker ID="clpUser" runat="server" UseLocalSuggestionCache="True"/>

JS:
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[clientId + "_TopSpan"];
var users = peoplePicker.GetAllUserInfo();

var expressions = new Array();
for (var i = 0; i < users.length; i++) {
    expressions.push("<Eq><FieldRef Name='Absentee'></FieldRef><Value Type='User'>" + users[i].DisplayText + "</Value></Eq>");
}

var query = buidQueryFromExpressions(expressions);

My problem is for several users ClientPeoplePicker returns values that represent login (domain/username), but for the CAML query I should use display name or ID, because in my list that stores the data the user display name is used. How can I correctly configure this control? May be you know other solutions?

A: Using the hidden User Information List to get the ID has been a workaround since SP 2007 so it's basically a solution for this.


text:
Q: How to determine the voltage range of a microphone output? I have an analog microphone: PMM-3738-VM1010-R. I want to know what will be the voltage range of the microphone's output at a specific threshold level, let's say 89 dB threshold (different thresholds are mentioned in the datasheet, 89 dB is one of them).
The datasheet provides sensitivity and as far as I understand, sensitivity of -38dB corresponds to 13 mV, but I don't know how to use it to define the voltage range of the microphone.
Can someone please help? Thanks.
EDIT: I have found the values using an oscilloscope, but it would be great to know the theoretical way as well.


text:
Q: How to animate tabbar items (on selection) in SwiftUI? How can I animate Tabbar Items (of a TabView) on selection in SwiftUI?
for example give the selected item a .scaleEffect() with .spring() animation
or sth like below:

This is what I've tried so far:
struct MyTabbedView: View {
    @State var enlargeIt1 = false
    @State var enlargeIt2 = true

    var body: some View {
        TabView {
            Text("Item 1")
                .onAppear {
                    self.enlargeIt1.toggle()
                    self.enlargeIt2.toggle()
                }
                .tabItem{
                    VStack{
                        Image(systemName: "music.note")
                            .font(self.enlargeIt1 ? .system(size: 30) : .system(size: 15) )
                            .animation(.interpolatingSpring(mass: 0.7, stiffness: 200, damping: 10, initialVelocity: 4))
                        Text("Music")
                    }
                }.tag(1)

            Text("Item 2")
                .onAppear {
                    self.enlargeIt1.toggle()
                    self.enlargeIt2.toggle()
                }
                .tabItem{
                    VStack{
                        Image(systemName: "music.mic")
                            .font(self.enlargeIt2 ? .system(size: 30) : .system(size: 15) )
                            .animation(.interpolatingSpring(mass: 0.7, stiffness: 200, damping: 10, initialVelocity: 4))
                        Text("Mic")
                    }
                }.tag(2)

        }
    }
}

and the result is this:

I tried approximately the same code in a separate View called TestView :
struct TestView: View {
    @State var enlargeIt1 : Bool = false

    var body: some View {
        VStack{
            Image(systemName: "music.note")
                .font(self.enlargeIt1 ? .system(size: 30) : .system(size: 15) )
                .animation(.interpolatingSpring(mass: 0.7, stiffness: 200, damping: 10, initialVelocity: 4))
            Text("Music")
        }
        .onTapGesture {
            self.enlargeIt1.toggle()
        }

    }
}

and this is the result:

What's wrong with the TabView I've created that it's not giving the same result?

A: Here is possible approach for standard TabView (for provided code snapshot).
The idea is to use animatable modifier for font size over used SF images.
Tested with Xcode 11.4 / iOS 13.4

// Animating font size
struct AnimatableSFImage: AnimatableModifier {
    var size: CGFloat

    var animatableData: CGFloat {
        get { size }
        set { size = newValue }
    }

    func body(content: Self.Content) -> some View {
        content
            .font(.system(size: size))
    }
}

// helper extension
extension Image {
    func animatingSF(size: CGFloat) -> some View {
        self.modifier(AnimatableSFImage(size: size))
    }
}

// Modified test code snapshot
struct TestAnimatedTabBar: View {
    @State var enlargeIt1 = false
    @State var enlargeIt2 = true

    var body: some View {
        TabView {
            Text("Item 1")
                .onAppear {
                    self.enlargeIt1.toggle()
                    self.enlargeIt2.toggle()
                }
                .tabItem{
                    VStack{
                        Image(systemName: "music.note")
                            .animatingSF(size: self.enlargeIt1 ? 30 : 15 )
                        Text("Music")
                    }.animation(.interpolatingSpring(mass: 0.7,
             stiffness: 200, damping: 10, initialVelocity: 4))
                }.tag(1)

            Text("Item 2")
                .onAppear {
                    self.enlargeIt1.toggle()
                    self.enlargeIt2.toggle()
                }
                .tabItem{
                    VStack{
                        Image(systemName: "music.mic")
                            .animatingSF(size: self.enlargeIt2 ? 30 : 15 )
                        Text("Mic")
                    }.animation(.interpolatingSpring(mass: 0.7,
             stiffness: 200, damping: 10, initialVelocity: 4))
                }.tag(2)

        }
    }
}

A: Someone created a custom TabView that might be of help to you. I'm sure you could modify it to suit your needs.

BottomBar component for SwiftUI inspired by this concept

https://github.com/smartvipere75/bottombar-swiftui
import SwiftUI
import BottomBar_SwiftUI

let items: [BottomBarItem] = [
    BottomBarItem(icon: "house.fill", title: "Home", color: .purple),
    BottomBarItem(icon: "heart", title: "Likes", color: .pink),
    BottomBarItem(icon: "magnifyingglass", title: "Search", color: .orange),
    BottomBarItem(icon: "person.fill", title: "Profile", color: .blue)
]

struct BasicView: View {
    let item: BottomBarItem

    var detailText: String {
    "\(item.title) Detail"
}

var followButton: some View {
    Button(action: openTwitter) {
        VStack {
            Text("Developed by Bezhan Odinaev")
                .font(.headline)
                .color(item.color)

            Text("@smartvipere75")
                .font(.subheadline)
                .foregroundColor(.gray)
        }
    }
}

var destination: some View {
    Text(detailText)
        .navigationBarTitle(Text(detailText))
}

var navigateButton: some View {
    NavigationLink(destination: destination) {
        ZStack {
            Rectangle()
                .fill(item.color)
                .cornerRadius(8)
                .frame(height: 52)
                .padding(.horizontal)

            Text("Navigate")
                .font(.headline)
                .foregroundColor(.white)
        }
    }
}

func openTwitter() {
    guard let url = URL(string: "https://twitter.com/smartvipere75") else {
        return
    }
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

var body: some View {
    VStack {
        Spacer()

        followButton

        Spacer()

        navigateButton
        }
    }
}

struct ContentView : View {
    @State private var selectedIndex: Int = 0

    var selectedItem: BottomBarItem {
        items[selectedIndex]
    }

    var body: some View {
        NavigationView {
            VStack {
                BasicView(item: selectedItem)
                    .navigationBarTitle(Text(selectedItem.title))
                BottomBar(selectedIndex: $selectedIndex, items: items)
            }
        }
    }
}


text:
Q: JRE Bit version in javascript I need to check the JRE version installed in the client system using javascript. I tried the following code:
<script src="http://www.java.com/js/deployJava.js"></script>
<script>
     var versions = deployJava.getJREs();
     alert(versions);
</script>

But it was not working for me. It resulted in empty array [].
Is there any other possible solutions for this. Solutions in Angular 6 or Nodejs is also appreciated.
Thanks in advance.


text:
Q: Commands after the snap enable docker command is erroring out in script file I have a script file as follows.
#!/bin/sh

sudo snap enable docker

sudo docker image ls

sudo docker ps -a

sudo docker start postgresql-dev

sudo docker start dev-pgadmin

psql -h 172.17.0.2 -U postgres tutorialdb

When I execute the file using bash bash django-local-env-init.sh, I am getting the below output
docker enabled
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
CONTAINER ID   IMAGE            COMMAND                  CREATED          STATUS                        PORTS     NAMES
c6e99fe8c8b1   dpage/pgadmin4   "/entrypoint.sh"         21 minutes ago   Exited (137) 30 seconds ago             dev-pgadmin
650bc6538472   postgres         "docker-entrypoint.s…"   29 hours ago     Exited (137) 28 seconds ago             postgresql-dev
postgresql-dev
dev-pgadmin
psql: error: connection to server at "172.17.0.2", port 5432 failed: FATAL:  the database system is starting up

Second time when I run it, its showing the below output.
error: cannot enable "docker": snap "docker" already enabled
REPOSITORY       TAG       IMAGE ID       CREATED       SIZE
postgres         latest    74b0c105737a   7 days ago    376MB
dpage/pgadmin4   latest    40a516ee7dea   3 weeks ago   341MB
CONTAINER ID   IMAGE            COMMAND                  CREATED          STATUS         PORTS                                        NAMES
c6e99fe8c8b1   dpage/pgadmin4   "/entrypoint.sh"         21 minutes ago   Up 8 seconds   0.0.0.0:80->80/tcp, :::80->80/tcp, 443/tcp   dev-pgadmin
650bc6538472   postgres         "docker-entrypoint.s…"   29 hours ago     Up 9 seconds   0.0.0.0:5432->5432/tcp, :::5432->5432/tcp    postgresql-dev
postgresql-dev
dev-pgadmin
Password for user postgres:
psql (14.2 (Ubuntu 14.2-1ubuntu1))
Type "help" for help.

I think some delay needs to be introduced between commands.
How this can be done. I saw few posts regarding writing sleep commands.
Is that the correct method? Could you please help me with the correct method for doing this?


text:
Q: Rendering  tag in table I am attempting to render noImageURL when icon.image is null. For some reason, noImageURL is always rendered. It's not respecting the  javascript if statement

       <apex:image value="{!icon.image}" styleClass="img-responsive" alt="{!icon.image}" height="150" width="150" rendered="{!IF(icon.image != null && icon.image != '' && icon.image != 'null', true, false)}" />

A: Yeah don't try to use rendered into a img tag, it's only for apex.
Updated :

    <apex:image value="{!icon.image}" styleClass="img-responsive" alt="{!icon.image}" height="150" width="150" rendered="{!IF(icon.image != null && icon.image != '' && icon.image != 'null', true, false)}" />
    <apex:image value="{!noImageURL}" styleClass="img-responsive" alt ="noImage" height="150" width="150" rendered="{!IF(icon.image == null, true, false)}"/>


text:
Q: Can I perform cluster analysis before PCA? I would like to know what are pros and cons of performing cluster analysis before/after PCA?
My data are not very well explained by the first and the second PC (49%), so I am thinking it would be more beneficial to apply PCA after clustering just for visualization than to use PCA for feature extraction and perform cluster analysis afterward.
Please let me know if my thought process makes sense. I am relatively new to this field.
P.S. I have to only use these 2 tools for my analysis as part of a requirement.
Thank you in advance!


text:
Q: JavaScript: Highlight/select word under mouse pointer How do I highlight (css: background-color) a word with JavaScript when the mouse pointer is hovering over it? It should be possible to select it by clicking on it then and saving it in a variable.

A: var words=$("#yourTextContainer").text().split(' ');
$("#yourTextContainer").html("");
$.each(words, function(i,val){
//wrap each word in a span tag
$('<span/>').text(val+" ").appendTo("#yourTextContainer");

});
$("#yourTextContainer span").live("mouseover",function(){
//highlight a word when hovered
$(this).css("background-color","yellow");
});
$("#yourTextContainer span").live("mouseout",function(){
//change bg to white if not selected
if($(this).css("background-color") !="rgb(0, 0, 255)")
{
 $(this).css("background-color","white");
}
});
$("#yourTextContainer span").live("click",function(){
$("#yourTextContainer span").css("background-color","white");
$(this).css("background-color","blue");
//gets the text of clicked span tag
var text = $(this).text();
});

EDIT:See the example http://jsfiddle.net/aD5Mu/


text:
Q: Stored Procedure Create Table from Variable with Variable Constraint I have managed use a stored procedure to create a copy of a table with a variable name. But I am struggling to understand how to incorporate a constraint into the stored procedure.
The problem: the constraint must be a variable as when it makes a copy of a table it cannot name the PK that I have with the same as one used before. I am getting syntax errors in these areas.
I am very new to SQL Server... literally just started learning today!! So please explain in dummy terms.
Code so far below:
    CREATE PROCEDURE procFinancialPeriodTable
        (@TABLENAME as varchar (50))
    AS
        DECLARE @SQL varchar(2000)
        --SET @SQL = "if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[@TABLENAME]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
        --drop table [dbo].[@TABLENAME]
    BEGIN
        SELECT @SQL = 'CREATE TABLE ' + @TABLENAME + '('

        SELECT @SQL = @SQL + '[ID] [int] IDENTITY(1,1) NOT NULL,[FinPeriodNr] [int] NOT NULL,[FinCurrentPeriod] [bit] NULL,[FinStart] [date] NULL,[FinEnd] [date] NULL,[FinStatusOpen] [bit] NOT NULL,[PeriodClosedTS] [smalldatetime] NULL,[PeriodClosedUID] [varchar](3) NULL,)'
    CONSTRAINT [PK_FinancialPeriod' + @TABLENAME + '_1] PRIMARY KEY CLUSTERED(
    [FinPeriodNr] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,                 ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    EXEC(@SQL)

    SET NOCOUNT ON;
END

A: Your logic seems fine, you are getting a syntax error because you aren't delimiting your strings correctly.
[PeriodClosedUID] [varchar](3) NULL,)' <-- problem

Also it's very helpful to be liberal with carriage returns and indenting, so problems like this aren't hidden 4 screens over and only accessible via horizontal scrollbar.
CREATE PROCEDURE dbo.procFinancialPeriodTable -- always use schema prefix
    @TABLENAME SYSNAME
AS
BEGIN -- use body wrappers around whole body
  SET NOCOUNT ON; -- put this at the beginning - no point in setting it at the end

  DECLARE @SQL NVARCHAR(MAX); -- dynamic SQL should always be Unicode

  SELECT @SQL = 'CREATE TABLE dbo.' + QUOTENAME(@TABLENAME) + '('
    + '[ID] [int] IDENTITY(1,1) NOT NULL,[FinPeriodNr] [int] NOT NULL,
       [FinCurrentPeriod] [bit] NULL,[FinStart] [date] NULL,
       [FinEnd] [date] NULL,[FinStatusOpen] [bit] NOT NULL,
       [PeriodClosedTS] [smalldatetime] NULL,[PeriodClosedUID] [varchar](3) NULL,
       CONSTRAINT [PK_FinancialPeriod_' + @TABLENAME + '_1] PRIMARY KEY CLUSTERED(
         [FinPeriodNr]));'; -- all those options you specified were verbose defaults

  EXEC sp_executesql @sql; -- instead of EXEC(@sql)
END
GO

Some links:

*

*My Stored Procedure "Best Practices" checklist

*Bad habits to kick : Avoiding the schema prefix

*Bad habits to kick : Using EXEC() instead of sp_executesql


text:
Q: Moving a Node within its parent pane, and dropping it to another
Moving a node (Label in this case) within its parent Pane (lets call it moving), works as expected by adding appropriate handlers for MouseEvent:
node.setOnMousePressed(new EventHandler<MouseEvent>() {
    @Override public void handle(MouseEvent mouseEvent) {
        x = node.getLayoutX() - mouseEvent.getSceneX();
        y = node.getLayoutY() - mouseEvent.getSceneY();
    }
});

node.setOnMouseDragged(new EventHandler<MouseEvent>() {
    @Override public void handle(MouseEvent mouseEvent) {
        node.setLayoutX(mouseEvent.getSceneX() + x);
        node.setLayoutY(mouseEvent.getSceneY() + y);
    }
});

Dragging the Label and dropping it at another Pane (lets call it dragging) also works as expected by adding appropriate handlers to source :
    node.setOnDragDetected(new EventHandler <MouseEvent>()  {
        @Override public void handle(MouseEvent event) {

            Dragboard dragboard = node.startDragAndDrop(TransferMode.COPY_OR_MOVE);
            ClipboardContent content = new ClipboardContent();
            content.putString(node.getId());
            dragboard.setContent(content);
            event.consume();
        }
    });

and target:
    target.setOnDragOver(new EventHandler <DragEvent>() {
        @Override public void handle(DragEvent event) {
            event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
            event.consume();
        }
    });

    target.setOnDragDropped(new EventHandler <DragEvent>(){
        @Override public void handle(DragEvent event) {
            Dragboard dragboard = event.getDragboard();
            if (dragboard.hasString())  {
                Node dragged = scene.lookup("#"+dragboard.getString());
                ((Pane) dragged.getParent()).getChildren().remove(dragged);
                target.getChildren().add(dragged);
                event.setDropCompleted(true);
            }
            else{
                event.setDropCompleted(false);
            }
            event.consume();
        }
    });

The problem is getting both work together. After adding drag-drop support it seems that MouseEvents are disabled so "moving" does not work.
Sure, I can work-around it and enable drag-drop only when Label is outside its parent Pane, but I wonder is this the appropriate way to get both functionalities ?
Here is a mcve. Setting isEnableDargAndDrop to false will disable node.setOnDragDetected thus enable moving  it:
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class DragTest extends Application {

    private double x, y;
    private boolean isEnableDargAndDrop;
    private Scene scene;

    @Override public void start(Stage primaryStage) throws Exception {

        isEnableDargAndDrop = true;
        GridPane root = new GridPane();
        Label label = getLabel();
        Pane leftPane = getPane(label, "cyan");
        root.add(leftPane,0,0);
        Pane rightPane = getPane(null, "yellow");
        root.add(rightPane,1,0);
        scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
        addDragSupport(label);
        addDropSupport(rightPane);
        addDropSupport(leftPane);
    }

    private Label getLabel() {

        Label label = new Label(" Move me ");
        label.setId("label");
        label.setStyle("-fx-background-color:white;-fx-border-width: 1;-fx-border-color: red;" );
        return label;
    }

    private Pane getPane(Node label, String color) {

        Pane pane = (label == null)? new Pane() : new Pane(label);
        pane.setStyle("-fx-background-color:"+color+";");
        pane.setPrefSize(150,100);
        return pane;
    }

    private void addDragSupport(Node node) {

        node.setOnMousePressed(new EventHandler<MouseEvent>() {
            @Override public void handle(MouseEvent mouseEvent) {
                x = node.getLayoutX() - mouseEvent.getSceneX();
                y = node.getLayoutY() - mouseEvent.getSceneY();
                node.setCursor(Cursor.MOVE);
            }
        });
        node.setOnMouseReleased(new EventHandler<MouseEvent>() {
            @Override public void handle(MouseEvent mouseEvent) {
                node.setCursor(Cursor.HAND);
            }
        });
        node.setOnMouseDragged(new EventHandler<MouseEvent>() {
            @Override public void handle(MouseEvent mouseEvent) {
                node.setLayoutX(mouseEvent.getSceneX() + x);
                node.setLayoutY(mouseEvent.getSceneY() + y);
            }
        });
        node.setOnMouseEntered(new EventHandler<MouseEvent>() {
            @Override public void handle(MouseEvent mouseEvent) {
                node.setCursor(Cursor.HAND);
            }
        });

        node.setOnDragDetected(new EventHandler <MouseEvent>()  {
            @Override public void handle(MouseEvent event) {
                if(! isEnableDargAndDrop ) { return;}
                Dragboard dragboard = node.startDragAndDrop(TransferMode.COPY_OR_MOVE);
                ClipboardContent content = new ClipboardContent();
                content.putString(node.getId());
                dragboard.setContent(content);
                event.consume();
            }
        });
    }

    private void addDropSupport(Pane target) {

        target.setOnDragOver(new EventHandler <DragEvent>() {
            @Override public void handle(DragEvent event) {
                event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
                event.consume();
            }
        });

        target.setOnDragDropped(new EventHandler <DragEvent>(){
            @Override public void handle(DragEvent event) {

                Dragboard dragboard = event.getDragboard();

                if (dragboard.hasString())  {

                    Node dragged = scene.lookup("#"+dragboard.getString());
                    if((dragged == null) || (dragged.getParent() == target)) {return;}

                    ((Pane) dragged.getParent()).getChildren().remove(dragged);
                    target.getChildren().add(dragged);
                    event.setDropCompleted(true);
                }
                else{
                    event.setDropCompleted(false);
                }
                event.consume();
            }
        });
    }

    public static void main (String[] args) {launch(null);  }
}


text:
Q: Read data from excel file to postgres database (Active Record) I am building a web application that shows stock data trends and stock quotes. The data has been sent to me in an excel file and I now need to load it into the database. The excel file has daily stock data for each stock, with columns in this format:
date | bid | offer | price | volume
And each stock is in a separate work sheet in the file, as below, each block is a worksheet:
Stock1 | Stock2 | Stock3 | Stock4
What is the best way for me to load this data from the excel spreadsheet to my DailyQuotes table, the migration file for my DailyQuotes table is below:
class CreateDailyQuotes < ActiveRecord::Migration
  def change
    create_table :daily_quotes do |t|
      t.date :date
      t.decimal :bid
      t.decimal :offer
      t.decimal :price
      t.integer :volume
      t.integer :stock_id

  t.timestamps
    end
  end
end

I have already created a Stocks table with the StockName and ID as columns.

A: I like roo.  It works with both xls and xlsx formats.
That said, the sample code in the official documentation is good enough for your case.  You'll need to do the following:

*

*Iterate through each sheet

*Iterate through each row

*Create a Stocks object and populate fields from each row

*Save

An alternate solution is to save your excel as csv, and use faster_csv gem which allows you to directly populate your db tables from the csv file.

A: The gem 'spreadsheet' maybe the best choice to parse old excel format 'xls'. Check this guide
And if you want to deal with xlsx, maybe rubyXL is better.


text:
Q: Column does not exists in outer join after alias I have a problem with the next SQL query (generated by sequelize ORM):
SELECT
    "Publication".*,
    "user"."id" AS "user.id"
FROM
    (SELECT "Publication"."club_id" AS "clubId", "Publication"."user_id" AS "userId" FROM "publication" AS "Publication" WHERE ("Publication"."club_id" = '1')) AS "Publication"
    LEFT OUTER JOIN "user_account" AS "user" ON "Publication"."user_id" = "user"."id";

The resulting error is:

ERROR:  column Publication.user_id does not exist
LINE 6:  LEFT OUTER JOIN "user_account" AS "user" ON "Publication"."...
                                                           ^

My intuition of what is happening is that "Publication"."user_id" is being aliased as userId. Then, the query is being aliased as "Publication"(overwriting the label which was previously refering to the table). The left outer join tries to match new the Publication user_id property with user.id, but it is unable because now it is called userId.
Am I correctly understanding the problem?

A:
ERROR:  column Publication.user_id does not exist

Answer is simple user_id <> userId:
SELECT "Publication".*,
       "user"."id" AS "user.id"
FROM
    (SELECT "Publication"."club_id"  AS "clubId"
            ,"Publication"."user_id" AS "userId"
      FROM "publication" AS "Publication"
     WHERE "Publication"."club_id" = '1') AS "Publication"
LEFT JOIN "user_account" AS "user"
  ON "Publication"."userId" = "user"."id";
                    -- here use column's alias


text:
Q: Squashed Entanglement The squashed entanglement of the system $\rho_{AB}$ is defined as:
\begin{equation}
E_{sq} (\rho_{AB}) = \inf \bigg[\dfrac{1}{2} I(A; B|E)_{\rho} : \rho_{ABE} \ \ \ \textrm{is an extension of } \ \ \rho_{AB} \bigg]
\end{equation}
Where $I(A;B|E)_{\rho}$ is the quantum conditional mutual information of $\rho_{ABE}$
\begin{equation}
I(A;B|E)_{\rho} := S(\rho_{AE}) +  S(\rho_{BE}) - S(\rho_{ABE})- S(\rho_{E})
\end{equation}
You can read more about it here on Wikipedia .
My question is: If given a quantum state, how do you compute $I(A;B|E)_{\rho}$, so that you can find the infimum, and obtain the squashed entanglement? For example:
Given the system $\rho_{AB} = \begin{bmatrix}
    1 &  0 & 0 & 1 \\
   0 &  0 & 0 & 0 \\
   0 &  0 & 0 & 0 \\
  1 &  0 & 0 & 1 \\
\end{bmatrix}  $
which is fully entangled, how can I compute it using the squashed entanglement?
 For the entanglement of formation, it's fairly easy to compute since there is an explicit formula depends on $\rho$ but for the Squashed Entanglement, I am not sure how to do it.
Thanks!

A: For pure states like the example you give, the squashed entanglement is just the normal entropy of entanglement (i.e., $S(\rho_A)$).  This follows trivially from the fact that all purifications of a pure state are of product form, $\rho_{ABE}=\rho_{AB}\otimes \rho_E$.
For mixed states, there exists no general way to compute squashed entanglement.
(By the way, I am not sure what you mean that it is "fairly easy" to compute entanglement of formation -- it is a pretty hard optimization problem. But of course, it is at least finite dimensional, which is not known to be the case for squashed entanglement.)


text:
Q: HTML5 Local Storage fallback solutions I'm looking for javascript libraries and code that can simulate localStorage on browsers that do not have native support.
Basically, I'd like to code my site using localStorage to store data and know that it will still work on browsers that don't natively support it. This would mean a library would detect if window.localStorage exists and use it if it does. If it doesn't exist, then it would create some sort of fallback method of local storage, by creating its own implementation in the window.localStorage namespace.
So far, I've found these solutions:

*

*Simple sessionStorage implementation.

*An implementation that uses cookies (not thrilled with this idea).

*Dojo's dojox.storage, but it is it's own thing, not really a fallback.

I understand that Flash and Silverlight can be used for local storage as well, but haven't found anything on using them as a fallback for standard HTML5 localStorage. Perhaps Google Gears has this capability too?
Please share any related libraries, resources, or code snippets that you've found! I'd be especially interested in pure javascript or jquery-based solutions, but am guessing that is unlikely.

A: Pure JS based simple localStorage polyfill:
Demo: http://jsfiddle.net/aamir/S4X35/
HTML:
set key: foo, with value: bar

get key: foo

delete key: foo

JS:
window.store = {
    localStoreSupport: function() {
        try {
            return 'localStorage' in window && window['localStorage'] !== null;
        } catch (e) {
            return false;
        }
    },
    set: function(name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else {
            var expires = "";
        }
        if( this.localStoreSupport() ) {
            localStorage.setItem(name, value);
        }
        else {
            document.cookie = name+"="+value+expires+"; path=/";
        }
    },
    get: function(name) {
        if( this.localStoreSupport() ) {
            var ret = localStorage.getItem(name);
            //console.log(typeof ret);
            switch (ret) {
              case 'true':
                  return true;
              case 'false':
                  return false;
              default:
                  return ret;
            }
        }
        else {
            // cookie fallback
            /*
             * after adding a cookie like
             * >> document.cookie = "bar=test; expires=Thu, 14 Jun 2018 13:05:38 GMT; path=/"
             * the value of document.cookie may look like
             * >> "foo=value; bar=test"
             */
            var nameEQ = name + "=";  // what we are looking for
            var ca = document.cookie.split(';');  // split into separate cookies
            for(var i=0;i < ca.length;i++) {
                var c = ca[i];  // the current cookie
                while (c.charAt(0)==' ') c = c.substring(1,c.length);  // remove leading spaces
                if (c.indexOf(nameEQ) == 0) {  // if it is the searched cookie
                    var ret = c.substring(nameEQ.length,c.length);
                    // making "true" and "false" a boolean again.
                    switch (ret) {
                      case 'true':
                          return true;
                      case 'false':
                          return false;
                      default:
                          return ret;
                    }
                }
            }
            return null; // no cookie found
        }
    },
    del: function(name) {
        if( this.localStoreSupport() ) {
            localStorage.removeItem(name);
        }
        else {
            this.set(name,"",-1);
        }
    }
}

A: I use PersistJS (github repository), which handles client-side storage seamlessly and transparently to your code.  You use a single API and get support for the following backends:

*

*flash: Flash 8 persistent storage.

*gears: Google Gears-based persistent storage.

*localstorage: HTML5 draft storage.

*whatwg_db: HTML5 draft database storage.

*globalstorage: HTML5 draft storage (old spec).

*ie: Internet Explorer userdata behaviors.

*cookie: Cookie-based persistent storage.

Any of those can be disabled—if, for example, you don't want to use cookies.  With this library, you'll get native client-side storage support in IE 5.5+, Firefox 2.0+, Safari 3.1+, and Chrome; and plugin-assisted support if the browser has Flash or Gears.  If you enable cookies, it will work in everything (but will be limited to 4 kB).

A: store.js uses userData and IE and localStorage on other browsers.

*

*It does not try to do anything too complex

*No cookies, no flash, no jQuery needed.

*Clean API.

*5 kb compressed
https://github.com/marcuswestin/store.js

A: have you seen the polyfill page on the Modernizr wiki?
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills
look for the webstorage section on that page and you will see 10 potential solutions (as of July 2011).
good luck!
Mark

A: Below is a tidied up version of Aamir Afridi's response that keeps all its code encapsulated within the local scope.
I've removed references that create a global ret variable and also removed the parsing of stored "true" and "false" strings into boolean values within the BrowserStorage.get() method, which could cause issues if one is trying to in fact store the strings "true" or "false".
Since the local storage API only supports string values, one could still store/retrieve JavaScript variable data along with their appropriate data types by encoding said data into a JSON string, which can then be decoded using a JSON encode/decode library such as https://github.com/douglascrockford/JSON-js
var BrowserStorage = (function() {
    /**
     * Whether the current browser supports local storage as a way of storing data
     * @var {Boolean}
     */
    var _hasLocalStorageSupport = (function() {
        try {
            return 'localStorage' in window && window['localStorage'] !== null;
        } catch (e) {
            return false;
        }
    })();

    /**
     * @param {String} name The name of the property to read from this document's cookies
     * @return {?String} The specified cookie property's value (or null if it has not been set)
     */
    var _readCookie = function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }

        return null;
    };

    /**
     * @param {String} name The name of the property to set by writing to a cookie
     * @param {String} value The value to use when setting the specified property
     * @param {int} [days] The number of days until the storage of this item expires
     */
    var _writeCookie = function(name, value, days) {
        var expiration = (function() {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days*24*60*60*1000));
                return "; expires=" + date.toGMTString();
            }
            else {
                return "";
            }
        })();

        document.cookie = name + "=" + value + expiration + "; path=/";
    };

    return {
        /**
         * @param {String} name The name of the property to set
         * @param {String} value The value to use when setting the specified property
         * @param {int} [days] The number of days until the storage of this item expires (if storage of the provided item must fallback to using cookies)
         */
        set: function(name, value, days) {
            _hasLocalStorageSupport
                ? localStorage.setItem(name, value)
                : _writeCookie(name, value, days);
        },

        /**
         * @param {String} name The name of the value to retrieve
         * @return {?String} The value of the
         */
        get: function(name) {
            return _hasLocalStorageSupport
                ? localStorage.getItem(name)
                : _readCookie(name);
        },

        /**
         * @param {String} name The name of the value to delete/remove from storage
         */
        remove: function(name) {
            _hasLocalStorageSupport
                ? localStorage.removeItem(name)
                : this.set(name, "", -1);
        }
    };
})();

A: I personally prefer amplify.js. It has worked really well for me in the past and I recommended it for all local storage needs.

supports IE 5+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ and provides a consistent API to handle storage cross-browser

A: The MDN page for DOM storage gives several workarounds that use cookies.

A: Lawnchair seems to be a good alternative too

a lawnchair is sorta like a couch except smaller and outside. perfect
  for html5 mobile apps that need a lightweight, adaptive, simple and
  elegant persistence solution.

*

*collections. a lawnchair instance is really just an array of objects.

*adaptive persistence. the underlying store is abstracted behind a consistent interface.

*pluggable collection behavior. sometimes we need collection helpers but not always.

A: There is realstorage, which uses Gears as a fallback.


text:
Q: Type Mismatch Error (Array): parsing JSON array of strings in VBA I keep receiving a "type mismatch error" (indicating that its not an array?) at:
Sub FillTaxiInfo

For i = 0 To UBound(data("prices")) - 1

The code is attempting to parse JSON from (see "prices" below):
{"id":1,"prices":[{"name":"expressTaxi","fare":{"fareType":"standard", "base":"$2.50"...}}

When I place a breakpoint and inspect "prices", it tells me that the 'Value' is Expression not defined in context and 'Type' is Empty.
Any other suggestions for improvement would be much appreciated.
My full code:
Option Explicit

Sub Run()

Dim myUrls As Variant
myUrls = Array("URL1, URL2, URL3")
FillMultipleCityInfo myUrls, ActiveWorkbook

End Sub

Function GetJson(ByVal url As String) As Dictionary
With New WinHttpRequest
    .Open "GET", url
    .Send
    Set GetJson = JsonConverter.ParseJson(.ResponseText)
End With
End Function

Sub FillTaxiInfo(data As Dictionary, sheet As Worksheet)
Dim i As Integer, taxi As Dictionary
For i = 0 To UBound(data("prices")) - 1
    Set taxi = data("prices")(i)
    If taxi.Exists("name") Then
      sheet.Cells(i, 1) = taxi("name")
      sheet.Cells(i, 2) = taxi("fare")("fareType")
    End If
Next i
End Sub

Sub FillMultipleCityInfo(urls As Variant, book As Workbook)
Dim i As Integer, data As Dictionary, sheet As Worksheet

For i = 0 To UBound(urls) - 1
    Set data = GetJson(urls(i))
    Set sheet = book.Sheets(i + 1)
    FillTaxiInfo data, sheet
Next i
End Sub

A: You are trying to receive the UBound() of an Dictionary data structure and not an Array. UBound() will only function on an Array.
Instead it appears you want to iterate over the keys of a Dictionary. Here is a small example how to do this.
Public Sub Dict_Iter()
    Dim key As Variant 'Even though the key is a string --
                       'Objects/Variant are needed in a For Each Loop
    Dim dict As New Dictionary

    'Add several items to the dictionary
    With dict
        .Add "a", "a"
        .Add "b", "b"
        .Add "c", "c"
    End With

    'Iterate over the keys
    For Each key In dict.Keys()
       Debug.Print dict(key)
    Next
End Sub


text:
Q: Access website behind IAP programatically? I want to access a websites REST APIs that is deployed on GCP and is behind Identity-Aware-Proxy (IAP). I only need to be able to access from my local computer, and I can't use Service Account key to achieve that.
I've tried to use gcloud auth login and gcloud auth application-default login to get application_default_credentials set, and then call Oauth2 endpoint to get the id_token.
No matter what I try I keep getting back an error "The audience client and the client need to be in the same project".
The client_id I have in default credentials (74XXXXXXX) and the client_id for IAP (73XXXXXXX) don't match, but they are both using the same GCP project.
Been using Python example from this (How to authenticate programmatically to a Cloud Identity-Aware Proxy (Cloud IAP)-secured resource using user default credentials?) question:
import google.auth
import requests
import json

def id_token_from_default_creds(audience):
    cred, proj = google.auth.default()
    # data necessary for ID token
    client_id = cred.client_id
    client_secret= cred.client_secret
    refresh_token = str(cred.refresh_token)
    return id_token_from_refresh_token(client_id, client_secret, refresh_token, audience)

def id_token_from_refresh_token(client_id, client_secret, refresh_token, audience):
    oauth_token_base_URL = "https://www.googleapis.com/oauth2/v4/token"
    payload = {"client_id": client_id, "client_secret": client_secret,
                "refresh_token": refresh_token, "grant_type": "refresh_token",
                "audience": audience}
    res = requests.post(oauth_token_base_URL, data=payload)
    return (str(json.loads(res.text)[u"id_token"]))

print("ID token from \"default\" credentials: %s" % id_token_from_default_creds("<IAP Client ID>"))

Any ideas how to pass IAP with local user credentials?

A: The audience client and the client need to be in the same project. This means that default credentials client ID and IAP client ID do not have matching project numbers. Using default credentials generated from gcloud auth application-default login gives the mismatch Client_ID for default credentials because the Client_ID should start with a project number. The project for Client ID used to obtain refresh token should match the project for IAP Client ID. Gcloud uses Client ID and secret defined in path_to/google-cloud-sdk/lib/googlecloudsdk/api_lib/auth/util.py for default credentials (DEFAULT_CREDENTIALS_DEFAULT_CLIENT_ID and DEFAULT_CREDENTIALS_DEFAULT_CLIENT_SECRET). Because of that, we can't use the refresh token from google.auth.default() without util.py change.
I ended up following Johns comment (Access website behind IAP programatically?), and created a desktop app in GCP Credentials. I'm using client_id and client_secret from the desktop app to first get auth_code, then refresh_token, and then id_token trough the Oauth2 API. This token then can be used in the header to pass IAP.
The code now opens a browser tab where the user needs to login, but that is fine for my use case. See https://stackoverflow.com/a/49129038/1411088 for the code example.


text:
Q: get data json file for angular js app-in-app in grails directly hi i want to access my json data file in my angular app inside an app  in grails. i dont find any way to address the json file clientside. in the tutorial the databinding is only cocered for json data so this is crucial for me.
function ShitCtrl($scope, $http) {

  $http.get('http://localhost:8080/webapp/clients.json').success(function(data) {
    $scope.shits = data;
  });
}

function ShitDetailCtrl($scope, $routeParams) {
  $scope.shitId = $routeParams.shitId;

}

this reports an 404 error. how can i solve this issue? when i address it in urlMappings
this does not work then the mappings are absolute.
the point is: grails maps everything based on urlMappings, so it is not possible to address a file directly from js.

A: config . groovy:
grails.resources.adhoc.patterns = [
        '/images/*',
        '/css/*',
        '/js/*',
        '/plugins/*',
        **'/staticData/*',**
        '/assets/*'

so this then works like a charm:
function ShitCtrl($scope, $http) {
  $http.get('../static/staticData/clients.json').success(function(data) {
    $scope.shits = data;
  });
}


text:
Q: Alternative to superclass field public class CustomNode extends GuiObject {

    public void doSomethingWithBase() {
        Pane base = getBase();
        //The problem is here, base can only be VBox or HBox, but
        //accessing it as a Pane removes a couple of needed features like
        //setFillHeight(boolean val), etc
        //I can do casting here (to VBox or HBox), but it doesn't look too elegant
        //Any alternatives?
    }

}

public abstract class GuiObject {

    private final Pane base;

    public Pane getBase() {
        return base;
    }

}

In doSomethingWithBase() I need to process base which can only be VBox or HBox, but I'm forced to use a superclass to get it, but also I'm forced to do casting, which I don't prefer.
Is there any alternative to casting here?

A: If you only have HBox or VBox in doSomethingWithBase you can use generics. Would look like this:
public class CustomNode extends GuiObject<VBox> {

    public void doSomethingWithBase() {
        VBox base = getBase();
        //The problem is here, base can only be VBox or HBox, but
        //accessing it as a Pane removes a couple of needed features like
        //setFillHeight(boolean val), etc
        //I can do casting here (to VBox or HBox), but it doesn't look too elegant
        //Any alternatives?
    }

}

public abstract class GuiObject<P extends Pane> {

    private final P base;

    public P getBase() {
        return base;
    }

}

If you have both VBox and HBox in doSomethingWithBase then the question is - how do you know what you get?