text:
Q: How to compile lexical environments into objects in JavaScript compiler? I am working on a custom language and want to now support lexical environments (closures). I am asking for help in how this would look in JavaScript to keep it easier and more applicable to others.
Basically, say you have this in a file.
let a = 10
let b = 20

function doFoo() {
  let x = 300
  let y = 400
  let z = doBar(x, y)
  return a * z + b * z

  function doBar(m, n) {
    return m * a + n * b
  }
}

Keeping it simple (not thinking about how compilers can optimize away or remove simple expressions), what do the objects look like for lexical environments (like in JSON), and how do the lexical environments get used at runtime generally?
It seems to me that you would end up like this:
let a = {
  vars: [
    {
      varname: 'a',
      value: 10
    },
    {
      varname: 'b',
      value: 20
    }
  ],
  funcs: ['doFoo']
}
let b = {
  parent: a,
  vars: [
    {
      varname: 'x',
      value: 300
    },
    {
      varname: 'y',
      value: 400
    },
    {
      varname: 'z',
      value: undefined
    }
  ],
  funcs: ['doBar']
}
let c = {
  parent: b,
  vars: [
    {
      varname: 'm',
      value: undefined
    },
    {
      varname: 'n',
      value: undefined
    }
  ]
}
let environments = [a, b, c, /* and tons more */]

Then when you actually invoke the function doFoo, it would serialize the data at that instant or something like that.
run(script)

// 1. link a = 10, b = 20
// 2. call doFoo
//   3. create a new object, link it to the lexical environment.
//   4. repeat

This "create a new object" part is where I'm lost. We must create a new "scope" or "context" for every invocation of the function correct? And how does it relate to that environments array I created?
It seems that a scope is an instance of an environment, where the variables of the environment are filled in right before they are used. Then an environment just says what variables there are.
But this seems like a performance problem, creating a new scope with potentially dozens of variables to serialize all at once. So they must update the scopes as the variables change. How does this generally look or work? What objects do we have, how are they linked together, and when/how do they get updated?

A: First we want to understand the difference between scopes and environments in theory.
Environments are the bindings that associate variables to values need to be stored somewhere. You can think of it like a map where the keys are variable names and the values. Updating values is as simple as changing the value that the key points to.
A scope defines a region in code where a name maps to a value. Multiple scopes enable the same name to refer to different things in different contexts.
So as you mentioned, scopes are essentially environments. But what happens when we have the following:
function defineVariable() {
    let a = "some variable";
}

defineVariable();
console.log(a); // undefined!

Here we have a function, and it contains it's own scope. This means that any variables defined after the opening brace { get deleted after the closing brace }.
So in this above snippet we'd do the following:

*

*call function defineVariable

*create scope

*create and assign variable a

*close scope
& delete all variables in previous scope: so delete a

*log a to console (a is undefined, it was deleted so we log undefined)

So now we know that scopes fence variables between their braces {}. However we also have the case of shadowing. For example:
let shadowed = 0;

function printShadowed() {
  let shadowed = 1;
  console.log(shadowed); // 1
}

printShadowed(); // prints 1
console.log(shadowed); // 0

Here we do something interesting, we declare a new variable with the same name as an existing variable. This is called shadowing. It let's us create new variables that are entirely separate from their parenting environment. To better understand this we can talk about the difference between local and global variables:
let global = 10;

function doMath() {
  let local = 15;
  console.log(global + local); // 25
}

doMath(); // prints 15
console.log(local); // undefined, `local` is local to the `doMath` scope

The idea is that a scope has access to all of it's parents scopes, but doesn't have access to any children scopes.
To recap an environment is a map of variable names to their respective values. A program is a tree of different environments. A scope is a branch of those environments which are accessible.  When we declare variables with the same name as a variable in it's parent environment it's called shadowing. To picture this visually, the following code is equivalent to:
let global = 10;

function doMath() {
  let local = 15;
  console.log(global + local); // 25
  console.log(a); // undefined, a is not in scope
}

function other() {
   let a = "...";
}

doMath(); // prints 15

Where the environments circled in red are the scope of the doMath function.
Now in practice this can be implemented in a variety of ways. The simplest is the idea of the stack.
let global = 10;
// environments = [ { "global": 10 } ]

function doMath() {
   let local  = 15;
   // environments = [ { "global": 10 }, { "local": 15 } ]

   console.log(global + local); // 25
   // we walk the list from back to front until we find
   // a map that contains the requested variable. So:
   //
   // for `local` we first check the last map, we find `local`
   // in that map, so our value is 15
   //
   // for `global` we first check the last map, we don't find
   // `global`, so we move up the list, we check the second last
   // map (here it's the first) and we find `global` in that map,
   // our value is 10
}
// exiting function scope
// environments = [ { "global": 10 } ]

doMath();

EDIT: I realized that I completely forgot to go over the closures part. So take the following example:
let x = "global";
function outer() {
  let x = "inner";
  function inner() {
    console.log(x);
  }
  return inner;
}
outer()();

In a stack based scope implementation this will print "global" when theoretically we would expect it to print "local". Now this is why I mentioned that scope creates a tree like structure. However with closures, we need to capture that scope in some way. What I mean by this is that we want the inner function to capture it's scope, thus from it's point of view x with the value of "local" should take precedence.
Let's go over what I mean by capturing and storing scope: So instead of representing our environments as a stack we will instead represent them as a tree. We can then keep track of the branch which we are currently on by pointing to that tree. By then climbing the tree we get all of the info needed for our standard stack implementation above. However, if we can see that a user has defined a closure, that closure is going to hold two things. The code which make's up the closure's body, and a pointer to where the closure's scope exists. So to use that new logic on the above example:
let x = "global";
// { "x": "global", children: [] }

function outer() {
  let x = "inner";
  // { "x": "global", children: [ { "x": "local", children: [] } ] }
  function inner() {
    console.log(x);
  }
  // inner is a closure, it stores the code within it
  // and a pointer to to the current scope that it was
  // instantiated in
  return inner;
}
// we are now pointing to the scope on the top of the tree, but notice how we
// don't delete the "local" x scope
// { "x": "global", children: [ { "x": "local", children: [] } ] }
outer()();
// good thing we didn't, because this function returned a function that
// needed it about when that local x should be deleted is a headache for
// our garbage collector

Now another case that you mentioned was what if we change the value of local x? Well that's why we create a pointer to the scope of the local x. So any changes to local x will be reflected when we call it. This also has the added bonus of avoiding unnecessary copying.
About memory, that's where things get a little hairy. Ideally we don't want our GC to have to work harder than it needs to. Many languages, like lua, will only store scope if there's a closure. What this means is that instead of storing a perfect tree of environments, it will only store a branch if it's captured by a closure, or is currently in use.
This was a lot, and it may be more helpful to look at other resources as well. The book that you linked is great as it goes into a lot of detail about language implementation in general. Also the links that @Bergi posted in his comments to this question could also be helpful. If I've missed something myself, or am wrong in any part of this answer, constructive criticism is always helpful :)


text:
Q: How to introduce delay in POSTGRESQL 9.3 replication? I have master slave replication setup. How I can force some delay in replication ?
Is there a setting that I can use ?
Thanks !

A: Not in 9.3.
In 9.4 you can use min_recovery_apply_delay. See this blog post.
In 9.3, if you have WAL-archive based replication (no streaming) you could archive the WAL to one location, and only move it to a location readable by the standby after a delay. You can't do it with streaming in 9.3.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ggplot2 stacked barchart with groups I want to create a stacked barchart with two stacked columns in each time period.
I was able to achieve it with the code bellow, but the solution has some limitations. Is there other way than using paste0 for x axis? Can I somehow group data by var4 to achieve it?
dd <- data.frame(date = rep(2001:2005,4),
                 var2=rep(c("a","b","c","d"),each=5),
                 var3=rnorm(20,5),
                 var4=rep(c(1,2),each=10))

ggplot(data = dd, aes(x=paste0(date, "/",var4), y=var3, fill=var2)) +
  geom_bar(stat="identity", position="stack")

A: Here are two options, neither of which is optimal.  The first one uses arithmetic instead of paste, but really is fairly similar to what you are already doing:
ggplot(data = dd, aes(x=date + var4/2 - .75, y=var3, fill=var2)) +
  geom_bar(stat="identity", position="stack")

The second one uses facets to generate the groups.  This is generic since you can change how many groups var4 has and this will update automatically.  It is however a total hack:
ggplot(data = dd, aes(x=date, y=var3, fill=var2)) +
  geom_bar(stat="identity", position="stack") +
  facet_wrap(~ date + var4, scales="free_x", nrow=1) +
  scale_x_continuous(breaks=dd$date)


text:
Q: Animating frame Images with ease effect on iPad Let me show you example (360 Deg 3D Object Rotator): Demo: http://activeden.net/item/interactive-renders-360-deg-3d-object-rotator/39718?ref=mixDesign
As you see, there is a camera 3D rotating on mouse event. Actually, it is a collection of images (frames) animating frame by frame depending on mouse event.
I want to implement this animation with objective - c using swipe gesture (or maybe I should use another gesture?). So that I can make rotation by my finger, to the left, to the right (I want animation with smooth ease effect, depending on swipe speed velocity).
Note: I have ready images for each frame.

Sample codes, online tutorials doing this will really help me.
! Should I use some external graphics library, in order to keep performance? I have hundreds of images (PNG), each with size of 300kb
Thank you in advance, I really need your help!

A: Maybe it will be easier to go with touchesBegan:, touchesMoved:, and touchesEnded: here? This will allow you to react to velocity and direction changes very fast.
Update: example can be found here.

A: I don't think you should use swipe gesture here. I recommend you LongPressGesture with short minimumPressDuration.
Let me show example code:
longPress = [ [UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGesture:)]
longPress.delegate = self;
longPress.minimumPressDuration = 0.05;
[viewWithImage addGestureRecognizer:longPress];

float startX;
float displacement = 0;
-(IBAction)handleLongPressGesture:(UILongPressGestureRecognizer *)sender
{

float nowX;
    if ( sender.state == UIGestureRecognizerStateBegan )
    {
        startX = [sender locationInView:viewWithImage].x;
    }
    if ( sender.state == UIGestureRecognizerStateEnded || sender.state == UIGestureRecognizerStateCancelled)
    {
       ... do something at end ...
    }
nowX = [sender locationInView:mainWidgetView].x;
displacement = nowX - startX;

  // set right rotation with displacement value
  [self rotateImageWith:displacement];
}


text:
Q: swift Pod install error Analyzing dependencies
[!] Unable to satisfy the following requirements:

*

