text:
Q: What could cause Command-Tab task switching to get "stuck"? When I Command-Tab to task switch (in both Mavericks and Yosemite), occasionally (maybe 60% of the time) the task switcher will behave as if the Tab button was held down. That is, the task-switcher selection will fly over to the right-most icon. If I mouse-over the app icons, the cursor will continue constantly moving to the right.
I doubt it's a stuck Tab key, because I use the Tab key all the time when coding, navigating Cocoa controls, etc...never have a problem with Tabs being constantly entered. This only ever occurs on Command-Tab.
Any ideas?

A: Just had the same issue.
Turns out it is because I've got my mouse in my bag and it's still connected to the bluetooth dongle on the machine. So essentially is the mouse.
As soon as I disconnected the mouse the issue went away.

A: Had the same issue today - almost 6 years later!
Couldn't find any workable solution online. I had already tried restarting and logging into another account with no help.
Finally reached out to the apple support.
They got me to do a safe boot (https://support.apple.com/en-us/HT201262).
The problem wasn't there in safe boot mode.
Then, booted back to normal mode - and the problem was gone there as well!

A: Trying to gather some more information: Are you running multiple monitors when you see this?  Do you have any tweaks, like Witch or Secrets, which could be modifying the default behavior?
For what it's worth my 2010 13" MBAir running Yosemite stops at the right-most icon when I hold Command-Tab. Command-` (once the switcher is running) stops at the far left.

A: The cause is most often a second mouse, or mouse-like device (eg Wacom tablet, or 3DConnexion mouse, or trackpad, or playstation controller - with something on it.
Every few months I forget to check - and it's always that.  Unplugging the various devices normally sorts it out.


text:
Q: How to mock method inside tested function using codeception I'm just trying to implement unit testing to my PHP application and really can't figure out how it works with mock/stub and Codeception
So I'm using Laravel and want to add testing to an API endpoint like this
$I->sendGET('/user/inventory/<user_id>');

Then in the controller I have function to authenticate the user, something like
public function getUserInventory($userId) {

    if ($this->authenticateUser($userId))
    {
        do some logic...
        if ($success) {
            return $good_data;
        } else {
            return $bad_data;
        }
    }
    return false;
}

authenticateUser function is not relevant to the test and I just want to mock the return to true or false so I can test the actual logic on whether it should return $good_data or $bad_data, is that possible?
I've tried to declare stub object before calling the sendGET function like this
Stub::make(
    'App\Http\Controllers\Controller',
    ['authenticateUser' => true],
    $this
);

$I->sendGET('/user/inventory/<user_id>');

but it doesn't seem to use the stub object inside the getUserInventory function when I ran the test.
Is there any way to use stub/mock method inside the $I->sendGET('/user/inventory/<user_id>'); test?
Hopefully my question make sense

redpajama_set_name: RedPajamaStackExchange


text:
Q: Configuring NetworkManager to use systemd-resolved without dnsmasq in 17.04 After upgrading to 17.04 from 16.04 I can't figure out how host name resolution system is meant to be configured.
First, I've noticed that after upgrade search domains have disappeared from /etc/resolv.conf. They came back once I've removed /etc/resolv.conf symlink and restarted NetworkManager. But then the contents became as follows:
# Generated by NetworkManager
search mydomain1 mydomain2
nameserver 127.0.1.1

Ok, search domains are there. But why nameserver 127.0.1.1 is there? No process is listening on that address, hence the name resolution doesn't work.
AFAIK, 127.0.1.1 is the hard-coded listen address of dnsmasq, which is not configured in /etc/NetworkManager/NetworkManager.conf:
[main]
plugins=ifupdown,keyfile

[ifupdown]
managed=false

[logging]
level=DEBUG

Actually, dnsmasq wasn't even installed after upgrade. After installing dnsmasq and adding the line dns=dnsmasq into NetworkManager.conf, everything works well, but I wonder if I am doing something wrong, or is it a bug in NetworkManager or somewhere else.
So my questions are, is it possible to use systemd-resolved instead of dnsmasq? If not, what is the purpose of moving to systemd-resolved?


text:
Q: Android Deep Copy of an ArrayList My ArrayList looks like this:
Parent1, Parent2, ..., Parentn
Each Parent has a ChildList
Child1, Child2, ..., Childm
Every Child holds some Strings, int etc.
How do I create a deep copy of it?


text:
Q: What exactly is multi-hot encoding and how is it different from one-hot? In one-hot encoding there is one bit reserved for each word we desire to encode.
How is multi-hot encoding different from one-hot? In what scenarios would it make sense to use it over one-hot?

A: Imagine your have five different classes e.g. ['cat', 'dog', 'fish', 'bird', 'ant']. If you would use one-hot-encoding you would represent the presence of 'dog' in a five-dimensional binary vector like [0,1,0,0,0]. If you would use multi-hot-encoding you would first label-encode your classes, thus having only a single number which represents the presence of a class (e.g. 1 for 'dog') and then convert the numerical labels to binary vectors of size $\lceil\text{log}_25\rceil = 3$.
Examples:
'cat'  = [0,0,0]
'dog'  = [0,0,1]
'fish' = [0,1,0]
'bird' = [0,1,1]
'ant'  = [1,0,0]

This representation is basically the middle way between label-encoding, where you introduce false class relationships (0 < 1 < 2 < ... < 4, thus 'cat' < 'dog' < ... < 'ant') but only need a single value to represent class presence and one-hot-encoding, where you need a vector of size $n$ (which can be huge!) to represent all classes but have no false relationships.
Note: multi-hot-encoding introduces false additive relationships, e.g. [0,0,1] + [0,1,0] = [0,1,1] that is 'dog' + 'fish' = 'bird'. That is the price you pay for the reduced representation.

A: The accepted answer seems rather eccentric to me. I think that is rarely done, if ever, and will usually yield bad results.
There's a much more common, sensible use case for this. "Multi-hot encoding" doesn't seem to be a standard term, but I'm not sure there's any standard term. scikit-learn refers to a multi label binarizer.
This is simply used for multi label problems. That is, problems where more than one label can be associated with each example.
For example, say you are trying to detect whether certain types of animal are in a photo. Note that multiple types of animal can be in a single photo. Say the possible types of animal are ['cat', 'dog', 'fish', 'bird', 'ant']. A photo containing cats and dogs would be represented as [1, 1, 0, 0, 0].

A: I too find the accepted answer likely wrong. I could not find any reference to such an encoding anywhere.
In Tensorflow and in Francois Chollet's (the creator of Keras) book: "Deep learning with python", multi-hot is a binary encoding of multiple tokens in a single vector.
Meaning, you can encode a text in a single vector, where all the entries are zero, except the entries corresponding to a word present in the text is one.
Please see the Tensorflow category_encoding output_mode parameter's description at
https://www.tensorflow.org/api_docs/python/tf/keras/layers/CategoryEncoding#args


text:
Q: How do I apply a model to predict and append the outcome for every observation in a dataframe? I'm a relative novice with R (STATA refugee).
I have a dataframe, the observations of which are individual people. I also have a model of superannuation balances by age. I want to append the predicted superannuation balance to each person based on their age (age at last birthday).
The model was built to smooth grouped mean data for superannuation balances by age:
library(mgcv)
# Age bracket mid-points
x = seq(22, 62, 5)

# Male age-bracket super balance medians
y = c(6, 21, 42, 65, 75, 110, 137, 150, 230)

# Model the super as a function of age bracket
mod = gam(y ~ s(x, k = 8), family = Gamma(link = "log"))

# Predict the super balance for each age
pred = cbind(Age = 20:64, Super = predict(mod, data.frame(x = 20:64), "response"))

# Plot raw data and predictions for each year
plot(y ~ x, xlim = c(20, 64), ylim = c(0, 250), las = 1)
points(pred, col = "red")

I also have another dataframe, age, that has many vectors, one of which is age. What I would like to do is add a new vector to this dataframe that uses mod to predict that individual's superannuation balance based on their age.
As an example dataframe (not my real data):
age=data.frame(seq(25,51,2))

An alternative would be to use the dataframe pred and to read off the relevant value for super from the appropriate age row and append that to age.
Unfortunately, I don't know how to do either of these things. I figured there must be a way to use vapply() to run a prediction of the model over age but couldn't make it work.
I also tried cbind():
cbind(age,y = predict(mod, newdata = age))

but got an error telling me the numbers of rows didn't match.
Any help much appreciated.

A: You are trying to bind a dataframe to a vector/array in
cbind(age,y = predict(mod, newdata = age))

The output of predict is an array:
> class(predict(mod, data.frame(x = 20:64)))
[1] "array"

So you need to use sth like the following:
New <- data.frame(age=seq(25,51,2))

pred <-  cbind(Age = New$age, newdata = predict(mod, data.frame(x = New$age), "response"))

OR
pred <-  cbind(Age = seq(25,51,2), newdata = predict(mod, data.frame(x=seq(25,51,2)), "response"))


text:
Q: Powershell set Attributes sh when name starts with ~ I need to write a script that goes recursive through several hundred directories and if it finds a file beginning with "~", the hidden and system attribute should be set at that file.
So far I got this:
Get-ChildItem C:\test\~* - Recurse | foreach {$_.Attributes = 'Hidden, System'}

But it only seems to change the first file.

A: *

*Use the -Filter parameter to find files beginning with ~.

*Add the -File switch to exclude directories.

*Remove the space between - and Recurse
This should work:
Get-ChildItem 'C:\test\' -Filter '~*' -Recurse -File | foreach {
    $_.Attributes = 'Hidden, System'
}

A: Do something like dir c:\ -recurse | ? Name -match "~", that gets you all with the ~ in. Then set the attribute like you are.


text:
Q: List Comprehension Not Working Through All Elements I'm working on a scrabble solver. I have 81 squares, A1 (top left corner) to I9 (bottom left)
and 3 lists of lists of length 9 with 9 elements each for the rows, columns and sub grids respectively.
I also have a masterList = sub + col + row
For example:
row[0] = [['1A', '2A', '3A', '4A', '5A','6A','7A','8A','9A']]

When I do this:
test = [i for i in masterList if 'A1' in i]
print test
print len(test)

The length is only 2 (it should be 3) and it only prints from the first 2 lists that make up masterList (so in this instance, it does not find row[0].
 test2 = [i for i in row if 'A1' in i]
 print test2

Works correctly. I'm not sure why it is doing this.

A: You cannot place an assigment statement with a print. Separate them as follows:
test = [i for i in test if 'A1' in masterList]
print test
print len(test)

As you can see here: print a = ... is invalid syntax

A: Your first and second list comprehension are not identical:
test = [i for i in test if 'A1' in masterList]

is not the same as
 test2 = [i for i in row if 'A1' in i]

For one, the ONLY thing the first test checks is to see if 'A1' is in masterList, you're not actually iteratively checking anything.
I can't explain why/what you should be getting because it's not clear from your question what is contained in test initially, but the fact that you're checking to see if 'A1' in i in one list comp and if 'A1' in masterList in the other is probably the source of the discrepancy.


text:
Q: how to read objectId of a field from one collection and insert that objectid as field to another collection? how to read objectId of a field from one collection and insert that objectid as field to another collection?
I have a collection called student which have objectId name address and teacherId as fields. also I have another collection teacher with objectId name designation. how can I take objectId of teacher from teacher collection and insert it into the field in the student collection.I am trying to get it objectId in this format like  ObjectId("5e97f6636e554578590b24758ae9")…


text:
Q: Concatenating __DIR__ constant with a string as an array value which is a class member in PHP Can anyone tell me why this doesn't work?
It's just a crude example of what I'm trying to do somewhere else.
$stuff = array(
    'key' => __DIR__ . 'value'
);

However, this produces an error:
PHP Parse error:  syntax error, unexpected '.', expecting ')' in /var/www/.../testing.php on line 6

Also, this works:
$stuff = array(
    'key' => "{__DIR__} value"
);

A: The first piece of code does not work because it's not a constant expression, as you are trying to concatenate two strings.  Initial class members must be constant.
From the documentation:

[property] initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

A: You can't use operator in a property initialization. The workaround is to use the constructor:
public function __construct()
{
  $this->stuff = array(
        'key'   =>  __DIR__ . 'value'
  );
}

From the PHP doc:

This declaration may include an initialization, but this
  initialization must be a constant value--that is, it must be able to
  be evaluated at compile time and must not depend on run-time
  information in order to be evaluated.

http://www.php.net/manual/en/language.oop5.properties.php

A: Set $stuff value on your constructor
function __construct()
{
$this->$stuff = array(
        'key'   =>  __DIR__ . 'value'
    );
}


text:
Q: Is there a way to use objects in the vertex buffer in Android's OpenGL ES 2.0 with Java? In C++, I could define a vertex such as
class Vertex
    {
    public:
        Vertex();
        ~Vertex();
        //Position
        float x, y, z, w;
        //Normals
        float nx, ny, nz, nw;
        //Textures
        float tu, tv;

    };

and then create a vertex buffer of an array of the above Vertex objects.  I would tell the shader what the offsets for the position, normal, and textures were, and the shader would be able to map the values correctly.
In Java on Android, with OpenGL ES 2.0, I've been able to create individual float arrays for position, normals, and textures, or a single float array for all of them where I specify the offsets, but I haven't found a way to tell the buffer I'm using an array of objects.  Is this possible?  Or do I need to generate an array of floats myself?

A: No, as far as I know this is not possible in Java.
In C and C++ this works as in an array of objects, the objects are aligned contiguously in memory, as are their member variables. So you have one big contiguous block of data to pass to GL.
Java stores object by reference - so you rather have an array of references. The actual objects are not aligned contiguously in memory.


text:
Q: uninitialized constant ActiveRecord::Base::Delayed::Job I am trying to add an owner field to DelayedJob. I found this SO answer showing a way to do it
But when I code things up like mentioned in that answer, and in the rails console I do
SomeArModel.new.jobs

I get this error:
NameError: uninitialized constant ActiveRecord::Base::Delayed::Job
The error points to the has_many:
class ActiveRecord::Base
  has_many :jobs, :class_name => "Delayed::Job", :as => :owner
  ....

Any ideas on what is going on here and how I can fix it?


text:
Q: Partial derivative operator from 2 variables multiplied by functions
My main issue when I try to put all the equations in Mathematica ,I get different solution from what I expected should be,Epsilon 11,22,12 are functions and multiplied by Their partial derivative operator,Can anyone confirm if the written code is right?
Clear[op1, op2, op3]
Subscript[\[Epsilon], 11] = Subscript[\[Epsilon], rr]*Cos[\[Theta]]^2 + Subscript[\[Epsilon], \[Theta]\[Theta]]*Sin[\[Theta]]^2 -
     Subscript[\[Epsilon], r\[Theta]]*Sin[2*\[Theta]] & ;
op1 = Sin[\[Theta]]^2*D[#1, {r, 2}] + Cos[\[Theta]]^2*(1/r)*D[#1, r] + Cos[\[Theta]]^2*(1/r^2)*D[#1, {\[Theta], 2}] -
     Sin[2*\[Theta]]*(1/r^2)*D[#1, \[Theta]] + Sin[2*\[Theta]]*(1/r)*D[#1, r]*D[#1, \[Theta]] & ;
firstterm := TrigExpand[op1[Subscript[\[Epsilon], 11][f[r, \[Theta]]]] +
     op1[f[r, \[Theta]]]*Subscript[\[Epsilon], 11][f[r, \[Theta]]]];
Subscript[\[Epsilon], 22] = Subscript[\[Epsilon], rr]*Sin[\[Theta]]^2 + Subscript[\[Epsilon], \[Theta]\[Theta]]*Cos[\[Theta]]^2 +
     Subscript[\[Epsilon], r\[Theta]]*Sin[2*\[Theta]] & ;
op2 = Cos[\[Theta]]^2*D[#1, {r, 2}] + Sin[\[Theta]]^2*(1/r)*D[#1, r] + Sin[\[Theta]]^2*(1/r^2)*D[#1, {\[Theta], 2}] +
     Sin[2*\[Theta]]*(1/r^2)*D[#1, \[Theta]] - Sin[2*\[Theta]]*(1/r)*D[#1, r]*D[#1, \[Theta]] & ;
secondterm := TrigExpand[op2[f[r, \[Theta]]]*Subscript[\[Epsilon], 22][f[r, \[Theta]]] +
     op2[Subscript[\[Epsilon], 22][f[r, \[Theta]]]]];
SSSS = Expand[firstterm + secondterm];
Subscript[\[Epsilon], 12] = -0.5*Subscript[\[Epsilon], \[Theta]\[Theta]]*Sin[2*\[Theta]] + 0.5*Subscript[\[Epsilon], rr]*Sin[2*\[Theta]] +
     Subscript[\[Epsilon], r\[Theta]]*Cos[2*\[Theta]] & ;
op3 = 2*(Sin[\[Theta]]*Cos[\[Theta]]*D[#1, {r, 2}] - Sin[\[Theta]]*Cos[\[Theta]]*(1/r)*D[#1, r] -
      Sin[\[Theta]]*Cos[\[Theta]]*(1/r^2)*D[#1, {\[Theta], 2}] - Cos[2*\[Theta]]*(1/r^2)*D[#1, \[Theta]] +
      Cos[2*\[Theta]]*(1/r)*D[#1, r]*D[#1, \[Theta]]) & ;
thirdterm = Expand[op3[f[r, \[Theta]]]*Subscript[\[Epsilon], 12][f[r, \[Theta]]] + op3[Subscript[\[Epsilon], 12][f[r, \[Theta]]]]];
TrigExpand[TrigExpand[thirdterm - SSSS]]

The solution that I get in Mathematica is like below
-((2*Subscript[\[Epsilon], r\[Theta]]*
      Derivative[0, 1][f][r, \[Theta]])/r^2) -
   (1.*Subscript[\[Epsilon], rr]*Derivative[0, 2][f][r, \[Theta]])/
  r^2 -
   (1.*Subscript[\[Epsilon], rr]*Derivative[1, 0][f][r, \[Theta]])/r +
   (2*Subscript[\[Epsilon], r\[Theta]]*
    Derivative[0, 1][f][r, \[Theta]]*
    Derivative[1, 0][f][r, \[Theta]])/r -
   1.*Subscript[\[Epsilon], \[Theta]\[Theta]]*
  Derivative[2, 0][f][r, \[Theta]]

A: Here is an approach that gives an expression similar to the one you want.  The main differences between this approach and the one in the original post are

*

*Variables $\epsilon_{r\theta}$, etc, must be explicit functions of $r,\theta$.

*Variables $\epsilon_{11}$, etc, are not "functions", so no & at the end.

*The mixed partial derivatives, $\partial^2/\partial r\partial\theta$ are second derivatives, not the product of first derivatives.

*Subscripts are not used, so the code is easier to read.

*Exact values, like 1/2, are used instead of approximate ones, like 0.5.

First, here are some preliminary definitions.  The rules allow us to work with $f, g, h$ instead of the subscripted variables.  The next definition tells Mathematica how to display the partial derivatives when we use TraditionalForm.  These definitions will be used later.
ClearAll["Global`*"]
Remove[ϵ]
rules = {
   f -> Subscript[ϵ, rr],
   g -> Subscript[ϵ, θθ],
   h -> Subscript[ϵ, rθ]};

Derivative /:
 MakeBoxes[Derivative[α__][f1_][vars__?AtomQ],
  TraditionalForm] :=
 Module[{bb, dd, sp},
  MakeBoxes[dd, _] ^=
   If[Length[{α}] == 1, "\[DifferentialD]", "∂"];
  MakeBoxes[sp, _] ^= "\[ThinSpace]";
  bb /: MakeBoxes[bb[x__], _] := RowBox[Map[ToBoxes[#] &, {x}]];
  TemplateBox[{ToBoxes[bb[dd^Plus[α], f1]],
    ToBoxes[Apply[bb,
      Riffle[Map[
        bb[dd, #] &, (Pick[{vars}, #]^Pick[{α}, #] &[
          Thread[{α} > 0]])], sp]]],
    ToBoxes[Derivative[α][f1][vars]]}, "ShortFraction",
   DisplayFunction :> (FractionBox[#1, #2] &),
   InterpretationFunction :> (#3 &), Tooltip -> Automatic]]

Now, here is the main calculation.  The variables $f, g,h$ are explicit functions of $r,\theta$.
ϵ11 = f[r, θ]*Cos[θ]^2 + g[r, θ]*Sin[θ]^2 - h[r, θ]*Sin[2*θ];

ϵ22 = f[r, θ]*Sin[θ]^2 + g[r, θ]*Cos[θ]^2 + h[r, θ]*Sin[2*θ];

ϵ12 = 1/2*f[r, θ]*Sin[2*θ] - 1/2*g[r, θ]*Sin[2*θ] + h[r, θ]*Cos[2*θ];

op1 = Sin[θ]^2*D[#1, {r, 2}] +
    Cos[θ]^2 (1/r)*D[#1, r] +
    Cos[θ]^2*(1/r^2)*D[#1, {θ, 2}] -
    Sin[2*θ]*(1/r^2)*D[#1, θ] +
    Sin[2*θ]*(1/r)*D[#1, r, θ] &;

op2 = Cos[θ]^2*D[#1, {r, 2}] +
    Sin[θ]^2*(1/r)*D[#1, r] +
    Sin[θ]^2*(1/r^2)*D[#1, {θ, 2}] +
    Sin[2*θ]*(1/r^2)*D[#1, θ] -
    Sin[2*θ]*(1/r)*D[#1, r, θ] &;

op3 = 2*(Sin[θ]*Cos[θ]*D[#1, {r, 2}] -
      Sin[θ]*Cos[θ]*(1/r)*D[#1, r] -
      Sin[θ]*Cos[θ]*(1/r^2)*D[#1, {θ, 2}] -
      Cos[2*θ]*(1/r^2)*D[#1, θ] +
      Cos[2*θ]*(1/r)*D[#1, r, θ]) &;

lhs = op1[ϵ11] + op2[ϵ22];
rhs = op3[ϵ12];

FullSimplify[rhs - lhs] /. rules // Expand // TraditionalForm

This expression is, of course, the left hand side of the desired equation minus the right hand side.  The expression has the same 6 derivatives as the desired equation.  The signs and the exponents of $r$ are all the same.  The only difference that I see is the first two terms of this expression have the factor of 2 in the numerator instead of in the denominator.  Perhaps there is a typo somewhere?


text:
Q: How do you inspect a react element's props & state in the console? React Developer Tools give a lot of power to inspect the React component tree, and look at props, event handlers, etc. However, what I'd really like to do is to be able to inspect those data structures in the browser console.
In chrome I can play with the currently selected DOM element in the console using $0. Is there a way to extract React component info from $0, or is it possible to do something similar with the React Dev Tools?

A: Open console (Firefox,Chrome) and locate any reactjs rendered DOM element or  alternatively execute js script to locate it:
document.getElementById('ROOT')

Then check for element properties in object property viewer for attributes with name beginning like '__reactInternalInstace$....' expand _DebugOwner and see stateNode.
The found stateNode will contain (if it has) 'state' and 'props' attributes which is used heavily in reactjs app.

A: Though the accepted answer works, and is a great method, in 2020 you can now do a lot of inspection without using the $r method. The Components tab of React DevTools will show you props and detailed state when you select the relevant component (make sure you're on the right level), as well as let you do other things like suspend it or inspect the matching DOM element (little icons in the top right).

A: Assign the state or prop object to the window object:
window.title = this.state.title

And then from the dev tools console you can try different methods on the exposed object such as:
window.title.length

8

A: An answer to your question can be found here in a similar question I asked:
React - getting a component from a DOM element for debugging
I'm providing an answer here because I don't have the necessary reputation points in order to mark as duplicate or to comment above.
Basically, this is possible if you are using the development build of react because you can leverage the TestUtils to accomplish your goal.
You need to do only two things:

*

*Statically store the root level component you got from React.render().

*Create a global debug helper function that you can use in the console with $0 that accesses your static component.

So the code in the console might look something like:
> getComponent($0).props

The implementation of getComponent can use React.addons.TestUtils.findAllInRenderedTree to search for match by calling getDOMNode on all the found components and matching against the passed in element.

A: Using React Developer Tools you can use $r to get a reference to the selected React Component.
The following screenshot shows you that I use React Developer Tools to select a component (Explorer) which has a state-object callednodeList. In the console I can now simply write $r.state.nodeList to reference this object in the state. Same works with the props (eg.: $r.props.path)

A: You can attach a reference to the window object like
import { useSelector } from "react-redux";
function App() {

    // Development only
    window.store = useSelector((state) => state);

    return (
        <div className="App">
        </div>
    );
}

export default App;

Then access it from the console
store
{states: {…}}
states:
someProperty: false
[[Prototype]]: Object
[[Prototype]]: Object

[Console][1]
[1]: https://i.stack.imgur.com/A4agJ.png


text:
Q: which one have I to choose between "union" and "case"? I have a list of tables (i.e. productsA, productsB, productsN, ...) each product in these tables may have a comment (stored in the comments table), if I hed to select top 10 ordered comments wich of these is the best solution to be adopted (in terms of performances and speed)?
using UNION:
http://www.sqlfiddle.com/#!3/bc382/1
select TOP 10 comment_product, product_name, comment_date FROM (
   select comment_product, product_name, comment_date from comments inner join productsA on product_id = id_product WHERE product_type = 'A'
UNION
   select comment_product, product_name, comment_date from comments inner join productsB on product_id = id_product WHERE product_type = 'B'
UNION
   select comment_product, product_name, comment_date from comments inner join productsC on product_id = id_product WHERE product_type = 'C'
) as temp ORDER BY comment_date DESC

using CASE:
http://www.sqlfiddle.com/#!3/bc382/2
select TOP 10 comment_product, comment_date,
CASE product_type
  when 'A' then (select product_name from productsA as sub where sub.id_product = com.product_id)
  when 'B' then (select product_name from productsB as sub where sub.id_product = com.product_id)
  when 'C' then (select product_name from productsC as sub where sub.id_product = com.product_id)
END
FROM comments as com
ORDER BY comment_date DESC

A: I'd suggest you need neither UNION or CASE and can just JOIN multiple times to comments:
SELECT TOP 10
            comment_product
          , COALESCE(a.product_name,b.product_name,c.product_name) AS product_name
          , comment_date
FROM comments z
LEFT JOIN productsA a
    ON z.product_id = a.id_product  AND z.product_type = 'A'
LEFT JOIN productsB b
    ON z.product_id = b.id_product  AND z.product_type = 'B'
LEFT JOIN productsC c
    ON z.product_id = c.id_product  AND z.product_type = 'C'
WHERE COALESCE(a.id_product,b.id_product,c.id_product) IS NOT NULL
ORDER BY z.comment_dateDESCC

A: The second query would most probably use an index scan on comment_date with nested loops over product tables, i. e. at most 10 logical seeks plus whatever it takes to read 10 records from comments
This first query would most probably use an index scan and sort over each of the queries, then a MERGE UNION of their results.
If you have indexes on comment_date and id_product in all product tables, the second query would be much faster.

A: I think this one. INNER JOIN is faster than UNION and nested queries.
Here's a Demo on SqlFiddle.
SELECT TOP 10 comment_product, comment_date,
case when product_type = 'A' then a.product_name
when product_type = 'B' then b.product_name
when product_type = 'C' then c.product_name
else '' end
FROM comments INNER JOIN productsA a ON product_id = a.id_product
INNER JOIN productsB b ON product_id = b.id_product
INNER JOIN productsC c ON product_id = c.id_product
ORDER BY comment_date DESC

A: As much as I don't like it, it seems that using CASE will be faster. Any SELECT TOP N will result in N sub-queries. If you have index on id_product in all 3 product tables that should be fast enough.
UNION solution will trigger 3 full queries, union, sort and then top.


text:
Q: Probability and expectation of an indicator multiplied by random variable Could you advice me on the following inequality
$P(|Z_n\mathbb{1}_{|Z_n|<n^{0.75}}|>\epsilon)\le P(|Z_n|<n^{0.75})$
and equality
$E(Z_n^2)E(\mathbb{1}^2_{|Z_n|\ge n^{0.75}})=P(|Z_n|\ge n^{0.75})$.

A: Assuming $Z_n = 0$ happens infrequently, the first inequality has a positive LHS when the indicator is 1 (then $P[|Z_n| > \epsilon] \le 1$).
For the second one you have for any event $A$: $$\mathbb{E}[1^2_A] = \mathbb{E}[1_A] = \mathbb{P}[A]$$ and apparently we are assuming $\mathbb{E}[Z_n^2] = 1$.


text:
Q: Working with default path Okay guys, I made one research and I found nothing to exemplify correctly that I did this and to not post this as someone lazy. My problem is:
I have one image on the rsc folder of my project. I can acess it from a full path name:
C:\Users\Victor\workspace\SHST\rsc\image.jpg

But, I need to move this folder in future to another desktop and 'course I can't change for every variable the Main path "C:\Users\Victor\workspace\". I tried to thing about environment variables but even though I swear  I found nothing. I know there is a way to do this and it's not so hard as it's seems, that's why I can't realize I found nothing about it. Could anyone help me please?

A: Put the image into C:\Users\Victor\workspace\SHST\res\ folder in your project and load the image file by call res/image.jpg. Than, anywhere you'll replace your project, it should being loaded.


text:
Q: JS for-loop doesn't work properly. Getting inaccurate value as a 'total' Trying to calculate array items, but keep getting an incorrect total value. Any thoughts where can be a mistake?

let input;
const numbers = [];
let total = 0;

//debugger;

do {
  input = prompt("Please, enter the number");
  if (input === null) {
    if (numbers.length > 0) {
      alert(`Total is ${total}`);
    }
    break;
  }

  input = parseInt(input);
  console.log("input: ", input);
  if (isNaN(input)) {
    continue;
  } else {
    numbers.push(input);
  }

  for (const [i, v] of numbers.entries()) {
    total = total + v;
  }

  console.log("total: ", total);
} while (input !== null);

A: For now at any step you add to the total, the new total, not replace the new total with the old one.
You can do:

let input;
const numbers = [];
let total = 0;

//debugger;

do {
  input = prompt("Please, enter the number");
  if (input === null) {
    if (numbers.length > 0) {
      alert(`Total is ${total}`);
    }
    break;
  }

  input = parseInt(input);
  console.log("input: ", input);
  if (isNaN(input)) {
    continue;
  } else {
    numbers.push(input);
  }
  total=0;
  for (const [i, v] of numbers.entries()) {
    total = total + v;
  }

  console.log("total: ", total);
} while (input !== null);

or just:

let input;
let total = 0;

//debugger;

do {
  input = prompt("Please, enter the number");
  if (input === null) {
      alert(`Total is ${total}`);
    break;
  }

  input = parseInt(input);
  console.log("input: ", input);
  if (isNaN(input)) {
    continue;
  } else {
    total += input;
  }

  console.log("total: ", total);
} while (input !== null);

A: You're looping over the whole array every time. So every number gets added to the total not just when you enter it, but again for every later number you enter.
Imagine that you enter 1 for the first number. Then numbers is [1] and total is 0 going into your loop, which adds 1 to total to make it 1. So far, so good.
Then you enter 2. Now going into your loop we have total as 1 and numbers as [1,2], so your loop adds add 1 and 2 to the previous value of 1 and sets total to 4 instead of 3.
Then you enter 3. Going into the loop this time, total is 4 and numbers is [1,2,3]. So the loop adds 1+2+3 to the previous 4 and now total is 10 instead of 6.
Basically, there's no need to loop because total already includes all the previously-entered numbers. So you can replace this loop:
 for (const [i, v] of numbers.entries()) {
    total = total + v;
  }

With this single statement:
  total = total + input;

Which can also be written like this:
  total += input;

Alternatively, since you're keeping all the entered numbers in an array, you can wait until they're all entered and then loop over that array then to add them up. But then you don't have a subtotal to display after each number.


text:
Q: Is there a short notation for function composition? So I think that if there exists two functions $f_1 \colon X \to Y$ and $f_2 \colon Y \to Z$ you can notate their composition using $(f_1 \circ f_2)(x) = f_3(x)$ right? If I have many functions that I need to compose, is there some shorter notation I can use such as $f_3 \colon X \to Y \to Z$ or something? The first example can get tedious when there are a lot of functions/mappings.
I already thought of putting all the sets in a some auxiliary set $V = (X_1,...X_n)$ and then defining $f_i \colon X_i \to X_{i+1}$ with $0 < i \leq n$ so I can notate composition like so $(f_1 \circ...\circ f_n)(x)$. But some functions are partial so I need to explicitly use the partial function arrow with a bar sometimes in this format $f_3 \colon X \to Y \to Z$. Would have demonstrated the bar arrow here but needs extra package installed.
Edit:
In the context of the paper I'm writing, I'm explaining the specific ways in which the functions work with words because its computer science work that is hard to express succinctly with maths notation, but I would still like to show the relationship between the these functions using function notation. I assumed this was the best way to show this relationship. I'm open to the suggestion of alternative notations though.

A: You don't need to have to add the $(x)$ in the example you give.  So you can write $(f_1 \circ f_2)(x) = f_3(x)$ as $f_1 \circ f_2 = f_3$.
If you are doing a large indexed set of composed functions then big circle notation works just like $\Sigma$ for sums and $\Pi$ for product. $\bigcirc_{i=1}^nf_i$
However if you are doing a great deal of compositions simply define your notation to have juxtaposition to be equivalent to composition $f_2(f_1(x)) = (f_1f_2)(x) $ (or whatever ordering convention is most useful to you).

A: The standard notation in my area of interest (fractal geometry and analysis on fractals) is to use superscript notation for functional composition.  This is not unreasonable, as the set of functions on a space, together with the operation of composition, has a nice algebraic structure (a monoid?  a semigroup?  I can never remember which is which—there is an identity function, but inverses don't necessarily exist).
To compose multiple functions, define a "word" as a sequence (or tuple) of indices, and denote the composition along that sequence with a superscript.  For example,
$$ \omega = (\omega_1, \omega_2, \omega_3, \omega_4, \omega_5), $$
where each of the $\omega_i$ is an element of some index set.  Then
$$ f^\omega = f_{\omega_5} \circ f_{\omega_4} \circ f_{\omega_3} \circ f_{\omega_2} \circ f_{\omega_1}. $$


text:
Q: How to delete images in Media Library without deleting the file in server in wordpress I have used  a plugin https://wordpress.org/plugins/best-import/ in oder to import all images from server into my wordpress media lirabry. Unfortunately, I had mistakenly uploaded many necessary files.
Now, want to delete these files from MEDIA without deleting those in server.

A: In your admin panel go to media, you will render all your files. Then click bulk select, select all the files you wish to delete, then click delete selected. This will just delete it off your site.
A good plugin for this is Product CSV importer (You can download just products or all files)


text:
Q: Magento Module Not Loading I have created a very simple module for Magento. All that I have done so far is declared a module and created its config.xml file. I am trying to read the xpath from the file, however nothing is showing up. The directory is correct and all files are in their place. Does anyone know what the problem might be, because I'm quite new to Magento and I have spent hours googleing it.

<?xml version="1.0"?>
<config>
      <modules>
            <First_Module>
                  <active>true</active>
                  <codePool>local</codePool>
            </First_Module>
      </modules>
</config>

<?xml version="1.0"?>
<config>
      <default>
            <some>
                  <random>
                        <xpath>Here is some value.</xpath>
                  </random>
            </some>
      </default>
</config>

A: All I had to do is re-configure the location of Magento.
System -> Configuration -> General -> (And I set the location to my country Ex. United Kingdom )
At least that's how I managed to get it to work :)

A: A couple of problems here, firstly you haven't defined the module and version at the top of config.xml, also you should be defining system -> configuration menu items in system.xml rather than config.xml (in the same directory as config.xml).  Finally in later versions of Magento you need to define the access control for you module in order for admin to correctly function (this is good practice regardless of Magento version).  This can be done inside config.xml, but putting it instead inside adminhtml.xml (again in the same directory as config.xml) keeps things more manageable as config.xml can get pretty long for more complex modules.
The module definition inside app/etc/modules looks fine.
So you would have something like this for your config.xml:
<?xml version="1.0"?>
<config>
    <modules>
        <First_Module>
            <version>0.1.0</version>
        </First_Module>
    </modules>
    ...
</config>

And this for your system.xml (defining your system configuration menu items):
<?xml version="1.0"?>
<config>
    <tabs>
        <customtab translate="label">
            Tab Header
            <sort_order>500</sort_order>
        </customtab>
    </tabs>
    <sections>
        <section1 translate="label">
            Section Label
            <tab>customtab</tab>
            <frontend_type>text</frontend_type>
            <sort_order>1</sort_order>
            <show_in_default>1</show_in_default>
            <show_in_website>1</show_in_website>
            <show_in_store>1</show_in_store>
            <groups>
                <optiongroup translate="label">
                    Option Group Header
                    <frontend_type>text</frontend_type>
                    <sort_order>1</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>1</show_in_store>
                    <fields>
                        <field1>
                            Field 1 Name
                            <frontend_type>text</frontend_type>
                            <sort_order>1</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </field1>
                        <field2>
                            Field 2 Name
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>2</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </field2>
                        <field3>
                            Field 3 Name
                            <frontend_type>hidden</frontend_type>
                            <sort_order>3</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                        </field3>
                    </fields>
                </optiongroup>
            </groups>
        </section1>
    </sections>
</config>

Note the above creates a custom tab and has a few example options added.
Finally, your adminhtml.xml defining ACL for your module would be something like this:
<?xml version="1.0"?>
<config>
    <acl>
        <resources>
            <all>
                <title>Allow Everything</title>
            </all>
            <admin>
                <children>
                    <system>
                        <children>
                            <config>
                                <children>
                                    <section1 module="module">
                                        <title>First Module</title>
                                    </section1>
                                </children>
                            </config>
                        </children>
                    </system>
                </children>
            </admin>
        </resources>
    </acl>
</config>

With this in place you can then pull these config options using:
Mage::getStoreConfig('section1/optiongroup/field1');


text:
Q: swagger API documentation with my own yaml file I have my API documented with Swagger. For developer convenience I would like to provide the swagger GUI on my website as well. However, my provider has not installed the php yaml extension. It implies that I can't use the GUI on my own website.
So, I would like to use a third party GUI. I know that I can use https://petstore.swagger.io/ and enter the link to my yaml file in the text box. This is also not really user friendly. I prefer to open the GUI and specify the yaml when calling the url. For the user the GUI opens with my API definition.
Any thoughts?

A: If for some reason you cannot host Swagger UI youself, here are some alternatives you can try:

*

*Use SwaggerHub to host your API definition and docs.
Disclosure: I work for the company that makes SwaggerHub.

*Use GitLab to host your OpenAPI YAML/JSON file. GitLab uses Swagger UI to render OpenAPI files. Example:
https://gitlab.com/gofus/gofus-api/blob/dev/swagger.yaml

*Use https://petstore.swagger.io with the url query parameter to automatically load your API definition:
https://petstore.swagger.io?url=https://yoursite.com/api.yaml

For this to work, the server where your OpenAPI file is hosted must use HTTPS and support CORS.


text:
Q: Error occurred when a localspark session instance accessed by two application at same time. An error occurred while calling o2402.defaultParallelism In my case two applications are simultaneously trying to access the same spark context. But at some cases I got this defaultParallelism error since spark context is stopped.
Error stack trace:
py4j.protocol.Py4JJavaError: An error occurred while calling o2402.defaultParallelism.

: java.lang.IllegalStateException: Cannot call methods on a stopped SparkContext.
This stopped SparkContext was created at:

org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:423)
py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
py4j.Gateway.invoke(Gateway.java:238)
py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
py4j.GatewayConnection.run(GatewayConnection.java:238)
java.lang.Thread.run(Thread.java:745)

The currently active SparkContext was created at:

(No active SparkContext.)

    at org.apache.spark.SparkContext.assertNotStopped(SparkContext.scala:100)
    at org.apache.spark.SparkContext.defaultParallelism(SparkContext.scala:2359)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:745)```

A: Reason:
Stop the spark context before it application ends.
Explanation:
Let us consider two applications are trying to access the spark context(parallel process).

*

*Initially at t=0, Application 1 starts the spark context and process
is ongoing

*At t=1 application 2 starts and it also uses the same
spark context.

*At t=3, Application 1 completed and it kills the local
spark context it creates.

*At t=4, Application 2 still running and it
tries to access the killed spark context So It throws the above error and
application terminated

Solution:
Don't kill the spark context before both the application complete.


text:
Q: iOS deep link only works once after launch I'm using this function in AppDelegate.swift to deep link to a specific ViewController:
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool{
    if(url.host == "myviewcontroller"){
        window?.rootViewController?.performSegueWithIdentifier("DeepLinkToPushMessage", sender: nil)

    }
    return true

This is in my info.plist: http://www.bilder-upload.eu/show.php?file=2d634c-1464972321.jpg
Deep linking to a specific ViewController is working like this: myapp://myviewcontroller
But unfortunately it only works once. I have to restart my app to make deep linking workable again otherwise it only opens my app without deep linking to the ViewController.
What am I doing wrong?

A: I had this same issue with a QR Reader I was building my solution as to add a .stoprunning and a .startrunning at the bottom of the function to keep it from just stopping and crashing the app after it read a QR code once. not sure if this will solve your issue or not.
below is my code
extension QRViewController: AVCaptureMetadataOutputObjectsDelegate {
        func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
            // Check if the metadataObjects array is not nil and it contains at least one object
            if metadataObjects.isEmpty {
                qrCodeFrameView?.frame = CGRect.zero

                captureSession.stopRunning()
                captureSession.startRunning()
                return


text:
Q: Convolution of Uniform Distribution and Square of Uniform Distribution I am trying to find the CDF of $Z=X+Y$ whereby $X$ and $Y$ are random variables. Given that the CDF of Z is:
$$F_Z(z)=\int F_X\left(z-y\right)f_Y(y)dy$$
Given that $X$ is uniform distribution over $[0,1]$ with:
$$f_X \left(x \right)=\frac{1}{\sigma }\left [ H\left ( x \right ) -H\left ( x-\sigma  \right )\right ]$$
$$F_X \left(x \right)=\frac{x}{\sigma }\left [ H\left ( x \right ) -H\left ( x-\sigma  \right )\right ]$$
And $Y$ is square of uniform distribution over $[0,1]$ with:
$$f_Y \left(x \right)=\frac{log\left ( \frac{\sigma ^{2}}{x} \right )}{\sigma ^{2}}$$
$$F_Y \left(x \right)=\frac{x\left ( 1+2log\left ( \sigma \right ) - log\left ( x \right )\right )}{\sigma ^{2}}$$
For $\sigma=1$, how I started to solve is by partitioning the problem to $0<z<1$ and $1<z<2$. I used the integration below with its limits to obtain the solution:
$$\int_0^z (z-y) \log \left(\frac{1}{y}\right) \, dy=\frac{1}{4} z^2 (3-2 \log (z))$$
$$\int_{z-1}^1 (z-y) \log \left(\frac{1}{y}\right) \, dy=\frac{1}{4} \left(2 \left(z^2-1\right) \log (z-1)-3 (z-2) z\right)$$
Checking against numerical results, the first solution I obtained is correct. The second is not because it gives me the following graph for $1<z<2$:

Where am I wrong in the second integral? Is it the limits? Or is it something else? Thanks

A:
If $V\sim U[0,1]$ then $Y:=V^2$ has:
$$\begin{eqnarray*}
&i)&f_{Y}(y)=\frac{{\bf 1}_{\{0\leqslant y\leqslant 1\}}}{2\sqrt{y}}\\
&ii)&F_{Y}(y)={\bf 1}_{\{y > 1\}} + {\bf 1}_{\{0\leqslant y\leqslant 1\}}\sqrt{y}
\end{eqnarray*}
$$

This is in contrast with your pdf $f_Y(y)=\log (1/y)$.
In addition, assuming that $X$ and $Y$ are independent, we have
$$
\begin{eqnarray*}
F_{Z}(z) &=& {\bf 1}_{\{z \geqslant 2\}} + {\bf 1}_{\{0\leqslant z <2\}}\int_{-\infty}^{\infty}F_{X}(z-y)f_{Y}(y)\text dy \\
&=& {\bf 1}_{\{z \geqslant 2\}} + {\bf 1}_{\{0\leqslant z <2\}}\int_{-\infty}^{\infty}\frac{z-y}{2\sqrt{y}}{\bf 1}_{\{0\vee z-1\ \leqslant y\leqslant\  z \wedge 1\}}\text dy\\
&=& {\bf 1}_{\{z \geqslant 2\}} + {\bf 1}_{\{0\leqslant z <1\}}\int_{0}^{z}\frac{z-y}{2\sqrt{y}}\text dy  + {\bf 1}_{\{1\leqslant z <2\}}\Big(\int_{z-1}^{1}\frac{z-y}{2\sqrt{y}}\text dy + \int_{0}^{z-1}\frac{1}{2\sqrt{y}}\text dy\Big).
\end{eqnarray*}
$$
Hence,

$$
\begin{eqnarray*}
F_{Z}(z) &=& \ \ {\bf 1}_{\{z \geqslant 2\}} + {\bf 1}_{\{0\leqslant z < 1\}}\frac{2}{3}z^{3/2} \\ && + {\bf 1}_{\{1\leqslant z < 2\}}\Big(z-\frac{1}{3}-z(z-1)^{1/2}+\frac{1}{3}(z-1)^{3/2}+(z-1)^{1/2}\Big)\,.
\end{eqnarray*}
$$


text:
Q: Bar Code does not Print in crystal report I'm rendering a report programatically to PDF. One of the text boxes is supposed to display barcode font and it is actually not displaying anything. How can I fix this? I am using IDAutomationHC39M for converting string into barcode type.
Any other solution for this?

A: Here is a solution which works for me. I went with a jQuery based bmp generator (Image generator).  It's very easy to implement and it works very well.
You can download it from here
Just includes in your header like:

And divs which need barcodes should have the same class name for example say `barcodecls".
405479

405339

405341

Then run this script on document ready:

*

*Here is a Demo Link


text:
Q: D3 javscript: How to add a div in aura component? I am trying to create a map hierarchy visual aura component using D3 library and d3 tree and d3.hierachy methods. The original code had circles in place for the nodes, but I want to append a div so that I can have a square box with information/fields placed within the div. The problem is that I cant seem to get any formatting to show up on the aura component. Maybe it has to do with the strict rules on interacting with the DOM in salesforce, however I am not sure because I'm still fairly new to development in general.
Here is a pic of the component:

CSS

Relevant Js

The commented code is of course the circle that was previously there and that I am trying to replace with a div having a border. Can I even do this within salesforce?
Component cmp

Helper js
({
drawOrgChart : function(component, event, helper) {

  var treeData ={
                  "name": "Durango Holding",
                  "children": [
                      { "name": "Durango Trucking"},
                      { "name": "Durango Leasing" },
                      { "name": "VW",
                        "children" : [
                            { "name" : "Golf"},
                            { "name" : "Beetle"}
                        ]
                      },
                      { "name": "Hyundai"},
                   ]
                 };

  console.log(treeData);

 //setting the dimensions and margins of the diagram
 var margin = {top: 40, right:30, bottom:50, left:30};
 var width = 1260 - margin.left - margin.right;
 var height = 600 - margin.top - margin.bottom;

 //Declare a tree Layout and assign its size
 var treemap = d3.tree()
             .size([width, height]);

 //Assigns the data to hierarchy using parent-child relationships
 var nodes = d3.hierarchy(treeData, function(d){
                    return d.children;
                 });
 console.log(nodes);

 /*NOTE: This assigns a range of properties to each node including (node.data, node.depth, node.height, node.parent, node.children)
 We are telling the function to use the "children" element from treeData to generate property of the nodes. */

 //Map the node data to tree Layout
 nodes = treemap(nodes);
 console.log(nodes);

 //Append the Map(SVG) to the body of the Lightning Component
 var svg = d3.select("body")
         .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
         .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

 //Add All Links between nodes
 var link = svg.selectAll(".link")
           .data(nodes.descendants().slice(1)) //We are not including the main 'root' node as since its drawn from child to parent.
           .enter()
           .append("path")
           .attr("class", "link")
           .attr("fill", "none") //Including all the styles directly here as the Style configured is not applied to lighting component.
           .attr("stroke", "#ccc")
           .attr("stroke-width", "2px")
               .attr("d", function(d){  //Here Attribute 'd' is used to describe the curve. Using Bezier Curve
                return "M" + d.x + "," + d.y
                    + "L" + d.x + "," + (d.y + d.parent.y) / 2
                    + " " + d.parent.x + "," + (d.y + d.parent.y) / 2
                    + " " + d.parent.x + "," + d.parent.y
            });
 console.log(nodes.descendants());
 console.log(nodes.descendants().slice(1));

 //Add Each Node as a Group - Ie, setting up a group
 var node = svg.selectAll(".node")
                   .data(nodes.descendants())
                   .enter()
                   .append("g")
                        .attr("class", "node node--leaf")
                    .attr("transform", function(d){
                            return "translate(" + d.x + "," + d.y + ")";
                    });

 //Add a circle to the node
 /*
 node.append("circle")
     .attr("r", 15)
     .attr("fill", "#fff")
     .attr("stroke", "steelblue")
     .attr("stroke-width", "3px");

node.append("div")
    .style("border","2px solid black");;

node.append("rect")
    .attr("height", 100)
    .attr("width", 225)
    .attr("fill", "none")
    .attr("stroke", "black")
    .style("stroke-width", 2)
    .attr("rx", 3);

                             */
node.append("div")
    .attr("class", "box");

 //Add Text to the node
 node.append("text")
     .attr("dy", ".35em")
     .attr("y", function(d){ return d.children ? -20 : 20;})
     .style("text-anchor", "middle")
     .text(function(d) {return d.data.name; });

}
})

error:

code updated:

A: Your problem is here:
var svg = d3.select("body")

You can't use document.body and apply styles to it, because it is protected by Locker Service, and you are reaching outside your component's container.
You need to provide a valid element within your own component:
<aura:component>
  <div aura:id="container">
  </div>
</aura:component>

And then hand that element to d3:
var svg = d3.select(component.find("container"))

You can also use a lightning:container, described in this answer.


text:
Q: Unable to open application module -> There is an error in invoking javac. A full JDK (not just JRE) is required We have the server which has Java 8 and Javac 8.
But while trying to access a module(developed using servlet) in the application it shows exception as "A full JDK (not just JRE) is required".
While using command...
[pdpadmin@HKDVLE805 /]$ javac -version
javac 1.8.0_144
[pdpadmin@HKDVLE805 /]$ java -version
java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)
[pdpadmin@HKDVLE805 /]$ which java
/PDP/current-jdk8/bin/java
[pdpadmin@HKDVLE805 /]$ which javac
/PDP/current-jdk8/bin/javac

Stack trace

[2018-08-17T14:24:20.709+0800] [Payara 4.1] [WARNING] [] [javax.enterprise.web.core] [tid: _ThreadID=27 _ThreadName=http-thread-pool::http-listener-1(3)] [timeMillis: 1534487060709] [levelValue: 900] [[
    Servlet.service() for servlet jsp threw exception
  org.apache.jasper.JasperException: PWC6345: There is an error in invoking javac.  A full JDK (not just JRE) is required
      at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:92)
      at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:378)
      at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:119)
      at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199JavaCompiler.java:208)
      at org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:384)
      at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453)
      at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:625)
      at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:375)
      at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
      at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
      at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1606)
      at org.apache.catalina.core.ApplicationDispatcher.doInvoke(ApplicationDispatcher.java:821)
      at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:685)
      at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:641)
      at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:573)
      at com.flextronics.servlet.admin.LoginManagement.processRequest(LoginManagement.java:169)
      at com.flextronics.servlet.admin.LoginManagement.handleRequest(LoginManagement.java:276)
      at org.springframework.web.context.support.HttpRequestHandlerServlet.service(HttpRequestHandlerServlet.java:67)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
      at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1606)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
      at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:654)
      at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:593)
      at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
      at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
      at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:466)
      at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:169)
      at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
      at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
      at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
      at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
      at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
      at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
      at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
      at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
      at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
      at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
      at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
      at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
      at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
      at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
      at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
      at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
      at java.lang.Thread.run(Thread.java:748)
  ]]

[2018-08-17T14:24:20.711+0800] [Payara 4.1] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=27 _ThreadName=http-thread-pool::http-listener-1(3)] [timeMillis: 1534487060711] [levelValue: 900] [[
  StandardWrapperValve[LoginManagement]: Servlet.service() for servlet LoginManagement threw exception
org.apache.jasper.JasperException: PWC6345: There is an error in invoking javac.  A full JDK (not just JRE) is required
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:92)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:378)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:119)
    at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199JavaCompiler.java:208)
    at org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:384)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453)
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:625)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:375)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1606)
    at org.apache.catalina.core.ApplicationDispatcher.doInvoke(ApplicationDispatcher.java:821)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:685)
    at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:641)
    at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:573)
    at com.flextronics.servlet.admin.LoginManagement.processRequest(LoginManagement.java:169)
    at com.flextronics.servlet.admin.LoginManagement.handleRequest(LoginManagement.java:276)
    at org.springframework.web.context.support.HttpRequestHandlerServlet.service(HttpRequestHandlerServlet.java:67)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1606)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:654)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:593)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:466)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:169)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
    at java.lang.Thread.run(Thread.java:748)
]]
Though Javac and Java is same, it is showing excepion. Can you please help me to understand why i am getting JasperException?

A: your application uses JSPs and to compile them, Payara needs to be running with a JDK and not only with JRE. Check which path is configured in Payara Server - normally it uses the default Java installation, but it can be configured in configured in glassfish/config/asenv.conf or in bin/asadmin. If in doubt, check which process is running if you start Payara Server.


text:
Q: set custom and current time clock I have an alarm activity and i want to set the clock to 12:00 if it's the first time the user enter to the activity but when an alarm is set and the user trying to change i want to set to the current time.
Here is where i set the clock:
private class TimePickerFragment2 extends DialogFragment implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final Calendar c     = Calendar.getInstance();
        int hour             = c.get(Calendar.HOUR_OF_DAY);
        int minute           = c.get(Calendar.MINUTE);

        TimePickerDialog tpd = new TimePickerDialog(ActivityAlarm.this, new TimePickerDialog.OnTimeSetListener()
        {

            int callCount = 0;   //To track number of calls to onTimeSet()
            @Override
            public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute)
            {
                 int containerElementId = 0;
                 String keySelected     = null;
                 if(callCount == 0)
                 {
                    switch (elementId) {
                        case R.id.start_time:
                            containerElementId = R.id.start_time_container;
                            keySelected = "start_time";
                            break;
                        case R.id.end_time:
                            containerElementId = R.id.end_time_container;
                            keySelected = "end_time";
                            break;
                        default:
                            break;
                    }
                     TextView timeContainer = (TextView)findViewById(containerElementId);
                     String correctedMinute = null;
                     if(selectedMinute == 10){
                         correctedMinute = "00";
                     }
                     if(selectedMinute < 10)
                     {
                         correctedMinute = "0"+selectedMinute;
                     }
                     else{
                         correctedMinute = Integer.toString(selectedMinute);
                     }
                     timeContainer.setText(selectedHour+":"+correctedMinute);
                     if(keySelected == "start_time"){
                         startTime = selectedHour+":"+correctedMinute;
                     }
                     else{
                         endTime = selectedHour+":"+correctedMinute;
                     }

                 }
                 callCount++;    // Incrementing call count.
            }
        }, hour, minute, DateFormat.is24HourFormat(ActivityAlarm.this));
        tpd.setTitle("Set Time");
        // Create a new instance of TimePickerDialog and return it
        return  tpd;
    }