*SwiftyJSON (fromhttps://github.com/SwiftyJSON/SwiftyJSON.git) required by Podfile

*SwiftyJSON (fromhttps://github.com/SwiftyJSON/SwiftyJSON.git) required by Podfile

*SwiftyJSON (fromhttps://github.com/SwiftyJSON/SwiftyJSON.git) required by Podfile

*SwiftyJSON (fromhttps://github.com/SwiftyJSON/SwiftyJSON.git) required by Podfile

*SwiftyJSON (fromhttps://github.com/SwiftyJSON/SwiftyJSON.git) required by Podfile

*SwiftyJSON (= 2.3.2) required by Podfile.lock
None of your spec sources contain a spec satisfying the dependencies:         SwiftyJSON (fromhttps://github.com/SwiftyJSON/SwiftyJSON.git),   SwiftyJSON (= 2.3.2).
You have either:

*

*out-of-date source repos which you can update with pod repo update.

*mistyped the name or version.

*not added the source repo that hosts the Podspec to your Podfile.

Note: as of CocoaPods 1.0, pod repo update does not happen on pod  install by default.
pod update:
TEMPLATE END

[!] Oh no, an error occurred.

Search for existing GitHub issues similar to yours:
https://github.com/CocoaPods/CocoaPods/search?q=File+exists+%40+dir_s_mkdir+-+%2FUsers%2Fusers%2FMyApp-ios%2FPods%2FTarget+Support+Files%2FAlamofire-iOS8.0&type=Issues

If none exists, create a ticket, with the template displayed above, on:
https://github.com/CocoaPods/CocoaPods/issues/new

Be sure to first read the contributing guide for details on how to properly submit a ticket:

https://github.com/CocoaPods/CocoaPods/blob/master/CONTRIBUTING.md
Don't forget to anonymize any private data!

Looking for related issues on cocoapods/cocoapods...
Found no similar issues. To create a new issue, please visit:
https://github.com/cocoapods/cocoapods/issues/new

podfile:
Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'
pod 'Alamofire', '~> 3.4'
pod 'HanekeSwift'
pod 'Google/Analytics', '~> 1.0.0'
pod 'MBProgressHUD', '~> 0.9.1'

target 'MyApp' do
    pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'
    pod 'Alamofire', '~> 3.4'
end

target 'MyApp Watch app Extension' do
    platform :watchos, '3.0'
    pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'
    pod 'Alamofire', '~> 3.4'
end

target 'MyAppTests' do

end


text:
Q: Show that the set $A = \{n \alpha \pmod 1\mid n ∈ \mathbb Z\}$ is countably infinite, where $\alpha$ is an irrational number. I'm trying to understand a solution to a counting problem. I would like to receive detailed explanations to the different drawn conclusions in the solution, thank you.
Q: Given $x ∈ R $, let $y = x \pmod 1$, where $y ∈ [0,1)$, such that $x = n + y$ for some $n ∈ Z$. Now let $\alpha$ be an irrational number, which finally gives us the set $A = [n \alpha (mod 1)| n ∈ Z]$. Show that the set A is countably infinite.
S: Note that $A < B = [n \alpha - k| n,k ∈ Z]$. Now in the solution it is apparently obvious that the set $B$ is countable since it is a countable union of countable set, however I do not see that. If $B$ is a union what would each countable set $B_i$ look like?
Continuing the solution says: if we can show that $A$ contains infinitely many elements then we have proved that $A$ is countably infinite. Note that  if $y_i ∈ A$ and $m_i ∈ Z$ for $i = 1, 2$ and $m_1 y_1 + m_2 y_2 ∈ [0,1)$, then $m_1 y_1 + m_2 y_2 ∈ A$. Reason being that if $y_i ∈ A$ then we have $y = n_i \alpha - k_i$ for some $k_i$ and $n_i$. Hence we have $m_1 y_1 + m_2 y_2 = (m_1 n_1 + m_2 n_2) \alpha - m_1 k_1 - m_2 k_2$ and that $m_1 y_1 + m_2 y_2 ∈ [0,1)$, where $m_1 y_1 + m_2 y_2 = (m_1 n_1 + m_2 n_2) \alpha (mod 1)$, which gives the wanted conclusion.
Now, why is it necessary that $m_1 y_1 + m_2 y_2 ∈ A$ if $y_i ∈ A$ and $m_i ∈ Z$ for $i = 1, 2$ and $m_1 y_1 + m_2 y_2 ∈ [0,1)$? And further, how do I understand that $A$ is infinite from realizing $m_1 y_1 + m_2 y_2 = (m_1 n_1 + m_2 n_2) \alpha - m_1 k_1 - m_2 k_2$ and that $m_1 y_1 + m_2 y_2 ∈ [0,1)$, where $m_1 y_1 + m_2 y_2 = (m_1 n_1 + m_2 n_2) \alpha (mod 1)$?
I realize that the solution uses the theorem: "every infinite subset of a countable set $C$ is countable".
Thank you

A: An explanation of what's going on

Why is $B = \{n \alpha - k : n, k \in \mathbb Z\}$ countable?

It is the union of the countable sets $\mathbb Z + n \alpha$ over all $n \in \mathbb Z$ (where by $\mathbb Z + n \alpha$ I mean adding $n\alpha$ to each element of $\mathbb Z$).

If $y_1, y_2 \in A$ and $m_1 y_1 + m_2 y_2 \in [0,1)$, why is $m_1 y_1 + m_2 y_2 \in A$?

We can write $y_1 = n_1 \alpha \bmod 1 = n_1 \alpha - k_1$ for some integers $n_1, k_1$, and similarly $y_2 = n_2 \alpha - k_2$ for some integers $n_2, k_2$. Therefore $$m_1 y_1 + m_2 y_2 = (m_1 n_1 + m_2 n_2) \alpha - (m_1 k_1 + m_2 k_2).$$ Since $m_1 y_1 + m_2 y_2$ has the form "$(m_1 n_1 + m_2 n_2) \alpha$ minus an integer", and it is in the range $[0,1)$, it must be $(m_1 n_1 + m_2 n_2) \alpha \bmod 1$. That's an element of $A$ by definition.

Why does this tell us that $A$ is infinite?

By itself, it doesn't. The property above would be true even if $\alpha$ is rational; but if $\alpha$ were rational, then $A$ would be finite.
We have to additionally use the irrationality of $\alpha$ at some point, and the proof you're quoting never does. Maybe there's another part you haven't quoted? If not, then you're definitely not missing something obvious; there's just a gap in the proof.
A better proof
Rather than try to guess at what the intended use of that claim about $m_1 y_1 + m_2 y_2$ is, here is a shorter argument that avoids it entirely.
Define a function $f : \mathbb Z \to A$ by $f(n) = n\alpha \bmod 1$. It is surjective, because $A$ is defined as the image of $f$.
Lemma. $f$ is also injective: if $n_1, n_2 \in \mathbb Z$ with $n_1 \ne n_2$, then $(n_1 \alpha \bmod 1) \ne (n_2 \alpha \bmod 1)$.
Proof. We get $n_1 \alpha \bmod 1$ from $n_1 \alpha$ by adding some integer $m_1$ to get a value in the range $[0,1)$. This means that $(n_1 \alpha \bmod 1) = n_1 \alpha + m_1$. Similarly, there is some integer $m_2$ such that $(n_2 \alpha \bmod 1) = n_2 \alpha + m_2$.
We want to show that it's impossible to have $n_1 \alpha + m_1 = n_2 \alpha + m_2$. That's because if this holds, we can solve for $\alpha$ and get $\alpha = \frac{m_2 - m_1}{n_1 - n_2}$. But $\alpha$ was supposed to be irrational, contradiction. $\square$
Therefore $f$ is a bijection between $\mathbb Z$ and $A$. By definition, $|A| = |\mathbb Z|$: since $\mathbb Z$ is countably infinite, so is $A$.


text:
Q: Code to replace SWF with HTML5 if no flash detected What I have:
I'm embedding a *.swf file in a page.
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" width="960" height="630" id="test1">

<param name="movie" value="demo.swf" />

<embed src="demo.swf" width="960" height="630" name="test1" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" />

</object>

What I need:
When flash is not detected, I need to display a HTML5 version of the *.swf file (made using Google Swiffy).
The HTML5 version is a large block of code in <script></script> tags.
My question:
How do I detect if flash is not enabled and then substitute a *.swf with a HTML5 alternative?
I can't deviate from the above *.swf embed code because it's the only block of code that I can find that allows me to successfully embed *.swf files in WordPress posts.

A: I ended up using a jQuery script to detect Flash support:
http://code.google.com/p/jqplugin/
If flash support isn't detected, the script hides the div containing the flash content and reveals the HTML5 version (or whatever your alternative content is).

A: If you put your alternate code inside of your object tag, if a browser does not support that object (your swf) then it will instead only see the code.  This is how adobe checks for flash support and if it isn't supported shows the get flash button.
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" width="960" height="630" id="test1">

    <param name="movie" value="demo.swf" />

    <embed src="demo.swf" width="960" height="630" name="test1" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" />

    <!-- PUT YOUR WEBSITE CODE HERE-->

</object>


text:
Q: How to execute external python script file (which is hosted on remote desktop) from SQL Server MS How can I execute python project, which is hosted on remote desktop from my local SQL server management studio (ideally from stored procedure). I tried to look Run Python Script from MSSQL into this but I am not aware of how to use it.
The python script ideally has some print statement, ideally I should able to read those print statements from SQL server too


text:
Q: MSBuild ExtensionPack Sql2008.Database task I am trying to do some SQL stuff (back a database, restore a database, run some script files) as part of an MSBuild script.  The Sql2008.Database task from the MSBuild Extension pack seemed to be a nice easy way of doing this, however i cannot find a way to specify a server instance or username and password.   I find it hard to believe that it is limited to the default instance on the machine you are building on and want to connect as the user MSBuild is running but i can't find a way to do anything else. This is the documentation I am working from.  Can anyone explain how to do this or do i need to look at a different approach?

A: There are UserName and UserPassword properties you can use:

<MSBuild.ExtensionPack.Sql2008.Database
MachineName="$(SQLServer)"
TaskAction="Backup"
DatabaseItem="$(SQLDatabaseName)"
DataFilePath="$(SQLBackupLocation)"
UserName="$(SQLUserName)"
UserPassword="$(SQLPassword)" />

A: I discovered that the MSBuild.ExtensionPack.BaseTask class has the properties MachineName UserName and UserPassword. SQL2008.Database class inherits from this class.  I am used to MSDN style documentation where the inherited members are documented on the derived class so i did not think to look for them there although i should have.  It does seem a strange place for them though as they are meaningless in the context of many of the other classes that inherit from MSBuild.ExtensionPack.BaseTask.

A: Doesnt that task have the MachineName member? Think thats just the sql instance name you need.
I use the task MSBuild.ExtensionPack.SqlServer.SqlExecute and a sql statement to do everything else
 e.g.
<MSBuild.ExtensionPack.SqlServer.SqlExecute TaskAction="ExecuteReader"
                                                Sql="RESTORE DATABASE $(DatabaseName) FROM  DISK = N'$(RestoreFileDestination)\Source\$(Branch)\Build\$(DatabaseFile)' WITH FILE = 1,MOVE N'Accelerate' TO N'$(dataDir)\$(DatabaseName)_1.LDF', MOVE N'Accelerate_log' TO N'$(logsDir)\$(DatabaseName)_2.LDF', NOUNLOAD, REPLACE, KEEP_CDC, STATS = 10"
                                                ConnectionString="Data Source=Localhost\SQLExpress;Initial Catalog=master;Integrated Security=True"
                                                CommandTimeout="660">

They'd never think of all the options i seem to need....


text:
Q: How do you take the results of combination and save to a list? I know how to generate a 3 digit combination using combinations, and I can get the results to show, but I cannot for the life of me figure out how to get from this step to saving the generated list of 3 digit combinations into an actual list that I can save to a txt file. Any help would be appreciated.
I'm trying to generate a list of 3 digit combos that I can then test a script I wrote to take the txt file of the list and test it against a 3 digit password protect file. I really just want help on figuring out how to get the results from the combinations to save to a list.
comb = combinations([1, 2, 3,4,5,6,7,8,9], 3)
for i in list(comb):
    print i

Expect results if I can figure it out, the combination will run, and I will save the results to a list that I can write to file.

A: You can just convert directly to a list ...
from itertools import combinations
comb_list = list(combinations([1, 2, 3,4,5,6,7,8,9], 3))
> [(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 2, 7), (1, 2, 8), (1, 2, 9), (1, 3, 4), (1, 3, 5), (1, 3, 6), (1, 3, 7), (1, 3, 8), (1, 3, 9), (1, 4, 5), (1, 4, 6), (1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 5, 6), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 7, 8), (1, 7, 9), (1, 8, 9), (2, 3, 4), (2, 3, 5), (2, 3, 6), (2, 3, 7), (2, 3, 8), (2, 3, 9), (2, 4, 5), (2, 4, 6), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 5, 6), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 6, 7), (2, 6, 8), (2, 6, 9), (2, 7, 8), (2, 7, 9), (2, 8, 9), (3, 4, 5), (3, 4, 6), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 5, 6), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 6, 7), (3, 6, 8), (3, 6, 9), (3, 7, 8), (3, 7, 9), (3, 8, 9), (4, 5, 6), (4, 5, 7), (4, 5, 8), (4, 5, 9), (4, 6, 7), (4, 6, 8), (4, 6, 9), (4, 7, 8), (4, 7, 9), (4, 8, 9), (5, 6, 7), (5, 6, 8), (5, 6, 9), (5, 7, 8), (5, 7, 9), (5, 8, 9), (6, 7, 8), (6, 7, 9), (6, 8, 9), (7, 8, 9)]

EDIT
To get as 3 digit strings
[str(a[0])+str(a[1])+str(a[2]) for a in combinations([1,2,3,4,5,6,7,8,9], 3)]
> ['123', '124', '125', '126', '127', '128', '129', '134', '135', '136', '137', '138', '139', '145', '146', '147', '148', '149', '156', '157', '158', '159', '167', '168', '169', '178', '179', '189', '234', '235', '236', '237', '238', '239', '245', '246', '247', '248', '249', '256', '257', '258', '259', '267', '268', '269', '278', '279', '289', '345', '346', '347', '348', '349', '356', '357', '358', '359', '367', '368', '369', '378', '379', '389', '456', '457', '458', '459', '467', '468', '469', '478', '479', '489', '567', '568', '569', '578', '579', '589', '678', '679', '689', '789']

This is equivalent to
ans = []
for comb in combinations([1,2,3,4,5,6,7,8,9], 3):
    ans.append(str(comb[0])+str(comb[1])+str(comb[2]))

Or better yet using join
''.join(str(num) for num in (1, 2, 3))
> '123'

Gives
[''.join(str(num) for num in a) for a in combinations([1,2,3,4,5,6,7,8,9], 3)]


text:
Q: Can't change a navigation bar color I am trying to draw a white navigation bar with black button on splash (Theme.Paper.Launcher) and after change a background color to @color/primary_dark (Theme.Paper):
style-v27:
<resources>
    <!-- Basic paper theme -->
    <style name="Theme.Paper" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary</item>
        <item name="colorAccent">@color/accent</item>
        <item name="windowNoTitle">true</item>
        <item name="actionModeStyle">@style/Widget.Paper.ActionMode</item>
        <item name="windowActionModeOverlay">true</item>
        <item name="actionModeCloseDrawable">@drawable/ic_close_white_24dp</item>
        <item name="actionMenuTextColor">@color/white</item>
        <item name="android:windowLightStatusBar">false</item>
        <item name="android:navigationBarColor">@color/primary_dark</item>
        <item name="android:windowLightNavigationBar">false</item>
    </style>
    <!-- Splash theme. -->
    <style name="Theme.Paper.Launcher" parent="Theme.Paper">
        <item name="colorPrimary">@android:color/white</item>
        <item name="colorPrimaryDark">@android:color/white</item>
        <item name="android:windowBackground">@drawable/bg_splash</item>
        <item name="android:windowLightStatusBar">true</item>
        <item name="android:navigationBarColor">@android:color/white</item>
        <item name="android:windowLightNavigationBar">true</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    </style>
</resources>

But my navigation bar is still black with white buttons. What am I doing wrongly?
P.S. There is Android Oreo on my phone...


text:
Q: awk gensub matched the wrong number I'm trying to match the contents in the 1st [], but always get the last. What's wrong in the expression?
BTW, other fields are also needed, so awk is preferred.
echo "[a1 b1] [a2 b2]" | awk '{p=gensub(/.*\[(.*?)\].*/,"\\1",1); print p}'

want "a1 b1", but get "a2 b2". Thanks!

A: Following awk may help you in same.
echo "[a1 b1] [a2 b2]" | awk -F"[][]" '{print $2}'

Explanation: Simply making ][ as a field separator then printing the 2nd field since fields will be divided as per mentioned field separator.


text:
Q: Ошибки в интернет-магазине Добрый день. Установил на сайте OpenCart, но на сайте показывается огромное количество ошибок и с кодировкой проблемы. Подскажите, пожалуйста, что мне делать? Вот магазин - http://fishing-trade.com/
A: Да у вас не только с кодировкой проблемы, судя по всему, а еще и права выставлены неверно или вообще не выставлены)
A: все отлично работает...
а как вообще сам движок?
кто в курсе?
слышал что грамотный
Если сравнивать с simpla
OpenCart лучше или нет???