text:
Q: How to save a ssh session's whole echo history over tty to a file? I ssh connect to a Linux server and want to save all the output from the server tty(console) to a log file, for later read/search.
For example, if I do echo "dafds" and then ls in bash, I want the log file to have the following content, or maybe something similar:
bash-4.4$ echo "dafds"
dafds
bash-4.4$ ls
README.md

After I leave this session, this file should have all the contents I saw over the terminal during this session.
Can I achieve this?
Should I do this on server side or on client side? Thanks.

A: You can also use tmux for this.
:capture-pane -S 100 save the lasts 100 lines in a buffer.
:save-buffer filename.txt write this buffer on a file.

A: You could use tee to read from stdin and stdout and redirect to a log file:
ssh user@server | tee ssh_session.out
Assuming that you know before making the connection that you want to log the session.


text:
Q: How can you transfer specific keys from one bundle to another? I am using the Activity as a controller and Fragments as views method to create my application.
Communications between them is implemented with Bundles, as in I pass a Bundle at the fragment creation which is then stored as the arguments of the fragment and the fragment updates itself using that bundle's information
I also created the method
public void update(Bundle data)

which is where the update happens and is called by onCreateView as well as the activity when it wishes to alter the state of the fragment.
Now since I wish (if there is a need to recreate the fragment) to save the current state of the fragment, I decided that the base method of update(bundle) should copy all values related to the current fragment to the arguments.
Unfortunatelly I can't find a method other than putAll to copy directly data from one bundle (the parameter of the update method) to another ( the arguments of the fragment), and I do not wish to use putall because the bundle may contain data that I do not wish to save in the bundle arguments, I only wish to copy values for the keys that already exist
is there any way to do this?


text:
Q: Prove that an affine variety is irreducible if and only its projective closure is irreducible. Prove that an affine variety $X \subseteq \mathbb{A^n}$ is irreducible if and only its projective closure $\bar X \subset \mathbb{P}^n$ is irreducible.
attempt: suppose by contradiction that $X$ is reducible. And that $\bar X$ is reducible.
Then $\bar X = A \cup B$, where $A,B$ are close sets.
Then $X = (X \cap A) \cup (X \cap B)$. But this tell tell us that because $X$ is irreducible, we have $X = X \cup A$ or $X = X \cup B$. Then we have $X =  X \cup A$ implies $X \subseteq A$ or $X = X \cup B$ implies $X \subseteq  B$, then since $A,B$ are close, then $A = \bar A$ and  $B = \bar B$, so we have $ \bar X \subseteq A$ or $\bar X \subseteq B$, which we have a contradiction, so we must have that $X$ is irreducible.
Conversely, let $\bar X$ be reducible, so that $\bar X = A \cup B$, then $X$ is contained in $A \cup B$.
could someone please help me? I don't know if this makes sense.  I need help on the converse part. Thank you.

A: Assume $\overline{X}$ is irreducible.  Let $A, B$ be two closed sets of $X$ whose union is $X$.  We want to show that either $A = X$ or $B = X$.  Since $X = A \cup B$, we have $\overline{X}  =\overline{A} \cup \overline{B}$.  Since $\overline{X}$ is irreducible, we have say, $\overline{X} = \overline{A}$.  The closure of $A$ as a subset of $X$ is $\overline{A} \cap X = \overline{X} \cap X = X$.  But $A$ is already closed in $X$, so $A = X$.