text:
Q: Do POST beep codes also generate a numeric code for a POST test card? My wife is an American Sign Language interpreter. She is currently interpreting for a student in a computing class. Today they were talking about BIOS and POST beep codes and the student asked the instructor if there is any way they could get the code without being able to hear it.
The instructor didn't have any suggestions, but when she mentioned it to me my first thought was a POST test card. I haven't had/used one since the original PCI days. I don't remember and have no way at hand to test whether there is a numerical code generated/visible on the card when/after the beep codes play.
I have not been able to find any pertinent info, and I am having a hard time figuring out a search that doesn't return pages of false hits. If there is someone out there who knows or could test this for me I would appreciate it.

A: Possibly not an answer, but an option - as a lot of mobos don't have a beeper onboard, but do have a connector to attach one - a buzzer attached to that port perhaps, something that can be felt rather than heard?

A: I worked in an IT shop previously where one of our senior staff began to lose his hearing due to old age.
He was a bit of a DIY-centric person so he built this small handheld black box powered by a 9v battery. It had what looked like a rectangle with 10 square lights built into it, as well as a microphone. Simply put, the louder a given noise, the more lights lit up allowing him to visually distinguish sound.
I can't seem to find any similar commercial versions of this (Is the market viable enough for commercial manufacturing?). Though I suspect an Android phone and app might be able to accomplish something similar.

A: This seems to be an XY question, so I'm going to answer your problem rather than your question.
You can advise the student to use a spectral visualiser on her mobile, for example this app on Android. This has the advantage that it wouldn't require any special hardware, just a standard smart phone with a mic, and you don't need to crack open the case, and a room that's not too noisy.

A: A short search found this UltraX Post Monitoring:

How do I see the generated POST Error Codes?
  POST codes can be seen as they are being generated by your BIOS with any of Ultra-X's QuickPOST Series P.O.S.T. Card. Simply plug any of the QuickPOST Series cards into your PC's PCI or ISA slot or MicroPOST into your parallel port and watch as the BIOS as the BIOS performs its tests. The QuickPOST Series cards as well as the MicroPOST parallel adapter display HEX digits which consist of alphanumeric characters 0-9 & the letters A-F.

Using Google image search for bios post card display shows many POST cards having numerical displays.

A: Plug a LED with a ~330 Ohm resistor attached (note the +/- polarity!) instead of the beeper; it should light up when the beeper goes on.
Note 1: "Beep" is actually a square current alternating between GND (0V) and +5V rail - but since the LED will light up and down a couple of hundreds times a second, visually it will just light up with decreased intensity (as in PWM).
Note 2: Alternatively, since beeper is driven by 0/+5V voltage, you can power a BJT or MOS FET and drive any electronics with it, e.g. firing missile rockets at the moon at every beep; YMMV.
Reference: http://en.wikipedia.org/wiki/PC_speaker


text:
Q: I have a function that takes two arguements and i need to pass thru two columns of a dataframe one by one This is a function i am using. I have two variables that i need to enter to get an output as you see below. I need to pass thru 10,000 columns as seems in image 2, which is just two of the columns. But essentially i need this to run 10k lines of a dataframe and save each output back in the dataframe ideally.
Here is my table. i need to pass thru these columns. they are passed as lists to the function.

      |  dx_full_list                         |  poa
------|---------------------------------------|--------------------
12345 | [I255, I5023, R570, I4901]            | [R570]
44444 | [I255, D62, D689, T86298, N390, I495] | [T86298, N390, I495]

from hcuppy.elixhauser import ElixhauserEngine
ee = ElixhauserEngine()

dx_full_lst =  df.iat[0,0]
dx_poa_lst = df.iat[0,1]
out = ee.get_elixhauser(dx_full_lst,dx_poa_lst)
print(out)

{'cmrbdt_lst': ['HF'], 'rdmsn_scr': 0, 'mrtlt_scr': 0}`
image2
I can't get anything close to a result.


text:
Q: mysql query returns the value in the first column for all the other columns Hi I made a query to a table below and when I tried to get the value in each column , it returns the same value from the first column for all the other columns.
To elaborate
In my database table I have the following:
owner_id = 21
pet_id = 1
name = fluffy
color = green
type = dog
sub_type = boxer
location = LA

however whenever I try to access one column, say the name column, it returns 21 which is the
value in the owner_id column corresponding to that pet_id. I am not sure why this is
happening.
$query = sprintf("SELECT * FROM `petAttributes` where pet_id ='%d'",$p_id);
 $result = performQuery($query);

 $owner_id = stripslashes(mysql_result($result,"owner_id"));
 $pet_id = stripslashes(mysql_result($result,"pet_id"));
 $name = stripslashes(mysql_result($result,"name"));
 $color = stripslashes(mysql_result($result,"color"));
 $type = stripslashes(mysql_result($result,"type"));
 $sub_type = stripslashes(mysql_result($result,"sub_type"));
 $loc = stripslashes(mysql_result($result,"location"));

Information on my environment
PHP Version 5.2.14
MYSQL version 5.0.67

A: I believe that if you use mysql_result you also have to specify the row index number (row 0 in your case?), before you specify the column.
$name = stripslashes(mysql_result($result, 0, "name"));

A: refering to http://php.net/manual/en/function.mysql-result.php mysql_result has it's parameters like this: mysql_result($result,$rownumber,$fieldname or $fieldnumber)
this should workd:
$query = sprintf("SELECT * FROM petAttributes where pet_id ='%d'",$p_id);
$result = performQuery($query);

$owner_id = stripslashes(mysql_result($result,0,"owner_id"));
$pet_id = stripslashes(mysql_result($result,0,"pet_id"));
$name = stripslashes(mysql_result($result,0,"name"));
$color = stripslashes(mysql_result($result,0,"color"));
$type = stripslashes(mysql_result($result,0,"type"));
$sub_type = stripslashes(mysql_result($result,0,"sub_type"));
$loc = stripslashes(mysql_result($result,0,"location"));

BTW mysql_result is getting very inefficient if you take more than one row.
Then you should use mysql_fetch_row, mysql_fetch_array or mysql_fetch_assoc

A: Also you can;
for only first row
$query = sprintf("SELECT * FROM petAttributes where pet_id ='%d'",$p_id);
$result = performQuery($query);
$row = mysql_fetch_array($result);

extract($row);

or all returned rows;
$query = sprintf("SELECT * FROM petAttributes where pet_id ='%d'",$p_id);
$result = performQuery($query);
while($row = mysql_fetch_array($result))
{
  foreach ($row as $value)  echo $value."<br>";
}


text:
Q: Invite friends dialog I have an invite dialog on my page:
xx

When the invited user clicks the invite, he gets linked to the app, but I want the user to get redirected to a page like http://www.facebook.com/pages/xxx/xxx?sk=app_xxxx.
How can I do that?

A: That's not possible without some custom coding - the requests interface exists to drive traffic to apps on facebook, not to page tabs, there's no way to have Facebook send users to a tab when they accept the request.
You could just implement something on your canvas landing page that redirects users back to a page tab based on the information in the request as a workaround.

A: previous version of the apprequest which is request-form this was possible:   How can I include a link in a FB app request?
However current version of apprequest : facebook guys lets only redirect to your app: https://apps.facebook.com/yourapp
@Vihay comments helps this custom workaround to redirect to page.
Hoping next version apprequests, facebook enables redirect to links within the fb app.

A: Agree with previous answers. Facebook will redirect to your app, which is just a Facebook wrapper around a page you can provide. That page can then use a client-side redirect to whatever page you'd like (like what Klout does).


text:
Q: Any mechanism for Run Functional Test Task to not fail the release deploy on test failure Under the XAML and earlier builds we had built into the default templates a flag to state if failed tests failed the build, or issued a warning.
Under Release Management 2015 in a release definition using the Run Functional Test task- I don't see a means to indicate that failed tests should not fail the release. Am I overlooking something? A flag, an argument, is it something I don't realize I can set in a test settings file?
The flag of "Continue on error" for the task will still cause a failure of the release deploy for that environment if the task fails which it does if a test fails. Unless I am wrong on this but I think I am correct as I tested that scenario. TFS 2015 Update 3.
My scenario which I suspect is not uncommon is I run a few different sets of test on a deploy to a new environment. For example: set 1 are smoke BVT and if they fail I want the deploy to fail. That works fine. But set 2 I add a separate task to run that set of Functional Tests but they are regression tests that I don't want to fail the deploy just because one of them fails.
Worst case scenario I'll modify the task and make a custom task with the logic I desire but I'd prefer to not have to keep maintaining that if there is a means I am missing of flagging that the task failure does not fail the deploy.

A: Build and release tasks have an option to Continue on error in the Control Options parameters for each task. In a build definition, this results in a Build partially succeeded result if a task with this option set should fail. The same behavior is also available in release definitions. If a task fails, the overall release result will show as "Release partially succeeded".

By default, a partially successful release will not automatically
  trigger a release to a subsequent environment, even if this behavior
  is specified in the environment deployment options. However, a new
  option can be set in each release environment that instructs Release
  Management to trigger a release to a subsequent environment when the
  previous release is partially successful.

For more details, see Trigger on partially successful deployments
It's the simplest way in your situation. Otherwise you may have to modify the task and make a custom task with the logic as you mentioned. However this feature is not available on TFS2015 update3, you may have to update to TFS2017. Please see the related Release Note.


text:
Q: How to open an .exe file with -dev mode? (not the shortcut ) I want to start Company of Heroes game with the -dev mode but not through the shortcut but using the original .exe. Is there any way to bind the .exe with this flag so that it opens all the time using that flag?
I tried everything I could from the Internet. I created a shortcut and made it run through a .bat file and then converted the .bat file to an .exe file but the file is not being detected as the original file.
I want to use the .exe file with the GameRanger software.


text:
Q: Or equal (|=) ; And equal (&=); I've been coding in c++ for quite a while. today I've stumbled upon one table. it was depicting Logical operators and their symbols. Till now all of the operators I've ever used were : && , || , !. However the table tells that there are more. I haven't really cared about them except for two: "OR EQUAL" and "AND EQUAL".I have searched the internet for them. Sadly found no proper results.
Here is a picture of the table and  code below showing my point of view how those two operators could work.

Have you ever used these operators, if so how?


text:
Q: MySQL MATCH, AGAINST not works with PDO I have this simple code to make search results depending on relevance:
$stmt = $db->query('SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")');
$appCount = $stmt->rowCount();

echo $appCount;

And it's not showing any results!
Thanks in advance for your help,
Marcell

A: Stackoverflow's usability is below zero.
Because there is no way to make a half-screen banner shown to everyone posting a question under PDO tag:
Enable ERRMODE_EXCEPTION when connecting to PDO before asking a question.
Because it is pointless to ask without an error message, yet error message most likely will render a question unnecessary.
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
$opt = array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);
$pdo = new PDO($dsn,'root','', $opt);

A: Try
 'SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")'

in phpmyadmin and see if it really returns anything.

A: try this
   <?php
  // Connection data (server_address, database, name, poassword)
   $hostdb = 'localhost';
   $namedb = 'tests';
   $userdb = 'username';
   $passdb = 'password';

 try {
  // Connect and create the PDO object
 $db = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
 $db->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8

 // Define and perform the SQL SELECT query
 $sql = "SELECT * FROM `apps` WHERE MATCH(appName, appSeller) AGAINST("angry")";
 $stmt = $db->query($sql);

  // If the SQL query is succesfully performed ($stmt not false)
 if($stmt !== false) {
  $cols = $stmt->columnCount();           // Number of returned columns

   echo 'Number of returned columns: '. $cols. '
';

 // Parse the result set
  foreach($stmt as $row) {
  echo $row['id']. ' - '. $row['name']. ' - '. $row['category']. ' - '. $row['link'].  '
';
 }
 }

 $db = null;        // Disconnect
 }
 print_r($sth->errorInfo());
 }
?>

A: enclose your code in try and catch blocks, then you should get a clue to where your going wrong in your SQL syntax:
    try {

         // your code

    } catch ( PDOException £e ) {

         echo $e->getMessage();
         exit();

    }


text:
Q: Android/Java - Activity Lifecycle - where am on returning to previous Activity? I can't find information on where am I in first activity when I hit "back" in the second. Why?
The first one surely is not being re-made, so in which "on..." (like onResume(), onStop(), etc.) am I?

A: onResume() will be called per the Activity Lifecycle
In the image in that link it says

User returns to the activity

onPause() will be called first then upon returning, onResume() will be called, under normal circumstances.
To check this, you can @Override onResume() and see that it is called.

A: When you press back then you come back to onResume() of activity1
For more info check : http://developer.android.com/training/basics/activity-lifecycle/starting.html

A: The answer depends on your activities. Here are a couple of different scenarios that will result in different life cycle methods being called. Every scenario below assumes there is an activity A and B, where the latter is invoked by the first; i.e. after a button press.
Scenario 1: B is translucent and/or not full size (i.e. dialog style)
Activity A will lose focus but is still visible because B is non-full-sized and/or transparent and sits on top of A. In this case A will be paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.
Scenario 2: B is full size
Activity A is completely obscured by B. It will be stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.
All of the above is well-documented in the life cycle section of the Activity class.
So we now know that activity A will be either paused (scenario 1) or stopped (scenario 2), or it will have been killed by the system to free up memory. Let's first assume that the latter doesn't happen, then the following life cycle methods are relevant:
Scenario 1: onPause() when B shows, followed by onResume() when A comes back into focus.
Scenario 2:: onPause() and onStop() when B shows, followed by onStart() and onResume() when A comes back into focus.
If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state. That means the activity will start again with onCreate(), followed by onStart() and onResume().
In the life cycle documentation you'll find the following flow diagram that you may find of use:


text:
Q: How to change the direction of increasing x in a plot Consider the data set
data = Table[{10^-k, 10^(-2 k)}, {k, 5}]
and the plot:
ListLogLogPlot[data]

My goal is to reverse the plot direction for the abscissa. That is instead of having x increase from left to right, have x decrease when moving from left to right.
The instructions here How to change the axes' origin and direction? are not quite what is needed.

A: The ScalingFunctions option is officially documented for BarChart and similar functions, but it actually works with the *Plot functions as well! See Belisarius's comment here.
In your case, you could use it to your advantage:
data = Table[{10^-k, 10^(-2 k)}, {k, 5}]

ListPlot[
   data,
   ScalingFunctions -> {{-Log10[#] &, 10^-# &}, "Log"},
   Frame -> {True, True, False, False}
]

Here I am using a plot Frame rather than the Axes because I found that the latter have a disappointing tendency to now show up in log plots unless one specifies an AxisOrigin explicitly, which is typically a pain. Fortunately, however, a frame can be effectively used in lieu of axes, and it will always show up independent of the plot range.
Some standard scaling options for ScalingFunctions are shown in its documentation, such as "Log" for simple log plots, and "Reversed" to invert the values along one axis. What you want would be a combination of "Log" and "Reverse" for the x-axis. Unfortunately, however, no more than one of these built-in versions can be applied at a time, so we have to roll our own scaling function in your case.
For each axis, you provide a pair of functions to generate the desired scaling. If you'll allow me the hand-waving explanation, here is how I envision the process. The first function is applied to the raw data to determine the transformed value that will actually be plotted. Appropriate plot tick positions are then calculated internally, and the second function (typically the inverse of the first one) is applied to their value to generate the corresponding labels, so you get the effect mentioned in the documentation, i.e. ticks and gridlines showing unscaled values at scaled locations, just like one would expect for a log-log plot.
With that in mind, the "Log" scaling would be represented by a Log10[#]& scaling function; the "Reverse" scaling by a -#& function. Combine the two, and you'll obtain your desired reversed log scaling: -Log10[#]&. To generate ticks and grid lines, you'll need the inverse of that function, which of course is 10^-#&.

This use of ScalingFunctions has been shown before on this site (I wouldn't have been able to figure this out on my own!). I can't seem to find the relevant question right now, but I will add a link when I find it.

As soon as I posted the answer, I saw the comments from @GuessWhoItIs and @2012rcampion, respectively providing the link I couldn't find, and something very close to the solution I proposed here. Hopefully my explanation may still be useful to you.


text:
Q: How to insert blob using knex? Currently, I have an upload system using ng-file-upload to another server, which is working well thanks to CORS.
To manage my database I use knex (migrations and seed), and I have a specific table with a bytea column.
PostgreSQL database.
to make upload possible, I've added the busboy module to allow express to manage multipart requests, and the file is being saved to the disk with no problem.
but what I really want is to save it in the table, in the bytea column, and right now I'm with no luck on such quest.
Any guidance and better documentation are welcome.

A: After a long time i figured it out.
In the end it is dead simple to make upload works with angular+express+knex+postgres
first of all, there's no need to busboy, instead, you'll need the bodyParser's raw mode
second, adjust it to comport a reasonable upload size.
third, ng-file-upload will help with the upload part.
here's a few snippets if anyone is in need of it:
Upload button:
<div layout="row" layout-align="center center">
  <md-button ngf-select ng-model="arquivo" class="md-raised md-primary">Selecionar arquivo</md-button>
  <md-button ng-show="arquivo" ng-click="arquivo = null" class="md-raised md-warn">Cancelar</md-button>
  <md-button ng-show="arquivo" ng-click="sendarquivo(arquivo)" class="md-raised md-primary" ng-disabled="arquivo.size > 4096 * 1024">Enviar arquivo</md-button>
</div>

controller.sendarquivo:
$scope.sendarquivo = function (arquivo) {
  enqueteservice.uploadanexo(idenquete, arquivo).then(function () {
    $scope.list();
    $scope.arquivo = null;
  });
};

enqueteservice.uploadanexo:
// serviço de enquete
angular.module("roundabout").factory("enqueteservice", function($http, Upload) {
  return {
    uploadanexo: function(idenquete, file) {
      return Upload.http({
        url: "/enquete/" + idenquete + "/uploadanexo/" + file.name,
        method: 'POST',
        headers: {
          'Content-Type': 'application/octet-stream' // file.type //
        },
        data: file
      });
    }
  }
});

on server side, express router:
router.post("/:idenquete/uploadanexo/:descricaoanexoenquete", function (req, res) {
  knex("anexoenquete").insert({
    idenquete: req.params.idenquete,
    descricaoanexoenquete: req.params.descricaoanexoenquete,
    dadoanexoenquete: req.body
  }, "idanexoenquete").then(function (ret) {
    res.send("idanexoenquete:" + ret[0]);
  }).catch(function (err) {
    res.status(500).send(err);
    console.log(err);
  });
});

for reference, the bodyParser setup at index.js
// ...
app.use(bodyParser.json({limit: 1024 * 1024}));// 1MB of json is a lot of json
// parse some custom thing into a Buffer
app.use(bodyParser.raw({limit: 10240 * 1024, type: 'application/octet-stream'})); // 10 MB of attachments

with this setup, ng-file-upload body will arrive at express router as a Buffer, wich you can pass directly to knex insert statement.
download binary content can also be easily solved as follows:
download attachment
router.get("/downloadanexo/:idanexoenquete", function (req, res) {
  knex("anexoenquete").select().where({
    idanexoenquete: req.params.idanexoenquete
  }).then(function (ret) {
    if (!ret.length)
      res.status(404).send("NOT FOUND");
    else {
      var anexoenquete = ret[0];
      res.setHeader("Content-disposition", "attachment;filename=" + anexoenquete.descricaoanexoenquete);
      res.send(anexoenquete.dadoanexoenquete);
    }
  }).catch(function (err) {
    res.status(500).send(err);
    console.log(err);
  });
});

hope this reference helps anyone else in the future, i'm able to shutdown an simple java app which was solving this issue for me.

A: The best approach is using Amazon s3 or other services to store blobs while storing metadata in sql.
If you want to store anyway, you can use sql driver and bluebird.


text:
Q: CSV2XML using PHP - need to add a line to output XML I found the following code online and it works fine for me.
I need to convert and CSV file to an XML file.
The only thing I need to change is to make the code to output the same XML structure adding the line of the rss version as I mentioned below to my examples.
<?php
     // Map CSV file to array
      $rows = array_map('str_getcsv', file('data.csv'));
      $header = array_shift($rows);
      $data = array();
       foreach ($rows as $row)
      {
        $data[] = array_combine($header, $row);
      }
     // Process Data if need be
       foreach($data AS $key => $val)
     {
        // Processing here
      }
      //Creates XML string and XML document using the DOM
      $xml = new DomDocument('1.0', 'UTF-8');

      //Add root node
      $root = $xml->createElement('channel');
      $xml->appendChild($root);

      // Add child nodes
      foreach($data AS $key => $val)
  {
$entry = $xml->createElement('item');
$root->appendChild($entry);

foreach($val AS $field_name => $field_value)
{
    $field_name = preg_replace("/[^A-Za-z0-9]/", '', $field_name); // preg_replace has the allowed characters
    $name = $entry->appendChild($xml->createElement($field_name));
    $name->appendChild($xml->createCDATASection($field_value));
  }
}
 // Set the formatOutput attribute of xml to true
 $xml->formatOutput = true;
 // Output to screen
 // header('Content-Type: text/xml');
 // echo $xml->saveXML();
 // Save as file
    $xml->save('xml-import.xml'); // save as file
    ?>

The code mentioned above outputs the following XML structure:
<channel>
 <item>
 <title>
  <![CDATA[ pablo1 ]]>
 </title>
 <description>
  <![CDATA[ this is description 1 ]]>
 </description>
 <link>
  <![CDATA[ http://www.link1.com ]]>
 </link>
 </item>
</channel>

Someone knows how to update the code in order to output the following XML structure? Basically I need to add the rss version="2.0" line.
<rss version="2.0">
 <channel>
  <item>
   <title>
    <![CDATA[ pablo1 ]]>
   </title>
   <description>
    <![CDATA[ this is description 1 ]]>
   </description>
   <link>
    <![CDATA[ http://www.link1.com ]]>
   </link>
  </item>
 </channel>
</rss>

Thank you all for your help!

A: You can nest the element...
$root = $xml->createElement('channel');
$rss = $xml->createElement('rss');
$rss->setAttribute("version","2.0");
$rss->appendChild($root);
$xml->appendChild($rss);


text:
Q: Position buttons below image I'm trying to position these right below picture. I can make them appear below but not right before after image. Also on mobile version it is not a row. Buttons are not in line there is a button below better as a column. Screenshots provided. Please help

Here is my website: http://www.kiljakandweb.com
Here is my HTML:

Here is my CSS:
img {
    float: right;
    width: 85%;
    margin-top: 250px;
    margin-right: -25px;
    padding-bottom:200px;
}

.col-centered{
    float: none;
    margin: 0 auto;
    padding-bottom: 200px;
}

jQuery:
$(document).ready(function(){
    $("img").fadeOut("fast");
    $(".buttons1").fadeOut("fast");

    $("a").on("click", function(){
        $("img").fadeIn(2000);
    })

    $("a").on("click", function(){
        $(".buttons1").fadeIn(2000);
    })

    });

A: First there is a padding which prevents the buttons appearing below image. You can fix this easily by adding this to your css file.
section#myprojects img {
    padding-bottom: 0px;
}

And for the second problem, i advice you to give an id to this div like so:

And then you can call it in your css file:
#yourIDhere a {
    display: table-cell;
    padding: 5px;
}

or try this (I wouldn't recommend if you use this class definition elsewhere)
.col-lg-1.col-xs-2.col-sm-2.col-md-1.col-centered a {
    display: table-cell;
    padding: 5px;
}


text:
Q: Telerik MVC Grid Master Detail Cascading Dropdowns I am using a master-detail Telerik MVC Grid on two levels.

*

*The first level contains a drop-down of Customers and some misc data.

*The second level contains a drop-down of Cars that are linked to the customer on the first level and some misc data.

I am now using a foreign key column to show the dropdowns of cars and clients.
How can the second dropdown be filtered by the customer on the first level?
Code:
@(Html.Telerik().Grid<Models.ClientsModel>()
        .Name("Grid")
        .ToolBar(commands => commands.Insert().ButtonType(GridButtonType.ImageAndText))
        .DataKeys(keys => keys.Add(c => c.ClientLineID))
        .Columns(columns =>
        {
            columns.ForeignKey(o => o.ClientID, (System.Collections.IEnumerable)ViewBag.Client, "ClientID", "Name")
                                                   .Width(330)
                                                   .Title("Client");
            columns.Command(commands =>
                {
                    commands.Edit().ButtonType(GridButtonType.ImageAndText);
                    commands.Delete().ButtonType(GridButtonType.ImageAndText);
                }).Width(250);
        })
        .DetailView(car => car.ClientTemplate(

            Html.Telerik().Grid<Delta.Models.CarModel>()
                        .Name("Car_<#= ClientID #>")
                        .DataKeys(keys => keys.Add(c => c.LineID))
                        .ToolBar(commands => commands.Insert().ButtonType(GridButtonType.ImageAndText))
                        .DataBinding(dataBinding =>
                        {
                            dataBinding.Ajax()
                                .Select("_CarLineIndex", "Client", new { id = "<#= ClientID #>" })
                                .Insert("_CarLineCreate", "Client", new { id = "<#= ClientID #>" })
                                .Update("_CarLineUpdate", "Client")
                                .Delete("_CarLineDelete", "Client");
                        })
                        .Columns(columns =>
                                {
                                    columns.ForeignKey(o => o.CarID, (System.Collections.IEnumerable)ViewBag.Cars,
                                    "CarID", "No")
                                                   .Width(500)
                                                   .Title("Car");
                                    columns.Command(commands =>
                                    {
                                        commands.Edit().ButtonType(GridButtonType.ImageAndText);
                                        commands.Delete().ButtonType(GridButtonType.ImageAndText);
                                    }).Width(200);
                                })
                        .Editable(editing => editing => editing.Mode(GridEditMode.InLine))
                        .Scrollable(c => c.Height("auto"))
                        .Resizable(resizing => resizing.Columns(true))
                        .Reorderable(reorder => reorder.Columns(true))
                        .KeyboardNavigation()
                        .Footer(false)
                        .ToHtmlString()
            ))
        .DataBinding(dataBinding =>
        {
            dataBinding.Ajax()
                .Select("_ClientIndex", "Client")
                .Insert("_ClientCreate", "Client")
                .Update("_ClientUpdate", "Client")
                .Delete("_ClientDelete", "Client");
        })
        .Scrollable(c => c.Height("auto"))
        .Editable(editing => editing.Mode(GridEditMode.InLine))
        .Pageable(o => o.PageSize(50))
        .Filterable()
        .KeyboardNavigation()
        .Groupable())

I am thinking that the code might involve some javascript on the OnDetailViewExpand event, but I can't figure out what.
The only solution I have now is to split the grid into separate views and build cascasing comboboxes there.

A: Unfortunately I cannot comment on posts yet to clarify some facts about your question. I'll make some assumptions in my answer so that we can work out the exact nature of the problem. You have two model classes one for each grid ClientsModel and CarModel. You are filtering the CarModel (second)grid with fields from the ClientsModel (first)grid.
You are not restricted to just one(<= ClientID =>) parameter in your select binding. You can use other fields from the ClientsModel class the same way as ClientID.
Sample Code:
dataBinding.Ajax().Select("_CarLineIndex", "Client", new { id = "<#= ClientID #>", city = "<#= City #>" })

Here is a working example with mock data that illustrates the method mentioned above:
Client Class
public class Client
{
    public int ClientId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string City { get; set; }
}

Car Class
public class Car
{
    public string Make { get; set; }
    public string Model { get; set; }
    public int Year { get; set; }
    public string Color { get; set; }
}

HomeController
[GridAction]
public ActionResult _Index()
{
    Client c1 = new Client() { ClientId = 1, City = "Boston", FirstName = "Ted", LastName = "Boder" };
    Client c2 = new Client() { ClientId = 2, City = "New York", FirstName = "Chris", LastName = "Tobb" };
    Client[] clients = {c1, c2};
    return View(new GridModel(clients));
}

[GridAction]
public ActionResult _Cars(int ClientId, string City)
{
    Car c1 = new Car() { Color = "Yellow", Make = "Ford", Model = "Mustang", Year = 2012 };
    Car c2 = new Car() { Color = "Black", Make = "Toyota", Model = "Camry", Year = 2010 };
    Car[] cars = { c1, c2 };
    return View(new GridModel(cars));
}

View
@(Html.Telerik().Grid<Client>()
    .Name("Clients")
    .Columns(columns =>
    {
        columns.Bound(o => o.FirstName);
        columns.Bound(o => o.LastName);
        columns.Bound(o => o.City);
    })
    .DetailView(clientDetailView => clientDetailView.ClientTemplate(
         Html.Telerik().Grid<Car>()
         .Name("ClientDetails_<#= ClientId #>")
         .Columns(columns =>
         {
             columns.Bound(c => c.Make);
             columns.Bound(c => c.Model);
             columns.Bound(c => c.Year);
             columns.Bound(c => c.Color);
          })
          .DataBinding(db2 => db2.Ajax().Select("_Cars", "Home", new { ClientID = "<#= ClientId #>", City = "<#= City #>" }))
          .Pageable()
          .Sortable()
          .ToHtmlString()
    ))
    .DataBinding(db1 => db1.Ajax().Select("_Index", "Home"))
    .Pageable()
    .Sortable()
    .Filterable()
)

As you can see from the example I'm also passing a City parameter as well as a ClientId when binding the grid.
Let me know if I missed something.

A: You are correct that you will need to do this with javascript, and it is a matter of being able to filter cars by customers. Telerik allows you to add additional parameters using the "e.data" argument for most of their controls. So for example if you wanted to filter a city list based on a select state the CSHTML would look like this:

        @(Html.Telerik().DropDownListFor(m => m.State)
        .Name("State")
        .ClientEvents(events => events.OnChange("State_Change"))
        .BindTo(new SelectList(Model.GetStates()))
         .HtmlAttributes(new { style = string.Format("width:{0}px", 160) })
     )

     @(Html.Telerik().AutoCompleteFor(m => m.City)
         .Name("City")
         .Encode(false)
         .ClientEvents(events => {
             events.OnDataBinding("City_AutoComplete");
     })
     .DataBinding(a => a.Ajax().Select("CityList", "Location"))
     .AutoFill(true)
     .HighlightFirstMatch(true)
     .HtmlAttributes(new { style = string.Format("height: 17px; width:{0}px", 250) })
     )

The javascript would look like this:
function City_AutoComplete(e) {
    //pass state as an additional parameter here to filter
    //this would be your customer for cars list
    e.data = $.extend({}, e.data, { state: $("#State").val() });
}

function State_Change(e) {
    //reset when the parent list selection changes
    $('#City').data('tAutoComplete').text('');
    $('#City').data('tAutoComplete').value('');
}

A: Nothing to complex, create client event onEdit, you can found sample on telerik demo, than after once created client write down dropedown selection change event code that will filter data for you car dropdown. to do this I would suggest you to call ajax and insert HTml for dropdown. If you have still doubt than let me know I will explain it in detail.
If you you really find this answer best or appropriate please vote it.. it will help...


text:
Q: Spark JDBC password in clear text JDBC temporary view I'm using a temporary view to load Oracle data in Hive using Spark SQL. Example from the Spark docs below:
CREATE TEMPORARY VIEW jdbcTable
USING org.apache.spark.sql.jdbc
OPTIONS (
  url "jdbc:postgresql:dbserver",
  dbtable "schema.tablename",
  user 'username',
  password 'password'
)

This is working well but having the password in clear text in the view DDL means the password is visible in the Spark Thrift Server log. In pyspark I am able to read the password using spark.jdbc.password (as in How to protect password and username in Spark (such as for JDBC connections/accessing RDBMS databases)?) and pass the value through:
jdbc_password = spark.conf.get('spark.jdbc.password')
df = spark.read.format('jdbc').options(
    driver='oracle.jdbc.driver.OracleDriver',
    url='jdbc:oracle:thin://@host:1521/svc',
    user='db_user',
    password=jdbc_password,
...

But I cannot find a way to do this in pure Spark SQL for use via Thrift Server.
Assuming it is not possible then it would be great to hook into the credential API. Again I can to this via Python but cannot see a pure SQL way to do it.
Does anyone know if it's possible to avoid having the password in clear text in the temporary view?
(I've reworded this question as I think I originally misunderstood spark.jdbc.password)


text:
Q: accountExpires attribute not listed when read from Java Hello Java and AD experts..
I am having an issue while reading accountExpires attribute value from AD. When I read this attribute using Java code, I got the result null.
Then I thought of checking various attributes provided by AD by printing the all the AD attributes using the following code:
        Attributes allAttrs = ldapCtx.getAttributes(distinguishedName);
        System.out.println("Total no.of properties: " + allAttrs.size());
        try{
            String attrs = "";
            for (NamingEnumeration ae = allAttrs.getAll(); ae.hasMore();) {
                Attribute attr = (Attribute) ae.next();
                attrs = attrs+"\nFor attribute: "+ attr.getID()+" values are - ";

                /* print each value */
                for (NamingEnumeration e = attr.getAll(); e.hasMore(); attrs = attrs + e.next()+";");

            }
            System.out.println(attrs);
        }
        catch(Exception e){
            System.out.println("Exception in getAttribute: " + e);
        }

It had listed 72 properties. And accountExpires property itself is not present there :(
Can anyone guide me why this property is not available in my case and how to get rid of this
Regards,
FH

A: It wont list any account expiration attribute. You need to calculate it. Suppose your password expiration limit is 90 days and you need to send a warning mail to the user when there is 10 days left for expiration. You will get account created date, find the number of days between the account created date and current date if the difference is 80 then send a warning mail.


text:
Q: Python Data Scraping Data Scraping in Pyhton.
Code is working fine but it is showing the error which I mentioned below.
What could be the reason?
import urllib2
from bs4 import BeautifulSoup
from xlwt import workbook

wb = Workbook()
sheet1 = wb.add_sheet('Sheet1')

soup = BeautifulSoup(urllib2.urlopen("http://en.wikipedia.org/wiki/List_of_Indian_satellites").read())

for row in soup('table', {'class': 'wikitable sortable jquery-tablesorter'})[0].tbody('tr'):
    tds = row('td')
    sheet1.write(row, 0, tds[0].string)
    sheet2.write(row, 1, tds[1].string)

wb.save('Performance Project.xls')

Error:   File "ProcessingProject.py", line 12
      SyntaxError: Non-ASCII character '\xe2' in file ProcessingProject.py on line 12

but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

A: #!/usr/bin/env python
# -*- coding: utf-8 -*-

Add this to top of your file

A: for row in soup('table', {'class': 'wikitable sortable jquery-tablesorter'})[0].tbody('tr'):
You used a wrong character as single quote delimiter sign after jquery-tablesorter


text:
Q: Animate an OverlayItem when retrieving coordinates from a WebService I'm using a webservice to follow a car position and i display the car position on a map with an Overlay item.
I'm able to refresh the position of the car by removing/adding the overlayItem, however i would like to animate it from the old coordinates to the new one ithout removing it from the map. Is it possible ?


text:
Q: Add project as library in Android Studio I want to use this library in my project. I download the code and place it on my libs folder.
Then I set on app.gradle:
dependencies {
    compile project('libs/android-support-v4-preferencefragment')
}

as I read in a previous question here but it's not working, android studio tells me it cant find the project

A: The support-v4-preferencefragment project support local maven repository in this commit. So, you can deploy it into local maven repository and then reference it in your android studio application project.

*

*Clone the library project
$ git clone https://github.com/kolavar/android-support-v4-preferencefragment.git

*Deploy aar library into local maven
$ cd android-support-v4-preferencefragment
$ ./gradlew uploadArchives
Now, aar should be within your local maven repository. eg: ~/.m2/repository/com/android/support/support-v4-preferencefragment/1.0.0

*Reference it in the application project
Add compile 'com.android.support:support-v4-preferencefragment:1.0.0' within the dependencies block of your app's build.grade.
If there is no mavenLocal() within your repositories block, add it too.

A: right click on the jar file and click Make Module it should put the correct information in the gradle file. probably what the problem is that your are missing .jar at the end though


text:
Q: How Can I create complicated query in just one query like working with MS Access? I'm using MS Access in order to summary stuffs.
As an example, assuming that I had these 3 queries below
1. fetching all males who are aged over 20
1. select users.id, users.name, users.age, users.gender
   from users
   where users.age > 20 AND users.gender = 1   (means male)

2. fetching all cars whose make is "FORD"
2. select cars.user_id, cars.make, cars.name_of_car
   from cars
   where cars.make = "FORD"

3. fecthing all accidents that are the most recent happened in 2014
3. select accidents.user_id, accidents.car_accident_date_ymd
   from accidents
   group by accidents.user_id
   having (((max(accidents.car_accident_date_ymd)) Like "2014*"));

At 4th query, I connect them all together
users.id(1) = (n)cars.user_id
users.id(1) = (1)accidents.user_id

then show
`users.id, users.name, users.age, users.gender, cars.make, accidents.car_accident_date_ymd`

How can I put them all together in one query?
If possible, I'd like to use all 3 queries above and put them together somehow.
Any idea?

A: You are going to need to JOIN:
SELECT users.id,
       users.name,
       users.age,
       users.gender,
       cars.make,
       accidents.car_accident_date_ymd
FROM   users users
       JOIN cars cars
         ON users.id = cars.user_id
       JOIN accidents accidents
         ON accidents.user_id = users.id
WHERE  users.age > 20
       AND users.gender = 1
       AND cars.make = "ford"
GROUP  BY accidents.user_id
HAVING (( ( Max(accidents.car_accident_date_ymd) ) LIKE "2014*" ));

A: select users.id, users.name, users.age,
users.gender, cars.make, max(accidents.car_accident_date_ymd)
from accidents
join users on users.id = accidents.user_id
join cars on cars.user_id = users.id
where users.age > 20
    and users.gender = 1
    and cars.make = 'FORD'
group by users.id, users.name, users.age,
users.gender, cars.make
having max(accidents.car_accident_date_ymd) Like "2014*"

The query above assumes you want to select the most recent car_accident_date_ymd, if you want to select every unique one you'll need to include it in your group by which means you might get duplicate users in your result set i.e.
select users.id, users.name, users.age,
users.gender, cars.make, accidents.car_accident_date_ymd
from accidents
join users on users.id = accidents.user_id
join cars on cars.user_id = users.id
where users.age > 20
    and users.gender = 1
    and cars.make = 'FORD'
group by users.id, users.name, users.age,
users.gender, cars.make, accidents.car_accident_date_ymd
having max(accidents.car_accident_date_ymd) Like "2014*"


text:
Q: Taking mySQL database input from HTML form with PHP I'm trying to take in data from a webpage with a HTML form and PHP to my mySQL Database. It connects just fine on both pages but I get an error when I try to submit from the form. It will take in data if I just write it into the PHP myself and click submit, but it won't take it from the form so there must be something wrong there but I can't figure out what. I've never used PHP with mySQL before so I'm not too sure how it all works. Any help with an explanation of how it's working would be appreciated.
Below is my test.html.php page where my form is and the testinsert.php page where I try to insert the data.
(Also, courseID is a foreign key in the 'test' table, so i need to make the courseID selectable from the options, i struggled with this and I don't know if this is where the issue lies. In the current code it is in a drop down menu, it shows the courseID's but there is a blank option in between each option e.g. the list of options will be - '4', 'blank', '5'... etc)
<!DOCTYPE html>

<?php
include 'connect.php';
?>

    <link rel="stylesheet" type="text/css" href="style.css" />
    <meta name="viewport" content="width=1024, initial-scale=1.0, maximum-scale=1.0,user-       scalable=no"/>

    <title>Test Sign Up</title>

Test Sign Up

            <form action="testinsert.php" method ="post">

                Name:
                <input type="text" id="name" name="name" placeholder="Enter
                your name here" required>

                Test Sentence:
                <input type="text" id="testsentence" name="testsentence" placeholder="Enter your sentence here" required>

                Course:
                <select id="course" name="course">
                <?php

                $query = "SELECT CourseID FROM Course";

                $result = mysqli_query($conn, $query);

                while($row = mysqli_fetch_array($result)){

                    echo "<option>" . $row['CourseID'] . "<option>";

                }

                mysqli_close($conn);

                ?>
                </select>

            <button type="submit" name="submit">Submit</button>

            </form>

    View Courses

    Return to home page

Testinsert.php -
<?php
include 'connect.php';

$name = 'name';
$testsentence = 'testsentence';
$courseid = 'course';

$sql="INSERT INTO Test (Name, TestSentence, Course)
VALUES ('$name','$testsentence', '$courseid')";

if (mysqli_query($conn, $sql)) {
    echo "

New record added successfully";
    echo '

Return to home page';
} else {
    echo "

Error adding record";
    echo '

Return to home page';
}

mysql_close($conn);
?>

A: You are getting blank options AFTER each option with an expected value because you have failed to write a closing option tag.  / needs to be written into the second option tag like this:
while ($row = mysqli_fetch_array($result)) {
    echo "<option>{$row['CourseID']}</option>";
}

The option tags still render even if you don't properly close them.  In this case, the error presents itself by generating twice the desired tags.
I recommend that you use MYSQLI_ASSOC as the second parameter of your mysqli_fetch_array call or more conveniently: mysqli_fetch_assoc
In fact, because $result is iterable, you can write:
foreach ($result as $row) {
    echo "<option>{$row['CourseID']}</option>";
}

About using extract($_POST)...
I have never once found a good reason to use extract in one of my scripts.  Not once.  Furthermore, the php manual has a specific Warning stating:

Warning
  Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES).

There are more warning down the page, but you effectly baked insecurity into your code by calling extract on user supplied data.  DON'T EVER DO THIS, THERE IS NO GOOD REASON TO DO IT.
Here is a decent page that speaks about accessing submitted data: PHP Pass variable to next page
Specifically, this is how you access the expected superglobal data:
$name = $_POST['name'];
$testsentence = $_POST['testsentence'];
$courseid = $_POST['course'];

You must never write unfiltered, unsanitized user supplied data directly into your mysql query, it leads to query instability at best and insecurity at worst.
You must use a prepared statement with placeholders and bound variables on your INSERT query.  There are thousands of examples of how to do this process on Stackoverflow, please research until it makes sense -- don't tell yourself that you'll do it layer.

A: Make sure you added extract($_POST) (or something similar) in your PHP code!
You need to extract the parameters from your POST request before using them, otherwise your $name, $testsentence, and $courseid will be undefined.


text:
Q: Decoupling from the DOM and bringing functionality into a directive I am trying to make a Snap-to-Component Directive.  At this point I have made a proof of concept with logic that lives in the app component (which would possibly be replaced with Renderer2 HostListeners and HostBindings) and it looks like I would have to get the dom properties (child1L, child1R...etc.) of the children probably using Renderer2.  My question is how would you decouple what I have done so far into a directive or a group of parent and child directives?  Or at least what direction would you go from here?  I am new to using Renderer2, HostListeners, and HostBinding so I was wondering how a more experienced person would do this. Thank you. Here is my current stackblitz.
app.component.ts:
import { Component,ElementRef,ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

switchDirection = "first";
head: ElementRef;

@ViewChild('child01') child01;
@ViewChild('child02') child02;
@ViewChild('child03') child03;

  onScroll(event: Event) {
    let viewBoundaryL = (event.target as HTMLElement).scrollLeft;
    console.log("viewBoundaryL:" + viewBoundaryL);

//SNAP FROM FIRST TO SECOND CHILD
    if(viewBoundaryL >= 50 && this.switchDirection === "first"){
this.child02.el.nativeElement.scrollIntoView({ behavior: 'smooth', block: "center"  });
setTimeout(() => {
     this.switchDirection = "second";
      //  console.log(this.switchDirection)
    }, 300);
    }

//SNAP FROM SECOND TO FIRST CHILD
    if(viewBoundaryL <= 310 && this.switchDirection === "second"){
this.child01.el.nativeElement.scrollIntoView({ behavior: 'smooth', block: "center"  });
setTimeout(() => {
  this.switchDirection = "first";
  // console.log(this.switchDirection)
    }, 300);
    }

//SNAP FROM SECOND TO THIRD CHILD
        if(viewBoundaryL >= 370 && this.switchDirection === "second"){
this.child03.el.nativeElement.scrollIntoView({ behavior: 'smooth', block: "center"  });
setTimeout(() => {
  this.switchDirection = "third";
  // console.log(this.switchDirection)
    }, 300);
  }

//SNAP FROM THIRD TO SECOND CHILD
        if(viewBoundaryL <= 615 && this.switchDirection === "third"){
this.child02.el.nativeElement.scrollIntoView({ behavior: 'smooth', block: "center"  });
setTimeout(() => {
  this.switchDirection = "second";
  // console.log(this.switchDirection)
    }, 300);
        }
  }
}

app.component.html:

<child1 #child01></child1>
<child2 #child02></child2>
<child3 #child03></child3>

Thanks for your insights!

A: You probably want to create an attribute directive.
You can easily create a directive by using the Angular CLI with the following command (you can provide a path as the name core/directives/my-directive-name):
ng generate directive <name-of-directive>

Then in the constructor you can add the following to get reference to the element.
el: ElementRef

Finally using a HostListener, or any technique to bind to the scroll event. You can place a call to your snap to element code (will have to change to just check for itself), the element then will check if itself needs to initiate the scroll. And if it meets the condition, then it does.
For further bonus points, you can add inputs for setting and when to snap to the element for example, you template with the directive will look like this:

And then in the directive itself you would have:
@Input() scrollAt: number = 300 // sets a default incase it isn't provided;

Then you can use this variable for your view boundary.
Hope this helps, or at least puts you on the right track!


text:
Q: How can I change the background color via a manual boolean input toggle in Pine? I'm new to Pine Script and try to change the background color of the chart based on a boolean, which I manually can turn true/false (real time) via the input settings. The background color should only change for the bars, where the boolean is true (see example).
bool dummy_toggle = input(title="dummy_toggle", type=input.bool, defval=false)
BgBool = false
if dummy_toggle == true
    BgBool := true
bgcolor(color=BgBool ? color.lime : na, transp=85)

The mistake I probably make is that I don't appoint the bool value to a specific bar[series]. I don't know how to fix this. Could anybody help me with this?

A: You are moving in the right direction.
The script in your case should be something like this.
bool dummy_toggle = input(title="dummy_toggle", type=input.bool, defval=false)
BgBool = false
if condition_for_background_color == true
    BgBool := true
bgcolor(color=(dummy_toggle and BgBool)? color.lime : na, transp=85)

A: Happy New Year too!
Here is my sample code:
//@version=4
study("Test_Trade-ON-OFF-switch_bgcolor", overlay = true)

//GENERAL VARIABLES
//switch to manually turn the active trading ON and OFF
bool trade_on_off_switch = input(title="dummy_trade_on_off_switch", type=input.bool, defval=false)

//color background green for bars where active trading is ON (i.e. trade_on_off_switch == true)
color plotColor = color.white
BgBool = false
if trade_on_off_switch == true
    BgBool := true
bgcolor(color=(trade_on_off_switch and BgBool)? color.green : na, transp=85)

A: This script works.
//@version=4
study("Test_Trade-ON-OFF-switch_bgcolor", overlay = true)

//GENERAL VARIABLES
//switch to manually turn the active trading ON and OFF
bool trade_on_off_switch = input(title="dummy_trade_on_off_switch", type=input.bool, defval=true)

//color background green for bars where active trading is ON (i.e. trade_on_off_switch == true)
color plotColor = color.white
p = stoch(close, high, low, 14)
BgBool = false
if cross(p, 50) // e.g. crossing stochastic with level 50
    BgBool := true

hline(50,color=color.black)
bgcolor(color=(trade_on_off_switch and BgBool)? color.green : na, transp=50)
plot(p, color=color.blue)


text:
Q: Automatically copy all mails from one folder to another I have a postfix/dovecot mailserver setup, running fine. My problem is that different e-mail clients save sent e-mails in different folders. I realize that saving sent e-mail is not in the SMTP protocol, so my question doesn't regard that. I have installed Sieve succesfully in Dovecot but that only works on incoming mail (if I'm not mistaken).
Now my idea was to create a cronjob that moves all mails from different Sent folders to a 'default' one. So I want to select one 'default' Sent folder and move (not copy) all e-mails from alternative Sent folders to the default one on a regular basis, so that my users don't get confused over where to search for their sent e-mails on different clients. Can such a thing be done and if so, how would you approach it?
I'm not looking for a ready-cooked answer here, just some tips on how and where to start searching for information.

A: Following Michael Hamptons suggestion and some more details here I altered /etc/dovecot/15-mailboxes.conf like this (Dutch mailbox names included)
mail_plugins = $mail_plugins mailbox_alias

plugin {
  mailbox_alias_old = Sent
  mailbox_alias_new = Sent Messages
  mailbox_alias_old2 = Sent
  mailbox_alias_new2 = Verzonden items
  mailbox_alias_old3 = Sent
  mailbox_alias_new3 = Sent Items
}

# NOTE: Assumes "namespace inbox" has been defined in 10-mail.conf.
namespace inbox {
  # These mailboxes are widely used and could perhaps be created automatically:
  mailbox INBOX.Drafts {
    auto = subscribe
    special_use = \Drafts
  }
  mailbox INBOX.Junk {
    auto =  subscribe
    special_use = \Junk
  }
  mailbox INBOX.Trash {
    auto = subscribe
    special_use = \Trash
  }

  # For \Sent mailboxes there are two widely used names. We'll mark both of
  # them as \Sent. User typically deletes one of them if duplicates are created.
  mailbox Sent {
    special_use = \Sent
  }
  mailbox "Sent Messages" {
    special_use = \Sent
  }
  mailbox "Verzonden items" {
    auto = create
    special_use = \Sent
  }
  mailbox "Sent Items" {
    auto = create
    special_use = \Sent
  }

}

Of course this is not exhaustive, you can add more language specific (damn you outlook) mailbox aliases. Did a dovecot reload and status, no errors.


text:
Q: How to toggle between 2 forms in JQUERY i am new to Jquery. I am trying to load a HTML with with 2 forms. I need to display only when form when page is loaded but as user clicks the switch button i want it to hide form1 and display form 2 but it hides form1 when button is checked but does not display form2. here is my code

$(document).ready(function() {
  var $form1 = $('#form1'),
    $form2 = $('#form2'),
    $form2.hide();

  $("#customSwitch1").click(function() {
    if ($form2.is(':visible')) {
      $form1.hide()
      $form2.show()
    } else {
      $form1.show()
    }
  });
});
/* The switch - the box around the slider */

#customSwitch1 {
  position: relative;
  display: inline-block;
  width: 15px;
  height: 10px;
}

  <input type="checkbox" class="custom-control-input" id="customSwitch1">

Switch to form2

<form id='form1' name='form1' method="" action="">
  <input type="text">
</form>

<form id='form2' name='form2' method="" action="">
  <input type="text">
</form>

A: The two issues in your existing code is that you are using , instead of ; to separate your statements, which is resulting in a syntax error in the snippet you provided, and you also need to call $form2.hide() in the else condition.
That being said, the code can be made more succinct by using toggle() to set the state of both forms based on the checked property of the checkbox.
Also, you should use CSS to hide the #form2 element by default to avoid any possibility of a FOUC, and also hook to the change event of the checkbox instead of click so that your code still works for users who navigate the web using their keyboard.
With all that said, try this:

jQuery($ => {
  let $form1 = $('#form1');
  let $form2 = $('#form2');

  $("#customSwitch1").on('change', e => {
    $form1.toggle(!e.target.checked);
    $form2.toggle(e.target.checked);
  });
});
#customSwitch1 {
  position: relative;
  display: inline-block;
  width: 15px;
  height: 10px;
}

#form2 {
  display: none;
}

  <input type="checkbox" class="custom-control-input" id="customSwitch1">

Switch to form2

<form id="form1" name="form1" method="" action="">

Form 1

  <input type="text" placeholder="form 1 value..." />
</form>

<form id="form2" name="form2" method="" action="">

Form 2

  <input type="text" placeholder="form 2 value..." />
</form>

A: Maybe this will help you.

$(document).ready(function() {
  $('.login-box .nav li').click(function() {
    id = $(this).attr('id');
    $('.login-box .nav li.selected, .login-box form.selected').removeClass('selected');
    $('#' + id + ', .login-box form.' + id).addClass('selected');
    $('.login-box form.' + id + ' input').first().focus();
  });
  $('.login-box form .input input').on("focus", function() {
    $(this).parent('.input').addClass('selected');
  }).blur(function() {
    $(this).parent('.input').removeClass('selected');
    if ($(this).val() !== "")
      $(this).parent('.input').addClass('good');
  });
});
.login-box,
.login-box .nav,
.login-box .nav li,
.login-box form .input,
.login-box .social-media,
.login-box .social-media li,
.login-box form .input .icon,
.login-box form .input label,
.login-box form .input input {
  margin: 0;
  padding: 0;
  transition: 300ms cubic-bezier(.4, 0, .2, 1);
  -o-transition: 300ms cubic-bezier(.4, 0, .2, 1);
  -ms-transition: 300ms cubic-bezier(.4, 0, .2, 1);
  -moz-transition: 300ms cubic-bezier(.4, 0, .2, 1);
  -webkit-transition: 300ms cubic-bezier(.4, 0, .2, 1);
}

.login-box {
  position: absolute;
  top: 20px;
  left: 50%;
  width: 100%;
  max-width: 400px;
  transform: translateX(-50%);
  font-family: 'Titillium Web', sans-serif;
  background: #29292E;
  text-align: center;
  color: #F0F0F0;
  border-radius: 15px;
  box-shadow: 1px 1px 10px black;
  overflow: hidden;
}

.login-box .nav {
  position: relative;
  width: 100%;
  line-height: 40px;
  display: table;
  list-style: none;
  color: grey;
  margin-bottom: 10px;
}

.login-box .nav li {
  position: relative;
  display: table-cell;
  width: 50%;
  cursor: pointer;
  background: #141414;
  background: rgba(20, 20, 20, .7);
}

.login-box .nav li.selected,
.login-box .nav li:hover {
  border-bottom: 1px solid #006DFF;
  color: #F0F0F0;
  background: none;
}

.login-box .social-media {
  position: relative;
  display: block;
  width: calc(100% - 40px);
  padding: 0 20px;
  list-style: none;
  line-height: 40px;
  margin-top: 5px;
  margin-bottom: 25px;
}

.login-box .social-media li {
  position: relative;
  margin: 0 4px;
  display: inline-block;
  width: calc(33.3333% - 12px);
  max-width: 120px;
  background: Red;
  border-radius: 5px;
}

.login-box .social-media li a {
  display: block;
  color: #F0F0F0;
  height: 40px;
}

.login-box .social-media li a i {
  line-height: 40px;
  font-size: 20px;
}

.login-box .social-media li.facebook {
  background: #3B5998;
  background: rgba(59, 89, 152, .5);
}

.login-box .social-media li.facebook:hover {
  background: #3B5998;
  background: rgba(59, 89, 152, 1);
}

.login-box .social-media li.google {
  background: #CC3333;
  background: rgba(221, 75, 57, .5);
}

.login-box .social-media li.google:hover {
  background: #CC3333;
  background: rgba(221, 75, 57, 1);
}

.login-box .social-media li.twitter {
  background: #1DA1F2;
  background: rgba(29, 161, 242, .5);
}

.login-box .social-media li.twitter:hover {
  background: #1DA1F2;
  background: rgba(29, 161, 2422, 1);
}

.login-box .title {
  position: relative;
  font-size: 14px;
  text-shadow: 1px 1px 1px black;
}

.login-box form {
  display: none;
  position: relative;
  padding: 0 20px;
  overflow: hidden;
  margin: 20px 0;
}

.login-box form.selected {
  display: block;
}

.login-box form .input {
  position: relative;
  width: 100%;
  margin-bottom: 10px;
  border-bottom: 1px solid grey;
}

.login-box form .input input,
.login-box form .input label {
  position: relative;
  display: block;
  width: 100%;
  background: none;
  border: none;
  outline: none;
  color: grey;
  padding: 0 25px;
  font-size: 20px;
}

.login-box form .input input {
  line-height: 30px;
  z-index: 1;
  padding-top: 10px;
}

.login-box form .input label {
  position: absolute;
  left: 0;
  text-align: left;
  z-index: 2;
  cursor: pointer;
  line-height: 55px;
}

.login-box form .input .icon {
  position: absolute;
  top: 10px;
  left: -150px;
}

.login-box form .input .icon {
  font-size: 18px;
}

.login-box form .input .underline {
  position: absolute;
  top: 100%;
  left: 0;
  width: 0%;
  height: 1px;
  background: #006DFF;
  transition: 500ms cubic-bezier(.4, 0, .2, 1);
  -o-transition: 500ms cubic-bezier(.4, 0, .2, 1);
  -ms-transition: 500ms cubic-bezier(.4, 0, .2, 1);
  -moz-transition: 500ms cubic-bezier(.4, 0, .2, 1);
  -webkit-transition: 500ms cubic-bezier(.4, 0, .2, 1);
}

.login-box form .input.good input,
.login-box form .input.good label,
.login-box form .input.selected input,
.login-box form .input.selected label {
  color: #F0F0F0;
}

.login-box form .input.good label,
.login-box form .input.selected label {
  padding: 0;
  font-size: 12px;
  line-height: 0px;
}

.login-box form .input.good .icon,
.login-box form .input.selected .icon {
  left: 0;
  color: #F0F0F0;
}

.login-box form .input.selected .underline {
  width: 100%;
}

.login-box form .input.good .underline {
  left: auto;
  right: 0;
  width: 0%;
}

.login-box form .input.submit {
  margin-top: 30px;
  border: none;
}

.login-box form .input input[type="submit"] {
  color: grey;
  height: 40px;
  background: #141414;
  background: rgba(20, 20, 20, .7);
  padding: 0;
}

.login-box form .input input[type="submit"]:hover {
  box-shadow: inset 100px 0 100px 0 #006DFF;
  cursor: pointer;
  padding-left: 10px;
  color: white;
}

Login

Register

  <form class='login-form selected'>
    Please Enter Your Login Details:

      Username
      <input type='text' name='log-username' id='log-username' />

      Password
      <input type='password' name='log-password' id='log-password' />

      <input type='submit' name='login' id='login' value='Login' disabled />

  </form>
  <form class='register-form'>
    Please Register to Login:

      Username
      <input type='text' name='reg-username' id='reg-username' />

      E-Mail Address
      <input type='email' name='reg-email' id='reg-email' />

      Password
      <input type='password' name='reg-password' id='reg-password' />

      Confirm Password
      <input type='password' name='reg-conf' id='reg-conf' />

      <input type='submit' name='register' id='register' value='Register' disabled />

  </form>

A: I added placeholders to the form inputs

const $form1 = $('#form1');
const $form2 = $('#form2');

//hide second form by default
$(document).ready(function() {
  $form2.hide();
})

//toggle between form1 & form2
document.querySelector("#customSwitch1").addEventListener("change", () => {
  $form1.toggle()
  $form2.toggle()
})

  <input type="checkbox" class="custom-control-input" id="customSwitch1">

Switch to form2

<form id='form1' name='form1' method="" action="">
  <input type="text" placeholder="form1">
</form>
<form id='form2' name='form2' method="" action="">
  <input type="text" placeholder="form2">
</form>


text:
Q: Symfony2 entity type check box set preferred choices I have the following form filed in the edit form.
->add('district', 'entity', array(
                    'class' => 'AdminBundle:Districts',
                               'query_builder' => function(EntityRepository $repository) {
                return $repository->createQueryBuilder('c')
                                    ->where('c.status =:status')
                                    ->setparameter('status','1');
            },
                    'property' => 'districtName',
                    'preferred_choices' => array($details->getDistrict()),
                    'multiple' => TRUE,
                    'expanded' => TRUE,
                    'required' => true,

                        )
                )

Output of this is checkboxes. I can check more districts here.
In the edit mode how to set the preferred choices?

A: OK, you need to use an EventListener against the form. See documentation for more information.
This will allow you to pre set form data
Example ()
/* Form */
 namespace Company\YourBundle\Form\Type;

 use Symfony\Component\Form\AbstractType;
 use Symfony\Component\Form\FormBuilderInterface;
 use Doctrine\ORM\EntityRepository;
 use Company\YourBundle\Form\EventListener\YourEventListener;

 class FormType extends AbstractType {

     public function buildForm(FormBuilderInterface $builder, array $options) {
         $builder->addEventSubscriber(new YourEventListener($builder->getFormFactory()));
     }

     public function getName() {
         return 'company_formtype';
     }

}

/* Event Listener (You may require to pass more data to this class from your form as I have little information to help you with)*/
 namespace Company\YourBundle\Form\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class ActivityListener implements EventSubscriberInterface {

private $form;

public function __construct($form) {
    $this->form = $form;
}

public static function getSubscribedEvents() {
    return array(
        FormEvents::PRE_SET_DATA => 'onPreSetData',
    );
}

public function onPreSetData(FormEvent $e) {
    $data = $e->getData();
    $form = $e->getForm();

    if ($form->has('district')) {
        $form->remove('district');
    }

    $form->add($this->form->createNamed('district', 'entity', null, array(
                        'class' => 'AdminBundle:Districts',
                           'query_builder' => function(EntityRepository $repository) {
            return $repository->createQueryBuilder('c')
                                ->where('c.status =:status')
                                ->setparameter('status','1')},
                                'property' => 'districtName',
                'preferred_choices' => $data['id'] ? /** in edit mode set the preferred **/ ? null,
                'multiple' => TRUE,
                'expanded' => TRUE,
                'required' => true,

                    ));
      }

 }