text:
Q: PaintComponent() not called despite setPreferredSize of JPanel I am trying to understand why the following short piece code does not work.
I understand that when there are no Layout or the size of the component is 0, the paint component method isn't called.
But this isn't the case here.
Can you explain why I can't set the background for this?
public class Login extends JPanel {

    private BufferedImage bgImage;

    public Login() {
        super();
        initImages();
        setLayout(new BorderLayout());

        setPreferredSize(new Dimension(600, 600));
        add(new JLabel("Hi"), BorderLayout.CENTER);
    }

    private void initImages() {
        try {
            bgImage = ImageIO.read(new File("images/login.jpg"));
            System.out.println("image loaded");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("image not loaded");
        }
    }

    @Override
    public void paintComponents(Graphics g) {
        super.paintComponents(g);
        g.drawImage(bgImage, 0, 0, null);
        System.out.println("repaint");
    }

    public static void createAndShowGui() {
        JFrame frame = new JFrame();
        Login login = new Login();
        frame.add(login, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

A: If you want this to work, then you will need to change...
@Override
public void paintComponents(Graphics g) {
    super.paintComponents(g);
    g.drawImage(bgImage, 0, 0, null);
    System.out.println("repaint");
}

to something more like...
@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(bgImage, 0, 0, this);
}

paintComponent is responsible for painting the "bottom" layer of the component, paintComponents is responsible for painting the children


text:
Q: Simple Read then Write .bmp File C code I am trying to do a simple read of a .bmp file, and then output that same .bmp file. Right now, it only works if the width and height are the exact same. That's a good indicator of what my problem is, but I can't seem to figure it out. I'm looking for any ideas or suggestions y'all may have. There are other questions about this, but they seem not to be exactly what I'm looking for. However, my output when the width and height are different is similar to the output that is shown here Read/Write SImple BMP Image C++ - basically it's skewed, incomplete, and repetitive, not the actual image.
Here is the code where I read in the .bmp file:
    bool LoadBmp(const char *filepath)
    {
        FILE *f = fopen(filepath, "rb");
        if (f)
        {
          Bwidth = 0;
          Bheight = 0;
          pixels = NULL;
          unsigned char info[54] = {0};
          fread(info, sizeof(unsigned char), 54, f);
          Bwidth = *(unsigned int *)&info[18];
          Bheight = *(unsigned int *)&info[22];
          unsigned int size = Bwidth * Bheight * 3; // ((((Bwidth * Bheight) + 31) & ~31) / 8) * Bheight;
          pixels = malloc(size);
          fread(pixels, sizeof(unsigned char), size, f);
          fclose(f);
          return true;
       }
       return false;
   }

Note that I was unsure whether to create size how I do below (Bwidth * Bheight * 3) or use what is commented out. Also note that 'Bwidth' and 'Bheight' are declared as unsigned int, whereas 'pixels' is defined as unsigned char*. Additionally, I purposely am not using a struct to store .bmp file data.
Here is the code that I use to write the .bmp file that I just loaded:
    static bool WriteBMP(int x, int y, unsigned char *bmp, char * name)
    {
      const unsigned char bmphdr[54] = {66, 77, 255, 255, 255, 255, 0, 0, 0, 0, 54, 4, 0, 0, 40, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 1, 0, 8, 0, 0, 0, 0, 0, 255, 255, 255, 255, 196, 14, 0, 0, 196, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
      unsigned char hdr[1078];
      int i, j, c, xcorr, diff;
      FILE *f;

      xcorr = (x+3) >> 2 << 2;  // BMPs have to be a multiple of 4 pixels wide.
      diff = xcorr - x;

      for (i = 0; i < 54; i++) hdr[i] = bmphdr[i];
      *((int*)(&hdr[18])) = xcorr;
      *((int*)(&hdr[22])) = y;
      *((int*)(&hdr[34])) = xcorr*y;
      *((int*)(&hdr[2])) = xcorr*y + 1078;
      for (i = 0; i < 256; i++) {
        j = i*4 + 54;
        hdr[j+0] = i;  // blue
        hdr[j+1] = i;  // green
        hdr[j+2] = i;  // red
        hdr[j+3] = 0;  // dummy
      }

      f = fopen(name, "wb");
      if (f) {
          assert(f != NULL);
          c = fwrite(hdr, 1, 1078, f);
          assert(c == 1078);
          if (diff == 0) {
            c = fwrite(bmp, 1, x*y, f);
            assert(c == x*y);
          } else {
            *((int*)(&hdr[0])) = 0;  // need up to three zero bytes
            for (j = 0; j < y; j++) {
              c = fwrite(&bmp[j * x], 1, x, f);
              assert(c == x);
              c = fwrite(hdr, 1, diff, f);
              assert(c == diff);
            }
          }
          fclose(f);
          return true;
      }
      else return false;
    }

Thanks in advance for your help. I appreciate your time!


text:
Q: NgRoute does not work TemplateUrl I really don`t know why my routes does not work. Look:
I have a simple dir like:
build/
.../app/
....../app.js
.../templates/
....../dashboard/
........./dashboard.html

When i use:
 angular.module("Proposal.Dashboard").config(configRouter);

     function configRouter($routeProvider) {
         $routeProvider.when("/", {
             controller: "DashboardController",
             templateUrl: "../templates/dashboard/dashboard.html",
             controllerAs: "dashboardVm"
         })
     }

It should works. But does not, somebody has an ideia?


text:
Q: Finding a matrix that meets conditions of a nullspace Construct a non-zero matrix $A$ with the required property or explain why that is impossible:
a) The range of $A$ contains $(1, −1, −1)^T$ and $(−1, 1, 2)^T$, and nullspace of $A$ is $\{(s−t, s+t,s)^T|s, t \in R\}$.
I've been pondering this for a bit, and if I understand it correctly, this is saying the following:
$\begin{bmatrix}a & 1 &-1\\b & -1 & 1\\c & -1 & 2 \end{bmatrix}$$  \begin{bmatrix} s+t \\ s-t \\s \end{bmatrix}= \begin{bmatrix} 0\\ 0 \\0 \end{bmatrix}$
This seems like a rather cumbersome system to solve.

A: In short, this is impossible, since it is asking you to construct a matrix where nullity is $2$ and range is at least $2$. Then, this implies $n=3\geq 4$ from rank-nullity theorem. A contradiction.
Moreover, we know range is a vector space, so range must contain $2*(1,-1,-1)+(-1,1,2)=(1,-1,0)$. Now the nullspace also contains $(1,-1,0)$, by setting $s=0$ and $t=-1$. However, the nullspace and range of a linear transformation should not contain any non-trivial vector in its intersection.


text:
Q: Emacs suspends right after starting in bash (Possibly) important info:
Ubuntu version - 16.04 LTS
GNU Emacs version - 24.5.1
GNU bash version - 4.3.42(1)-release
I'm trying to edit my apache2.conf file in /etc/apache2/, but using
sudo emacs -mm apache2.conf &
to start Emacs doesn't work. In particular, it doesn't ask me for the root password, and the process just suspends immediately after starting. bg doesn't work either because the process just suspends again.
edit:
When starting Emacs as a foreground process instead, I'm asked for the root password, and the process doesn't suspend.
What might be causing this behavior?

A: This is because sudo meanwhile not works for many GUI based applications, use gksudo instead which you will find in the package gksu. So example:
sudo apt-get install gksu
gksudo emacs -mm apache2.conf &

Happy hacking.


text:
Q: Angularjs up/down spin button not working In IE11 In Chrome it's working fine but same functionality not working in IE11. My html code is
<div ng-switch="row.type">
 <input ng-switch-when="Increment" type="number" min="{{row.minVal}}" max="{{row.maxVal}}" step="{{row.step}}" ng-model="dynamicVal[row.name]" required class="form-control">
 <select ng-switch-when="LookUp" class="form-control" ng-model="dynamicVal[row.name]" ng-change="selectedLookUp(row.name, row.isAjax)" >
   <option ng-repeat="lookup in row.lookUpValues" value="{{lookup.id}}">{{lookup.name}}</option>
  </select>
<input ng-switch-default type="number" min="{{row.minVal}}" max="{{row.maxVal}}" step="{{row.step}}" ng-model="dynamicVal[row.name]" required class="form-control">
 </div>

and CSS is this
input[type=number]::-webkit-inner-spin-button,

input[type=number]::-webkit-outer-spin-button {

   opacity: 1;
}

I am new to CSS.

A: It's meant to only work in Chrome. There is no way to do what you are asking. Quoting MSDN's documentation on ::-webkit-inner-spin-button:

Non-standard
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

And

Specifications
NOT part of any specification. This is a proprietary pseudo-element specific to WebKit/Blink.

You can see it's clearly only supported by Webkit based browsers like Chrome, Opera and Safari (Internet Explorer isn't Webkit based):


text:
Q: Django: @property decorator on to emulate .queryset property I have a view which has dynamic queryset. But to use DjangoModelPermissions I need .queryset attribute. So I tried to use @property decorator on def queryset(self): but it does not work. Below is a code snippet.
@property
def queryset(self):
    return self.module.none()

But DjangoModelPermissions still complains about .queryset not being available. How to fix it?

A: Everything works fine. The self.module was not initialized and returned none.


text:
Q: Составная переменная в ternary j2-шаблона ansible Небольшой скрипт для сбора информации о серверах в cvs-файл:
- name: collect info about servers
  hosts: webservers
  tasks:
    - name: template list
      template:
        src="servers_report.j2"
        dest="~/ansible/webservers/servers_report.csv"
      connection: local

Простой шаблон servers_report.j2 с фильтром ternary:
hostname;provider;monitoring url;
{% for item in play_hosts %}
{{ item }};{{ hostvars[item].provider }};{{ hostvars[item].monitoring | ternary("https://{{ item }}/monitoring_url/", '') }};
{% endfor %}

Список параметров хостов в файле hosts_production (типовой фрагмент):
server1 provider="provider1" monitoring=True
server2 provider="provider2" monitoring=False

И... не работает: {{ item }} не считается за переменную.
hostname;provider;monitoring url;
server1;provider1;https://{{ item }}/monitoring_url/;
server2;provider2;;

Простые варианты типа ternary ('1', '2') работают без проблем, вопросы появляются именно в таких случаях посложнее, когда приходится угадывать, как расположить кавычки.

A: Для простоты можно считать, что внутри {{ и }} код на Python.
{{ hostvars[item].monitoring | ternary('https://'+item+'/monitoring_url/', '') }}

ternary – функция, в качестве одного из параметров ей нужно передать строку, чтобы получить результирующую строку, сложим строки 'https://' + item + '/monitoring_url/'.


text:
Q: Does Firestore support multitenancy? Does Firestore have any support for a multi-tenant app? I am creating a service which will have multiple clients and need to be able to separate each client's data completely from every other client.

A: Firestore in Native mode has no (built-in) support for multitenancy.
Firestore in Datastore mode has support for multitenancy via namespaces. However, Firestore in Datastore mode loses the real-time updates feature, which is a highly desirable feature for many developers/projects.
One workaround for this limitation is to use a (collection/document) hierarchy in the Native-mode Firestore that looks something like this:

*

*tenants (collection)

*

*Tenant-01 (document representing a particular tenant; can contain basic details like name etc.)

*

*users (sub-collection)

*assets (sub-collection)

*locations (sub-collection)

*Tenant-02

*

*users (sub-collection)

*assets (sub-collection)

*locations (sub-collection)

However, there still remains the limitation that you cannot know the resource usage on a per-tenant basis. This matters particularly when there's a noisy neighbour: a single tenant that is using far more resources than the average. As the service provider your total bill is rising, but there's no easy way to know which client (tenant) is causing the higher costs.
See also:

*

*Datastore Overview

*Choosing between Native mode and Datastore mode


text:
Q: task scheduler is displaying an error "The specified query is invalid" I am running Windows 10.
I'm trying to run a backup job (C:\WINDOWS\system32\robocopy.exe) using Task Scheduler. But I was getting issues. To figure out what was going on, I turned on the history log.  Unfortunately since doing that, every time I click the History tab I get the following error:

Dialog Title: "Query Error"
Dialog Message: "One or more logs in the query have errors."
The table in the dialog: "Microsoft-Windows-Task-Scheduler/Operational | The specified query is invalid"
"The events displayed are partial results."

Nothing appears in the History pane, so I cannot debug either problem.  Does anyone know what is going on?

I am having the exact same error as in

https://www.experts-exchange.com/questions/27676176/Query-Error-In-Microsoft-Task-Scheduler.html

The answer is at

http://www.minasi.com/forum/topic.asp?TOPIC_ID=27906

The answer site (www.minasi.com) is apparently moved and did not retain the answer so cannot try the fix that solved his problem.

A: Please check if you have single quotes (apostrophes) in the task name. It is known that the apostrophe in the task name breaks task history. To remove them you can try following batch file (it exports task to the xml file, imports it with the new name and removes the old task):
@set "tn=my PC's task"
@if not "%tn%"=="%tn:'=%" echo renaming "%tn%" ==^> "%tn:'=%" && ^
schtasks.exe /query /tn "%tn%" /xml>"%temp%\%tn:\=_%.xml" && ^
schtasks.exe /create /tn "%tn:'=%" /xml "%temp%\%tn:\=_%.xml" && ^
schtasks.exe /delete /tn "%tn%" /f && del /q /f "%temp%\%tn:\=_%.xml"


text:
Q: Subsetting and transposing table iterating in R I have this table (inputdf):

Number
Value

1
0.2

1
0.3

1
0.4

2
0.2

2
0.7

3
0.1

and I want to obtain this (outputdf):

Number1
Number2
Number3

0.2
0.2
0.1

0.3
0.7
NA

0.4
NA
NA

I have tried it by iterating with a for loop through the numbers in column 1, then subsetting the dataframe by that number but I have troubles to append the result to an output dataframe:
inputdf <- read.table("input.txt", sep="\t", header = TRUE)
outputdf <- data.frame()

i=1
total=3 ###user has to modify it

for(i in seq(1:total)) {
  cat("Collecting values for number", i, "\n")
  values <- subset(input, Number == i, select=c(Value))
  cbind(outputdf, NewColumn= values, )
  names(outputdf)[names(outputdf) == "NewColumn"] <- paste0("Number", i)
}

Any help or hint will be very wellcomed. Thanks in advance!

A: In the tidyverse, you can create an id for each element of the groups and then use tidyr::pivot_wider:
library(tidyverse)
dat %>%
  group_by(Number) %>%
  mutate(id = row_number()) %>%
  pivot_wider(names_from = Number, names_prefix = "Number", values_from = "Value")

# A tibble: 3 × 4
      n Number1 Number2 Number3
  <int>   <dbl>   <dbl>   <dbl>
1     1     0.2     0.2     0.1
2     2     0.3     0.7    NA
3     3     0.4    NA      NA

in base R, same idea. Create the id column and then reshape to wide:
transform(dat, id = with(dat, ave(rep(1, nrow(dat)), Number, FUN = seq_along))) |>
  reshape(direction = "wide", timevar = "Number")


text:
Q: Avoid function overload explosion Does TypeScript provide a way to avoid this sort of method overloading explosion and, in doing so, provide type safety to an unlimited number of varargs?
type Operator<FROM, TO> = (source: Stream<FROM>) => Stream<TO>

class Stream<V> {
    // ...

    pipe<A>(operator: Operator<VALUE, A>): Stream<A>
    pipe<A, B>(op1: Operator<VALUE, A>, op2: Operator<A, B>): Stream<B>
    pipe<A, B, C>(op1: Operator<VALUE, A>, op2: Operator<A, B>, op3: Operator<B, C>): Stream<C>
    pipe<A, B, C, D>(op1: Operator<VALUE, A>, op2: Operator<A, B>, op3: Operator<B, C>, op4: Operator<C, D>): Stream<D>
    pipe<A, B, C, D, E>(op1: Operator<VALUE, A>, op2: Operator<A, B>, op3: Operator<B, C>, op4: Operator<C, D>, op5: Operator<D, E>): Stream<E>
    pipe<A, B, C, D, E, F>(op1: Operator<VALUE, A>, op2: Operator<A, B>, op3: Operator<B, C>, op4: Operator<C, D>, op5: Operator<D, E>, op6: Operator<E, F>): Stream<F>
    pipe<A, B, C, D, E, F, G>(op1: Operator<VALUE, A>, op2: Operator<A, B>, op3: Operator<B, C>, op4: Operator<C, D>, op5: Operator<D, E>, op6: Operator<E, F>, op7: Operator<F, G>): Stream<G>
    pipe<A, B, C, D, E, F, G, H>(op1: Operator<VALUE, A>, op2: Operator<A, B>, op3: Operator<B, C>, op4: Operator<C, D>, op5: Operator<D, E>, op6: Operator<E, F>, op7: Operator<F, G>, op8: Operator<G, H>): Stream<H>
    pipe<A, B, C, D, E, F, G, H, I>(op1: Operator<VALUE, A>, op2: Operator<A, B>, op3: Operator<B, C>, op4: Operator<C, D>, op5: Operator<D, E>, op6: Operator<E, F>, op7: Operator<F, G>, op8: Operator<G, H>, op9: Operator<H, I>): Stream<I>
    pipe<A, B, C, D, E, F, G, H, I, J>(op1: Operator<VALUE, A>, op2: Operator<A, B>, op3: Operator<B, C>, op4: Operator<C, D>, op5: Operator<D, E>, op6: Operator<E, F>, op7: Operator<F, G>, op8: Operator<G, H>, op9: Operator<H, I>, op10: Operator<I, J>): Stream<J>
    pipe<A, B, C, D, E, F, G, H, I, J, K>(op1: Operator<VALUE, A>, op2: Operator<A, B>, op3: Operator<B, C>, op4: Operator<C, D>, op5: Operator<D, E>, op6: Operator<E, F>, op7: Operator<F, G>, op8: Operator<G, H>, op9: Operator<H, I>, op10: Operator<I, J>, ...restOps: Operator<unknown, unknown>[]): Stream<K>

    pipe<TO_VALUE>(operator: Operator<VALUE, unknown>, ...restOperators: Operator<unknown, unknown>[]): Stream<TO_VALUE> {
        return restOperators.reduce((stream, operator) => operator(stream), this as Stream<unknown>) as Stream<TO_VALUE>
    }
}

Note that each Operator's output type is the next Operator's input type.

A: It's possible.
Here is a working example which requires TypeScript 4 tuple types. The idea is to use an array generic T to keep track of each consecutive type to make sure the operators agree.
I based this answer off of this comment by @jcalz.
type Operator<FROM, TO> = (source: Stream<FROM>) => Stream<TO>

type Prev<T extends any[], K, D> = K extends keyof [ D, ...T ] ? [ D, ...T ][K] : never;
type Operators<VALUE, T extends any[]> = {
    [K in keyof T]: Operator<Prev<T, K, VALUE>, T[K]>
};
type PipeResult<T extends any[]> = T extends [ ...infer _, infer U ] ? Stream<U> : never;

class Stream<VALUE> {
    x?: VALUE; // Needed to make sure Stream<X> doesn't always extend Stream<Y>.

    pipe<T extends any[]>(...operators: Operators<VALUE, T>): PipeResult<T> {
        return operators.reduce<Stream<unknown>>((stream, operator) => operator(stream), this) as PipeResult<T>;
    }
}

Testing:
const OpA: Operator<number, 'hi'> = null as any;
const OpB: Operator<string, 'hello'> = null as any;
const OpC: Operator<string, Date> = null as any;

const OpD: Operator<1521, string> = null as any;
const OpE: Operator<5, 6> = null as any;
const OpF: Operator<6, 7> = null as any;

const NumberStream = new Stream<number>();

// x0: Stream<Date>
const x0 = NumberStream.pipe(OpA, OpB, OpC);
// x1: Stream<"hello">
const x1 = NumberStream.pipe(
    OpA, OpB, OpB, OpB, OpB, OpB, OpB, OpB, OpB, OpB, OpB,
    OpB, OpB, OpB, OpB, OpB, OpB, OpB, OpB, OpB, OpB, OpB,
    OpB, OpB, OpB, OpB, OpB, OpB, OpB, OpB, OpB, OpB, OpB);

// Error on arg 3.
const x2 = NumberStream.pipe(OpA, OpC, OpC);
// Error on arg 1.
const x3 = NumberStream.pipe(OpD, OpE, OpF);

Playground Link

Old bad answer: Playground Link


text:
Q: The difference between ".//*" and "//*" XPath? The difference between:
1: ".//*"
and
2: "//*"
XPath in the following:
the first one means "from the current context i.e from this place/point".
Do I get it right?
What is the sense in such XPath: ".//a[contains(., 'some text')]"?

A: While using Selenium you can find elements using WebDriver right?
Java example:
WebElement element = driver.findElement(...)
But you can also use element variable to look for elements in the context of this element. It will not search the whole DOM, it will limit the search to element.
Java example:
WebElement nestedElement = element.findElement(...);

That's where .// becomes handy. Because it tells xpath to use current context.
This will search in reduced context:
element.findElement(By.xpath(".//div"));

This will search through DOM, regardless of using element
element.findElement(By.xpath("//div"));


text:
Q: Which programming language to use when interacting with shell? I want to write a program that uses shell commands to make changes to audio such as:
pactl set-sink-volume 0 +10%
As I need it during my podcast I want to be able to quickly interact with it via GUI and also use the keyboard to activate functions. Which language would you suggest for programming it? My first guess would be C++ and QT but maybe there are better options.

A: This question may be regarded as opinion-based, because most higher-level programming languages have an interface to the system shell, and the decision is mainly a matter of preference (and only to some part of "the right tool for the right job"). However, here are some hints from my point of view:

*

*If the logic is simple (mainly the calls with fixed or passed parameters, no fancy calculations), use shell scripts. Easy to start with, to implement and to maintain.

*For more advanced logic, you'll be better off with a common scripting language like Python, Lua, even Perl if you know how to use it.

*C++/Qt makes sense if you want a sophisticated UI experience, but here also Python + PyQt would be an alternative. Altogether compiler languages add some overhead to the development cycle, but provide better runtime performance, which may be an advantage if the application is consuming much processor time and runs permanently.


text:
Q: Codeigniter Eloquent superclass I followed this tutorial and created a user model. I would like to create a superclass so that every model has the same timestamp value and a scope method. Is creating a superclass the correct method to do this? How do I extend a custom Eloquent model in Codeigniter?
I have the following idea, but i'm stuck on the custom model extends part.
CustomModel.php:
use \Illuminate\Database\Eloquent\Model as Eloquent;

class CustomModel extends Eloquent {
    protected function getDateFormat() {
        return 'U';
    }
    protected function scopeUser($query,$userID) {
        return $query->where('user_id','=',$userID);
    }
}

User.php:
class User extends CustomModel {

}

I thought about adding a manual include inside the User.php file, but I don't think it is a nice solution. I also prefer not to autoload the CustomModel class.

A: You can create core model with extending working model from that one. Create MY_Model in core directory with specific functionality you want to use in other models:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

use \Illuminate\Database\Eloquent\Model as Eloquent;

class MY_Model extends Eloquent {
    protected function getDateFormat() {
        return 'U';
    }
    protected function scopeUser($query,$userID) {
        return $query->where('user_id','=',$userID)
    }
}

Than extend any model from models directory from MY_Model.


text:
Q: Is there a DocBook reader for following in-progress documents? I have docbook2pdf installed, but it seems a bit wasteful to always need to delete and re-create the .PDF file when the source changes. Is there a good program for styling and viewing them natively?

A: Once I created a huge technical specification and used XMLMind for editing the source file in DocBook format. For conversion to Pdf used some java tool.
source


text:
Q: LaTeX - Reference Help I have some problems, when I try to use the command \ref{}.
When I compile my LaTeX code, It will not show me any number at all in the final pdf-document eventhough that I am using the correct command \ref{fig:statestik}.
I have my picture:
\begin{figure}[H]
\centering
\includegraphics[scale=0.6]{../../../Billeder/Horeskader/statestik.jpg}
\caption{This is my caption.}
\label{fig:statestik}
\end{figure}

I should just say, that i'm writing in subiles, and load it all in a main file.

A: run this example twice and everything will be fine:
\documentclass{article}
\usepackage[demo]{graphicx}
\begin{document}

\begin{figure}
\centering
\includegraphics[scale=0.6]{../../../Billeder/Horeskader/statestik.jpg}
\caption{This is my caption.}
\label{fig:statestik}
\end{figure}

Figure~\ref{fig:statestik} is a nice figure

\end{document}