text:
Q: Throwaway memoization makes built-ins faster? Yesterday I got into an argument with @UnchartedWorks over in the comment thread here. At first glance, he posted a duplicate of Marius' answer, but with some unnecessary memoization:
unitize[x_] := unitize[x] = Unitize[x]
pick[xs_, sel_, patt_] := pick[xs] = Pick[xs, sel, patt]

and proposed the following test to justify his claim that his approach is faster:
RandomSeed[1];
n = -1;
data = RandomChoice[Range[0, 10], {10^8, 3}];

AbsoluteTiming[Pick[data, Unitize@data[[All, n]], 1] // Length]

AbsoluteTiming[pick[data, unitize@data[[All, n]], 1] // Length]

(*
{7.3081, 90913401}
{5.87919, 90913401}
*)

A significant difference. Naturally, I was skeptical. The evaluation queue for his pick is (I believe) as follows:

*

*pick is inert, so evaluate the arguments.

*data is just a list, 1 is inert, data[[All, n]] quickly evaluates to a list

*unitize@data[[All, n]] writes a large DownValue...

*...calling Unitize@data[[All, n]] in the process, returning the unitized list.

*Another large DownValue of the form pick[data] = *pickedList* is created (data here is, of course, meant in its evaluated form), never to be called again (unless, for some reason, we explicitly type pick[data]).

*The *pickedList* is returned.

What about the evaluation queue for Pick[data, Unitize@data[[All, n]], 1]?

*

*Pick is inert.

*data becomes an inert list, 1 is inert, data[[All, n]] quickly evaluates to an inert list.

*Nothing happens here.

*Unitize@data[[All, n]] returns the unitized list.

*Nothing happens here either.

*The same step as before is taken to get us the picked list.

So, clearly pick has more things to do than Pick.
To test this out I run the following code:
Quit[]

$HistoryLength = 0;

Table[
  Clear[pick, unitize, data];
  unitize[x_] := unitize[x] = Unitize[x];
  pick[xs_, sel_, patt_] := pick[xs] = Pick[xs, sel, patt];
  data = RandomChoice[Range[0, 10], {i*10^7, 3}];
 {Pick[data, Unitize@data[[All, -1]], 1]; // AbsoluteTiming // First,
  pick[data, unitize@data[[All, -1]], 1]; // AbsoluteTiming // First},
  {i, 5}]

Much to my surprise, pick is consistently faster!

{{0.482837, 0.456147},
 {1.0301,   0.90521},
 {1.46596,  1.35519},
 {1.95202,  1.8664},
 {2.4317,   2.37112}}

How can I protect myself from black magic make a representative test? Or should I embrace the black magic is this real and a valid way to speed things up?
Update re: answer by Szabolcs
Reversing the order of the list like so:
{pick[data, unitize@data[[All, -1]], 1]; // AbsoluteTiming // First,
 Pick[data, Unitize@data[[All, -1]], 1]; // AbsoluteTiming // First}

gave me the following result:

{{0.466251, 0.497084},
 {1.18016,  1.17495},
 {1.34997,  1.42752},
 {1.80211,  1.93181},
 {2.25766,  2.39347}}

Once again, regardless of order of operations, pick is faster. Caching could be suspect, and as mentioned in the comment thread of the other question, I did try throwing in a ClearSystemCache[] between the pick and Pick, but that didn't change anything.
Szabolcs suggested that I throw out the memoization and just use wrapper functions. I presume, he meant this:
unitize[x_] := Unitize[x];
pick[xs_, sel_, patt_] := Pick[xs, sel, patt];

As before, on a fresh kernel I set history length to 0 and run the Table loop. I get this:
{{0.472934, 0.473249},
 {0.954632, 0.96373},
 {1.42848,  1.43364},
 {1.91283,  1.90989},
 {2.37743,  2.40031}}

i.e. nearly equal results, sometimes one is faster, sometimes the other (left column is pick, right is Pick). The functions perform as well as Pick in a fresh kernel.
I try again with the memoization as described towards the beginning of the answer:
{{0.454302, 0.473273},
 {0.93477,  0.947996},
 {1.35026,  1.4196},
 {1.79587,  1.90001},
 {2.24727, 2.38676}}

The memoized pick and unitize perform consistently better out of a fresh kernel. Of course, it uses twice the memory along the way.

A: I can't reproduce claimed speedup on "11.0.1 for Linux x86 (64-bit) (September 21, 2016)".
In my tests, custom function wrappers without memoization (as suggested by Szabolcs) consistently add overhead of about 1 µs, functions with memoization add 2-3 µs overhead, compared to built-ins. This overhead is measurable only for small lists, for larger lists it's completely negligible.
Important thing is that results of AbsoluteTiming are very volatile with median deviation from minimal value, for larger lists, from few to ten percent. I'm sure there are better ways to measure this volatility, I used median deviation just to have any estimate.
Code used for timings:
$HistoryLength = 0;

minDev // ClearAll
minDev // Attributes = HoldFirst;
minDev[expr_, n_Integer?Positive] := Module[{res, min},
  res = Table[expr, n];
  min = Min@res;
  {min, Median[res - min]}
]

testBuiltin@data_ := (
  ClearSystemCache[];
  Pick[data, Unitize@data, 1] // AbsoluteTiming // First
)
testCustom@data_ := (
  ClearSystemCache[];
  ClearAll[unitize, pick];
  unitize[x_] := Unitize[x];
  pick[xs_, sel_, patt_] := Pick[xs, sel, patt];
  pick[data, unitize@data, 1] // AbsoluteTiming // First
)
testMemo@data_ := (
  ClearSystemCache[];
  ClearAll[unitize, pick];
  unitize[x_] := unitize[x] = Unitize[x];
  pick[xs_, sel_, patt_] := pick[xs] = Pick[xs, sel, patt];
  pick[data, unitize@data, 1] // AbsoluteTiming // First
)

testAll[k_, n_] :=
  With[{data = (SeedRandom[1]; RandomChoice[Range[0, 10], k])},
    minDev[#@data, n] & /@ {testMemo, testCustom, testBuiltin}
  ]
format = TableForm@Map[
  NumberForm[#, ExponentFunction -> (Null &)] &,
  SetAccuracy[#, Min[Accuracy@SetPrecision[Min@#, 2], 7]],
  {-1}
] &;

First argument of testAll is size of used data, second is number of repeated timings. First column of result is minimal absolute timing, second is median deviation from this minimal value. First rows are results for memoized custom pick and unitize, second rows are results for non-memoized custom functions, third rows are for built-in Pick and Unitize.
testAll[10^1, 10^5]//format
(* 0.000004 0.*10^(-7)
   0.000002 0.000001
   0.000001 0.000001 *)

testAll[10^2, 10^5]//format
(* 0.000005 0.000001
   0.000003 0.000001
   0.000002 0.000001 *)

testAll[10^3, 10^5]//format
(* 0.000015 0.000001
   0.000014 0.*10^(-7)
   0.000013 0.000001 *)

testAll[10^4, 10^5]//format
(* 0.000124 0.000002
   0.000122 0.000002
   0.000121 0.000001 *)

testAll[10^5, 10^4]//format
(* 0.001297 0.000093
   0.001296 0.000069
   0.001295 0.000103 *)

testAll[10^6, 10^3]//format
(* 0.0201   0.0014
   0.0201   0.0011
   0.0201   0.0012 *)

testAll[10^7, 10^2]//format
(* 0.2004   0.0148
   0.2003   0.0099
   0.2004   0.0088 *)

testAll[5 10^7, 2 10^1]//format
(* 0.972    0.021
   0.974    0.017
   0.973    0.022 *)

Fresh kernel
To make sure that we're not using any Mathematica's internal cache, that might not be cleared by ClearSystemCache, we can launch separate kernel for each test using:
freshKernelEvaluate // ClearAll
freshKernelEvaluate // Attributes = HoldAll;
freshKernelEvaluate@expr_ := Module[{link, result},
  link = LinkLaunch[First@$CommandLine <> " -mathlink -noprompt"];
  LinkWrite[link, Unevaluated@EvaluatePacket@expr];
  result = LinkRead@link;
  LinkClose@link;
  Replace[result, ReturnPacket@x_ :> x]
]

Timings of built-ins:
resBuiltin = Table[
  freshKernelEvaluate[
    SeedRandom@1;
    data = RandomChoice[Range[0, 10], 5 10^7];
    Pick[data, Unitize@data, 1] // AbsoluteTiming // First
  ],
  100
]

{1.28392, 1.23527, 1.25863, 1.23625, 1.33601, 1.24361, 1.26809,
      1.23502, 1.34473, 1.23813, 1.24654, 1.23617, 1.27127, 1.25661,
      1.22674, 1.58978, 1.26939, 1.37024, 1.24581, 1.54075, 1.23516,
      1.23805, 1.3053, 1.40044, 1.42726, 1.39822, 1.46109, 1.27038,
      1.39617, 1.2588, 1.29047, 1.23082, 1.25069, 1.34985, 1.27281,
      1.24016, 1.2642, 1.2511, 1.23745, 1.27978, 1.24066, 1.38282, 1.32234,
      1.30623, 1.26118, 1.58021, 1.27522, 1.24706, 1.27051, 1.2493,
      1.24819, 1.28184, 1.46254, 1.24269, 1.26356, 1.24011, 1.35468,
      1.27491, 1.35288, 1.24462, 1.27119, 1.26811, 1.23685, 1.33249,
      1.23138, 1.29139, 1.23725, 1.28638, 1.23906, 1.27579, 1.3872,
      1.31602, 1.29556, 1.26464, 1.27076, 1.24602, 1.25735, 1.24667,
      1.27297, 1.23757, 1.34311, 1.26616, 1.35083, 1.24861, 1.23788,
      1.25357, 1.24262, 1.28117, 1.25753, 1.28231, 1.23406, 1.27971,
      1.22885, 1.27199, 1.24191, 1.23346, 1.26387, 1.24803, 1.27653,
      1.23953}

Timings of memoized custom functions:
resMemo = Table[
  freshKernelEvaluate[
    SeedRandom@1;
    data = RandomChoice[Range[0, 10], 5 10^7];
    unitize[x_] := unitize[x] = Unitize[x];
    pick[xs_, sel_, patt_] := pick[xs] = Pick[xs, sel, patt];
    pick[data, unitize@data, 1] // AbsoluteTiming // First
  ],
  100
]

{1.35284, 1.23307, 1.27167, 1.23678, 1.27437, 1.25009, 1.27847,
  1.2418, 1.23227, 1.39655, 1.26371, 1.26179, 1.27424, 1.27965, 1.236,
  1.28489, 1.25988, 1.26318, 1.24007, 1.24381, 1.2672, 1.25462,
  1.26703, 1.24123, 1.28868, 1.24192, 1.27177, 1.23488, 1.23468,
  1.27525, 1.26571, 1.27287, 1.23757, 1.26981, 1.25737, 1.2729,
  1.23705, 1.24429, 1.26927, 1.23292, 1.28266, 1.23352, 1.28423,
  1.23743, 1.26883, 1.23515, 1.27272, 1.25892, 1.23213, 1.23746,
  1.3435, 1.27545, 1.23472, 1.49113, 1.42916, 1.56421, 1.5238, 1.37695,
  1.27734, 1.23146, 1.2388, 1.24054, 1.27661, 1.23467, 1.43818,
  1.51605, 1.28172, 1.24674, 1.34043, 1.36447, 1.28034, 1.23788,
  1.3027, 1.25299, 1.26136, 1.24514, 1.23405, 1.26157, 1.24994,
  1.27737, 1.23637, 1.26785, 1.411, 1.24163, 1.2301, 1.29223, 1.25492,
  1.25177, 1.26862, 1.25825, 1.23715, 1.25327, 1.2694, 1.6624, 1.24317,
  1.26682, 1.27915, 1.25705, 1.23258, 1.25804}

I don't see any consistent difference, distribution of results seems similar:
res = <|"Built-in" -> resBuiltin, "Memo" -> resMemo|>;
ListPlot[res, PlotRange -> All]
Histogram[res, PlotRange -> All, ChartStyle -> {Blue, Orange}, ChartLegends -> Automatic]

Edit
UnchartedWorks writes in a comment that unitize is enough to show difference in speed and pick is not necessary. Carl Woll points out that data matrix should be used instead of data vector.
After changing above I see a difference between memoized and built-in version. Memoized function is consistently slower than built-in.
Used test functions:
testBuiltin = freshKernelEvaluate[
  $HistoryLength = 0;
  SeedRandom@1;
  data = RandomChoice[Range[0, 10], {#, 3}];
  Pick[data, Unitize@data[[All, -1]], 1] // AbsoluteTiming // First
] &;
testCustom = freshKernelEvaluate[
  $HistoryLength = 0;
  SeedRandom@1;
  data = RandomChoice[Range[0, 10], {#, 3}];
  unitize[x_] := Unitize[x];
  Pick[data, unitize@data[[All, -1]], 1] // AbsoluteTiming // First
] &;
testMemo = freshKernelEvaluate[
  $HistoryLength = 0;
  SeedRandom@1;
  data = RandomChoice[Range[0, 10], {#, 3}];
  unitize[x_] := unitize[x] = Unitize[x];
  Pick[data, unitize@data[[All, -1]], 1] // AbsoluteTiming // First
] &;

Timings:
SetDirectory@NotebookDirectory[];
s = OpenWrite@"results.dat";
k = 3 10^7;
Do[
  Write[s,
    If[OddQ@i,
      {testBuiltin@k, testCustom@k, testMemo@k},
      Reverse@{testMemo@k, testCustom@k, testBuiltin@k}
    ]
  ],
  {i, 10^2}
] // AbsoluteTiming
file = Close@s;
(* {898.653, Null} *)

Result analysis:
results = AssociationThread[{"Built-in", "Custom", "Memo"} -> Transpose@ReadList@file]
colors = {Blue, Orange, Darker@Green};
ListPlot[results, PlotRange -> All, PlotStyle -> colors]
Histogram[results, PlotRange -> All, ChartStyle -> colors, ChartLegends -> Automatic]

<|"Built-in" -> {1.22985, 1.22461, 1.23061, 1.23184, 1.2402, 1.22937,
     1.25221, 1.21342, 1.23612, 1.22765, 1.23061, 1.23409, 1.25464,
     1.21786, 1.23144, 1.24461, 1.24803, 1.24498, 1.24818, 1.23294,
     1.2348, 1.51256, 1.51016, 1.46498, 1.48277, 1.49113, 1.38432,
     1.23417, 1.23139, 1.23475, 1.23356, 1.22846, 1.23629, 1.25202,
     1.23593, 1.24975, 1.22473, 1.23137, 1.2266, 1.25627, 1.21828,
     1.2525, 1.23725, 1.24693, 1.24163, 1.23324, 1.28597, 1.23083,
     1.22618, 1.23927, 1.22844, 1.23095, 1.21823, 1.23546, 1.23057,
     1.22338, 1.22514, 1.23199, 1.23086, 1.21832, 1.22947, 1.22668,
     1.2302, 1.24527, 1.23862, 1.48311, 1.48445, 1.47365, 1.24457,
     1.25607, 1.26731, 1.22819, 1.23567, 1.23589, 1.27261, 1.22645,
     1.22554, 1.23832, 1.22731, 1.2334, 1.25166, 1.26591, 1.22114,
     1.24653, 1.22359, 1.22788, 1.22567, 1.25535, 1.23223, 1.24091,
     1.24912, 1.23169, 1.23663, 1.23177, 1.2278, 1.55135, 1.4796,
     1.49146, 1.49611, 1.23101},
   "Custom" -> {1.23652, 1.23587, 1.23412, 1.22896, 1.22707, 1.23646,
     1.25783, 1.26341, 1.24158, 1.22581, 1.22999, 1.24083, 1.23376,
     1.23851, 1.24782, 1.22384, 1.2431, 1.23661, 1.23801, 1.24318,
     1.23982, 1.53433, 1.48343, 1.54463, 1.48097, 1.47601, 1.23676,
     1.24323, 1.2311, 1.22642, 1.23351, 1.23296, 1.23254, 1.23407,
     1.23169, 1.24395, 1.24042, 1.24769, 1.23167, 1.21756, 1.2301,
     1.23421, 1.24282, 1.23704, 1.23525, 1.2351, 1.25029, 1.23524,
     1.22839, 1.22839, 1.23667, 1.26583, 1.22544, 1.22955, 1.22292,
     1.22819, 1.27443, 1.24958, 1.24789, 1.22195, 1.21883, 1.22279,
     1.21813, 1.22052, 1.23921, 1.5044, 1.49484, 1.50915, 1.23095,
     1.23694, 1.22373, 1.24806, 1.22945, 1.24085, 1.23373, 1.22282,
     1.2362, 1.23099, 1.23932, 1.24258, 1.25047, 1.26868, 1.23042,
     1.22579, 1.2229, 1.23243, 1.2368, 1.22925, 1.2387, 1.23014,
     1.21772, 1.2259, 1.22549, 1.23208, 1.26501, 1.33781, 1.48822,
     1.48658, 1.25979, 1.26228},
   "Memo" -> {1.29497, 1.29798, 1.29918, 1.29907, 1.31014, 1.29503,
     1.29095, 1.3249, 1.29036, 1.30051, 1.2789, 1.29959, 1.2988, 1.2882,
      1.29519, 1.28946, 1.31952, 1.32948, 1.32447, 1.29627, 1.31841,
     1.5721, 1.57097, 1.55392, 1.56358, 1.55974, 1.28744, 1.3029,
     1.28567, 1.2914, 1.29167, 1.29062, 1.29471, 1.29797, 1.30193,
     1.30423, 1.30097, 1.29706, 1.29027, 1.29005, 1.29543, 1.2929,
     1.29996, 1.29386, 1.29502, 1.31621, 1.31506, 1.29105, 1.30462,
     1.28348, 1.30922, 1.28715, 1.30386, 1.29361, 1.29596, 1.30149,
     1.28943, 1.29833, 1.31909, 1.2911, 1.31163, 1.28986, 1.29063,
     1.28847, 1.29451, 1.46695, 1.55118, 1.55433, 1.29779, 1.29201,
     1.29947, 1.29045, 1.28494, 1.29003, 1.29385, 1.2856, 1.31603,
     1.33432, 1.28929, 1.29873, 1.29259, 1.28694, 1.28868, 1.28838,
     1.29824, 1.29435, 1.29401, 1.30137, 1.2971, 1.29248, 1.29333,
     1.2847, 1.28666, 1.28647, 1.29923, 1.30116, 1.56112, 1.56282,
     1.29155, 1.2936}|>

A: Cause of speed up
This is definitely not memoization. The reason for the observed speed up is that for large arrays (e.g. 10^8 elements), the memory clean up operations may take noticeable time. If one doesn't free memory, one can perform some operations a bit faster.
Here is a simple example:
Let's create a large array, then perform a calculation, and remove the array:
AbsoluteTiming[
    Total[ConstantArray[0, 10^8]];
]

{0.422509, Null}

It takes 0.42 seconds. Let's now do the same thing, but keep the array in memory:
AbsoluteTiming[
    Total[garbage = ConstantArray[0, 10^8]];
]

{0.366755, Null}

This evaluation is a bit faster.
Let's check how long does it take to remove the large array:
AbsoluteTiming[
    Remove[garbage]
]

{0.061982, Null}

Note that 0.06 seconds is the difference of the calculation times above. This example shows that if we keep the large array instead of removing it, our code can run faster, because we don't need to spent time on freeing memory.
Your example
In the example you provide, removing the result of Unitize@data[[All, n]] from memory takes some time. If one saves this array in a redundant variable, one avoids immediate memory clean-up and the evaluation seems to be faster.
In case of pseudo-memoization the Clear[pick, unitize] command will take extra time to free the memory, but this command is placed outside the AbsoluteTiming[] scope. That is why "memoization" seems to speed up the calculation.
How to make a representative test?
You should put Clear[pick, unitize] inside your timing function.  This test will show that the pseudo-memoization technique is actually slower than built-in functions:
Table[
    Clear[data];
    data=RandomInteger[{0,10},{i*10^7,3}];
    {
        Pick[data,Unitize@data[[All,-1]],1]; // AbsoluteTiming // First
        ,
        Clear[pick,unitize];
        unitize[x_]:=unitize[x]=Unitize[x];
        pick[xs_,sel_,patt_]:=pick[xs,sel,patt]=Pick[xs,sel,patt];
        pick[data,unitize@data[[All,-1]],1]; // AbsoluteTiming // First
    },
    {i,5}]

(*
{{0.534744, 0.469538},
{1.03776, 1.05842},
{1.58536, 1.65404},
{2.10422, 2.11284},
{2.48129, 2.71405}}
*)

Technical note: as noted by Carl Woll in comments, if one wants to measure the symbol-removing-time using the following code:
In[1] := garbage = ConstantArray[0, 10^8];
In[2] := AbsoluteTiming[Remove[garbage]]

one should set $HistoryLength to zero, otherwise the Out[1] variable will retain the contents of the large array. If Out[1] retains the large data, Remove[garbage] will only delete the reference, but not the data itself. Deletion time of a reference is almost zero, but it doesn't correspond to the deletion time for large data.

A: You are absolutely correct that this memoization is completely unnecessary.
What seems to happens is that from the second run onwards on the same data, the builtin functions become faster.  I do not understand why (perhaps some internal caching), but it does show that it has absolutely nothing to do with the memoization:
In[38]:= AbsoluteTiming[Pick[data, Unitize@data[[All, n]], 1] // Length]
AbsoluteTiming[Pick[data, Unitize@data[[All, n]], 1] // Length]
AbsoluteTiming[Pick[data, Unitize@data[[All, n]], 1] // Length]

Out[38]= {10.6117, 90909421}

Out[39]= {8.08706, 90909421}

Out[40]= {7.96311, 90909421}

Another comment:
RandomSeed is an option, not a function. It should be SeedRandom, otherwise it does nothing.

A: What if let pick and unitize run before Pick and Unitize? pick is still faster than Pick.
In:
Clear[unitize, pick, n, data]
SeedRandom[1];
n = -1;
data = RandomChoice[Range[0, 10], {10^8, 6}];

unitize[x_] := unitize[x] = Unitize[x];
pick[xs_, sel_, patt_] := pick[xs, sel, patt] = Pick[xs, sel, patt]
AbsoluteTiming[
 pick[data, unitize@data[[All, n]], 1] // Length]
AbsoluteTiming[Pick[data, Unitize@data[[All, n]], 1] // Length]

Out:
{4.71476, 90911166}
{5.14919, 90911166}

Memoization
This technical is Memoization. I learned it from Haskell.
Memoization in GHC's interactive environment.(GHC=Glasgow Haskell Compiler)

The first execution time of add1 x is 0.73 seconds and the memory usage is 676MB memory, the second execution time of add1 x is 0.08 seconds, and the memory usage is only 86KB.
If you use this technique wisely, it can save a lot of CPU time and memory. In some worse scenarios, it might only save CPU time and use too much memory.


text:
Q: Couldn't install winexe-1.00, Python not found When I was installing winexe 1.00, after [winexe-1.00/source4/]./configure I got the following message:
checking for python2.6... /usr/local/bin/python2.6
checking for python2.6-config... /usr/local/bin/python2.6-config
checking working python module support... no
configure: error: Python not found. Please install Python 2.x and its development headers/libraries.

But I installed both Python 2.6 and 2.7. I couldn't find what's the problem.

A: just install python via yum or apt:
apt-get install python-all-dev

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error when trying to return True/False values to a definition in python def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True

    for i in range(2,x):
        if x % i == 0:
            return False
            break
        else:
            return True

The above code is mine from codecademy's python course, and i get a prompt telling me that when 9 is passed to the argument, the function returns True instead of False. I can fix this by doing:
    for i in range(2,x):
        if x % i == 0:
            return False
            break
    return True

I don't understand why the second bit of code works, and why the first bit doesn't. In fact, I would have thought the second bit of code wouldn't work: If the argument was 9, then when i == 3, x % i == 0. So the function gets a returned value of False, and the loop breaks. However, since the "return True" is NOT within the for loop, then after exiting the for loop, "return True" will execute anyway, so regardless of the input, the function will get returned a value of True, since that's the last line of code to be executed within the function?
Following that line of reasoning, I believed that my initial code would work, because if "return True" was within the for loop, then the break command would be executed (assuming the input was 9), AFTER the function has been returned a value of False. And since the "return True" line is within the the for loop, and since the break command will exit the for loop, then the last value given to the function would have been False, which would have been correct?
I apologise in advance if I have (very likely) misused certain terms, of have some flaw in my understanding of how the code works or is executed. I just can't seem to get my head around why the second bit of code works, but the first bit doesn't.
Cheers!

A: The for loop starts with i == 2. 9 % 2 == 1, so it goes into the else: branch, and returns True.
Only if the entire loop is run and none of the numbers divided 9 should you return True.
Also, following return ... by break is useless - the function has already returned, so that break statement is never reached.
That's also the answer to your last question -- when return is executed, this function ends. Nothing else is done anymore, and the program continues (returns to) wherever it was when it called the function.

A: The first version didn't work because , when ever the if condition is false it returns True.Thus, when x==9 and i==2, 9%2!=0, thus it returns true.  Also, no need to use break statement as return statement returns the value from function and loop doesn't continue after return.
Following is the correct code
def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True

for i in range(2,x):
    if x % i == 0:
        return False
return True


text:
Q: Unable to override ThemeData I want to have a different background color in MenuPage. I'm trying to override the themeData - I've followed the themeData tutorial from official flutter page but unable to get the result. do you guys have any suggestion?
void main() => runApp(MyApp());

final ThemeData _themeData = new ThemeData( // app theme
        scaffoldBackgroundColor: darkNavy,
        canvasColor: lightNavy,
        accentColor: lightNavy,
        primarySwatch: Colors.grey,
        appBarTheme: AppBarTheme(
            color: darkNavy,
            brightness: Brightness.dark,
            elevation: 10,
            iconTheme: IconThemeData(
              color: lightGrey,
            ),
            textTheme: TextTheme(
                headline6: GoogleFonts.crimsonPro(
                    color: darkGrey,
                    fontSize: 20,
                    fontWeight: FontWeight.w400))),

);

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: _themeData,
      home: HomeScreen(),
    );
  }
}

class MenuDashBoard extends StatefulWidget {

  @override
  _MenuDashBoardState createState() => _MenuDashBoardState();
}

class _MenuDashBoardState extends State<MenuDashBoard> {
  @override
  Widget build(BuildContext context) {
    return Theme(
        data: ThemeData(
              canvasColor: lightNavy,
              scaffoldBackgroundColor: lightNavy
            ),

      child: Scaffold(
        body: Container(
            padding: EdgeInsets.only(top: 30, bottom: 30, left: 20),
            child: Column(

My main homeScreen has a dark navy background i want to have a light navy in my Menu page.

A: You can use the attribute 'scaffoldBackgroundColor' in theme data, setting to the color you want With this, if you are using the scaffold widget, your background app will have the color you want. See:
MaterialApp(
   title: 'App',
   theme: ThemeData(
     scaffoldBackgroundColor: Colors.blue,
   ),
   home: YourScreen()
),


text:
Q: Predicate logic, models I'm trying to understand predicate logic and models.
I have an old exam question where we are supposed to find a model that shows that the formula does not hold:
$$
\exists x(P(x) \land \neg M(x)), \ \exists y(M(y) \land \neg S(y)) \vdash \exists z (P(z) \land \neg S(z))
$$
Solution: Consider the model $\mathcal{M}$ with universe $A = \{0,1\}$ and  $P^\mathcal{M} = S^\mathcal{M} = \{0\}$ and $M^\mathcal{M}=\{1\}$ and $l$ mapping all variables to $0$. ......more text
I know that $P^\mathcal{M} \subseteq A$. Same with the other predicates. And I suppose $l$ is a lookup-function, but why is it mapping all variables to zero? What is the meaning of that?
When we set $P^\mathcal{M} = \{0\}$, does this mean that $P^\mathcal{M}$ is only true when $x = 0$?

A: When we wet $P^\mathcal{M} = \{0\}$, we mean that, according to the model $\mathcal{M}$, $0$ is the only element of the universe that satisfies the predicate $P$. And similarly for the other predicates.
Your exercise asks to show that the formula $\exists z (P(z) \land \lnot S(z))$ is not a consequence of $\exists x (P(x) \land \lnot M(x))$  and $\exists y (M(y) \land \lnot S(y))$. This amounts to show that  there is a model $\mathcal{M}$ such that $\mathcal{M} \models \exists x (P(x) \land \lnot M(x))$ and $\mathcal{M} \models \exists y (M(y) \land \lnot S(y))$ but $\mathcal{M} \not\models \exists z (P(z) \land \lnot S(z))$, i.e., in $\mathcal{M}$, the formulas $\exists x (P(x) \land \lnot M(x))$ and $\exists y (P(y) \land \lnot S(y))$ are true but $\exists z (P(z) \land \lnot S(z))$ is false.
The model $\mathcal{M}$ you described is exactly what you are looking for, because $\mathcal{M} \models P(0) \land \lnot M(0)$ and $\mathcal{M} \models M(1) \land \lnot S(1)$, but $\mathcal{M} \not\models \exists z (P(z) \land \lnot S(z))$ since according to $\mathcal{M}$ all the elements of the universe that satisfy $P$ satisfy $S$ as well.
Note that the function $l$ mapping all variables to $0$ does not play any role in the exercise, since all the formulas involved in it are closed.


text:
Q: Minimum generalized variance for outlier detection I'm currently reading the paper Distribution of Variables by Method of Outlier Detection and am trying to understand the section on Minimum generalized variance
If my understanding is roughly correct, it basically starts off with no points and then adds points to a data-set. Each point is then assign a variance score. The further away the data point is from the median the more variance it accrues. The paper does a much better job at explaining it and is very accessible. My question is concerned with the section on cutoffs. For multi-variate outliers it uses the formula
$M_{G}+\sqrt{\chi_{0.975 . p}^{2}}\left(q_{3}-q_{1}\right)$
I understand the role of q1 and q2 but could anyone explain to me what the $\chi_{0.975 . p}^{2}$ in the section of the formula represents?

A: Comment:  Short answer: I don't really know. Explorations follow.
In the linked paper, it seems early on that $p$ is degrees
of freedom (or observations or dimensions). Then just after display (6) the author
seems about to define $\chi_{0.975,p}^2$ when the sentence
ends abruptly. At (7) this expression occurs again.
My guess is that this is the value that cuts probability 0.025 from
the upper tail of $\mathsf{Chisq}(\nu = p).$ Taking $p=2$ in (7)
this would lead to $\sqrt{\chi_{0.975,p}^2} = 2.716,$ which might make
sense in context. Computation in R:
sqrt(qchisq(.975, 2))
[1] 2.716203

However, a more common use of subscript notation with $\chi^2$
is that the probability in the subscript is cut from the lower tail of the distribution (a 'percentage point'). Then the quantity would be $0.225.$
sqrt(qchisq(.025, 2))
[1] 0.2250236

Note: The author quotes several well-known statisticians as being opposed
to the removal of outliers, unless traced to a specific mistake. Then
seems to ignore this advice with various suggestions for detecting and
removing inconvenient outliers from multivariate data.


text:
Q: XCode - I cannot seem to remove files from a project When i highlight a file and choose Edit->delete nothing happens.
What is going on. This is in the XCode IDE for Max OS

A: Try right clicking (two fingers, or cmd click) the file and selecting delete. It may be that edit>delete only works for code editing.


text:
Q: Get Employee Name from another table, by employee ID from input field in form I have an access database that i have gracefully been deemed responsible for.. I for the life of me cannot figure out how to do this simple relationship scenario..
Call Table
id - PKey Auto Inc
job_number
employee_id - Text -> links to UserInfo Linked SharePoint List Table
call_description

User Info Linked SharePoint Table
This table is readonly, a linked table from a SharePoint list..
id - PKey Auto Inc
employee_id
Name - Full name of employee

On the input form the call center tech will fill the form out, and enter the employee's ID number. Once they enter that i want it to show the employees name from the [UserInfo].[Name]  column in a textbox..
I tried using a DLookup function like so:
=DLookUp("[Name]","[UserInfo]"," [UserInfo]![Employee ID] =" & [Forms]![Call Entry]![employee_number])

but all i'm getting is #Error. the form's data source is set to the Call Table.

A: Look up the CompanyName field from table Company, where CompanyID = 874. This translates to:
=DLookup("CompanyName", "Company", "CompanyID = 874")

You don't want Company 874 printed for every record! Use an ampersand (&) to concatenate the current value in the CompanyID field of your report to the "Company = " criteria:
=DLookup("CompanyName", "Company", "CompanyID = " & [CompanyID])

If the CompanyID is null (as it might be at a new record), the 3rd agumenent will be incomplete, so the entire expression yields #Error. To avoid that use Nz() to supply a value for when the field is null:
=DLookup("CompanyName", "Company", "CompanyID = " & Nz([CompanyID],0))


text:
Q: How to pass block to sub method? Say I have the following code:
def a(n, m, &block)
  yield if block_given?
end

def a
  # My question is here. When a is called, block might be or might not be
  # given. Below line is obvious wrong. How to call b and properly pass
  # block to b?
  b(1, 2, &block)
end

a  # call a without block

a { # call a with a block
    puts "in block"
}

A: Write a() to accept a block. It is implied to be optional, and as Andrew Marshall noted, will be passed along as &nil if not given.
def b(n, m, &block)
  yield if block_given?
  puts "no block" if !block_given?
end

def a( &block )
  b(1, 2, &block)
end

a  # call a without block

a { # call a with a block
    puts "in block"
}

Output:
no block
in block


text:
Q: How to print the result from function (my extension of Codingbat question : Warmup-1 > near_hundred) I would just like to mention that i am very new to coding, i've begun with learning Python.
After completing a codingbat question I was trying to print the result (as per below), however it wasn't working for me. I would greatly appreciate if someone can please provide any help.
I understand that my solution can be written more simply however I'm still learning and the following made sense for me (and seeemed to work as well). I have tried some variations of the below however couldn't quite get it to work. I tried to have something like def near_hundred(input(n)) however that didn't really work. Also tried having print(near_hundred) at the bottom of the code and was unsuccessful.
n = input('Please enter number: ')
def near_hundred(n):
    if n in range (90,110) or n in range (190,211):
        return True
        print('this number is within range')
    else:
        return False
        print('this number is out of range')

A: You have to call your function. The function will do nothing until you use it
n = int(input('Please enter number: '))
def near_hundred(n):
    if n in range (90,110) or n in range (190,211):
        print('this number is within range')
    else:
        print('this number is out of range')

near_hundred(n)

A: Try using:
n = input('Please enter number: ')
def near_hundred(n):
    if n in range (90,110) or n in range (190,211):
        print('this number is within range')
    else:
        print('this number is out of range')
print(near_hundred(n))


text:
Q: easel JS security restrictions on localhost machine I'm learning EaselJS and I'm getting this weird error:

Unable to get image data from canvas because the canvas has been tainted by cross-origin data. easeljs-0.6.0.min.js:71
Uncaught An error has occurred. This is most likely due to security restrictions on reading canvas pixel data with local or cross-domain images.

The thing is, both my images are from localhost - I have them stored in my root directory. This is what my code looks like:
function init() {
    var canvas = document.getElementById("demoCanvas");
    var stage = new createjs.Stage(canvas);
    var im = new createjs.Bitmap("dbz.jpg");
        im.regX - im.image.width *.2;
        im.regY - im.image.height *.2;
    stage.addChild(im);
    stage.update();

    im.addEventListener("click", function() {
        var seed = new createjs.Bitmap("seed.jpg");
        stage.addchild(seed);
        stage.update();
    }); //end seed eventlistener

} //end function init()

A: EaselJS needs to read pixel values to determine mouse collision. I recommend using a local server like MAMP (osx) or XAMPP (win) to do local testing.
http://www.mamp.info/en/index.html
http://www.apachefriends.org/en/xampp.html
There are some good ones as well. Internally, we use Grunt for development, and it has a Connect module that provides the same functionality. It requires a bit more setup, but has a ton of other capabilities like code minification, sass compiling, browser auto-reload, etc.
http://gruntjs.com/
https://github.com/gruntjs/grunt-contrib-connect


text:
Q: Learndash groups content protection with tags Currently, I use learndash to lock courses and memberpress to lock posts/pages tagged "premium". Learndash provides the option to lock posts/pages with learndash groups. However, it only has the option to lock contents inside post editor by selecting individual courses/groups. How can I make learndash groups to protect posts/pages tagged premium so that I can deactivate memberpress and use only learndash?

A: Sorry for the late reply, you certainly not require the memberpress for these kind of controls.
Go to your quiz and under settings page you will see the following checkbox:
Only registered users can take this Quiz
After turning that ON, you will get the following message on the front-end:
You must sign in or sign up to start the quiz.
And it is obvious that registered users are only those, which actually purchase your course or you allow them with an identity.
Alternatively you can use another toolkit for these kind of toggles.
http://wordpress.org/plugins/toolkit-for-learndash-lms/


text:
Q: When trimming content it loses style I need help with Wordpress. I know that it prints content using get_the_content(); and the_content(); and etc.
The problem is that when it prints content with function the_content(); the text has styling, bold align and etc. but when I use get_the_content(); like this: wp_trim_words(get_the_content(), 100); it doesn't.
Is it possible to trim the_content(); so that content would be with styling?

A: Unfortunately, wp_trim_words is not going to do the work for you. That's simply because all tags are stripped $text = wp_strip_all_tags( $text ); before any result is returned.
For your purpose you are going to need a smart function that maintains HTML markup integrity. Luckily, I have found a function that does just that. Here's the blog that published it.
Use it like this: tuncateHtml(get_the_content(),100)
/**
 * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
 *
 * @param string $text String to truncate.
 * @param integer $length Length of returned string, including ellipsis.
 * @param string $ending Ending to be appended to the trimmed string.
 * @param boolean $exact If false, $text will not be cut mid-word
 * @param boolean $considerHtml If true, HTML tags would be handled correctly
 *
 * @return string Trimmed string.
 */
function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true) {
    if ($considerHtml) {
        // if the plain text is shorter than the maximum length, return the whole text
        if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
            return $text;
        }
        // splits all html-tags to scanable lines
        preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
        $total_length = strlen($ending);
        $open_tags = array();
        $truncate = '';
        foreach ($lines as $line_matchings) {
            // if there is any html-tag in this line, handle it and add it (uncounted) to the output
            if (!empty($line_matchings[1])) {
                // if it's an "empty element" with or without xhtml-conform closing slash
                if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
                    // do nothing
                    // if tag is a closing tag
                } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
                    // delete tag from $open_tags list
                    $pos = array_search($tag_matchings[1], $open_tags);
                    if ($pos !== false) {
                        unset($open_tags[$pos]);
                    }
                    // if tag is an opening tag
                } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
                    // add tag to the beginning of $open_tags list
                    array_unshift($open_tags, strtolower($tag_matchings[1]));
                }
                // add html-tag to $truncate'd text
                $truncate .= $line_matchings[1];
            }
            // calculate the length of the plain text part of the line; handle entities as one character
            $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
            if ($total_length+$content_length> $length) {
                // the number of characters which are left
                $left = $length - $total_length;
                $entities_length = 0;
                // search for html entities
                if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
                    // calculate the real length of all entities in the legal range
                    foreach ($entities[0] as $entity) {
                        if ($entity[1]+1-$entities_length <= $left) {
                            $left--;
                            $entities_length += strlen($entity[0]);
                        } else {
                            // no more characters left
                            break;
                        }
                    }
                }
                $truncate .= substr($line_matchings[2], 0, $left+$entities_length);
                // maximum lenght is reached, so get off the loop
                break;
            } else {
                $truncate .= $line_matchings[2];
                $total_length += $content_length;
            }
            // if the maximum length is reached, get off the loop
            if($total_length>= $length) {
                break;
            }
        }
    } else {
        if (strlen($text) <= $length) {
            return $text;
        } else {
            $truncate = substr($text, 0, $length - strlen($ending));
        }
    }
    // if the words shouldn't be cut in the middle...
    if (!$exact) {
        // ...search the last occurance of a space...
        $spacepos = strrpos($truncate, ' ');
        if (isset($spacepos)) {
            // ...and cut the text in this position
            $truncate = substr($truncate, 0, $spacepos);
        }
    }
    // add the defined ending to the text
    $truncate .= $ending;
    if($considerHtml) {
        // close all unclosed html-tags
        foreach ($open_tags as $tag) {
            $truncate .= '</' . $tag . '>';
        }
    }
    return $truncate;
}

A: I think what you are after is...
wp_trim_words( wpautop( get_the_content() ), 100);

So you are return what the_content() returns by using wpautop() which reenables the paragraphs etc...


text:
Q: Copy SAP hana table into Azure SQL database and get SQL Server can't be found I validated data factory and both source dataset and target dataset looks good and validated but as soon as I run pipeline and job hang on there and the error message as below.

Operation on target Copy data1 failed:
  ErrorCode=SqlFailedToConnect,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=Cannot connect to SQL Server database: 'tcp:mysqlserver2002.database.windows.net,1433', Database: 'mySampleDatabase', User: 'system'. Check the linked service configuration is correct, and make sure the SQL Server database firewall allows the integration runtime to access.
Source=Microsoft.DataTransfer.ClientLibrary
  Type=System.Data.SqlClient.SqlException
  Message=A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)
Source=.Net SqlClient Data Provider
  SqlErrorNumber=10060, Class=20, ErrorCode=-2146232060, State=0

Any idea and help will be appreciated
Thanks,

A: According you error message, the error happened in Source dataset, Data Factory don't have the permission to access the Source SQL database "mysqlserver2002.database.windows.net".
Please test the connection to the Source Azure SQL database like this:

If the connection failed, please check if you have opened the Allow Azure services and resources to access this server on Azrue SQL database firewall settings:

According my experience for this error, here are the solutions:

*

*Set Allow Azure services and resources to access this server to
yes

*Add the client ip(which we could get from the error message) to the
database firewall.

Another way, please Add a role assignment to Data Factory, then it will permission to access the database:

Hope this helps.


text:
Q: enter an if statement if multiple conditions are true in bash I am trying to enter an if/then statement only if these conditions are true:
if [ "$key1dtSec" -lt "$taSec" ] || [ "$key2dtSec" -lt "$taSec" ] && [[ ! -z "$user_lives_here" ]]; then

I want to enter the loop only if $key1dtSec OR $key2dtsec are true AND only if $user_lives_here has a value.
But the if/then statement gets executed even if $user_lives_here has a value. And I don't want that.
How can I ensure the if/then only happens if $user_lives_here has a value?

A: You can group your conditions with parenthesis inside the [[ / ]] operators:
if [[ ! -z "$user_lives_here" && ( "$key1dtSec" -lt "$taSec" || "$key2dtSec" -lt "$taSec" ) ]]

A: You need to wrap your OR || condition in parentheses:
if  ( [ "$key1dtSec" -lt "$taSec" ] || [ "$key2dtSec" -lt "$taSec" ] ) && [[ ! -z "$user_lives_here" ]]; then


text:
Q: How to capture console app output in Octopus custom PowerShell script? I simply created an console app with argument number check at the very beginning. And after the package is deployed, in the deployment PowerShell script part, I directly call this app with no argument to test the script. It seems Octopus just captures the exit code and show there is no output from the app captured in task log at all.
    static void Main(string[] args)
    {
        if (args.Length < 4)
        {
            Console.WriteLine("Invalid argument number");
            Environment.ExitCode = -1;
            return;
        }
    }

However, if I simply put "echo 'test'" or even just 'test' string in the script, the output was captured in Octopus deployment task log. Any idea what is the correct way to log console app in the script? Thanks.

A: Sorry, it is not fault of Octopus, It is actually the console app was built for .Net framework 4.6.1 but the tentacle server is only having 4.5.2. When I run the app on that server through remote desktop, it pops up error message saying 4.6.1 .Net framework is missing. Rebuild the app with 4.5.2 fixed this issue. However it was really hard to find this out because Octopus task log has nothing related to that. Hope this would help someone else in the future.

A: Create a file named "yourpowershellfile.ps1" or Create e deployment step "Run a script".
Try this powershell with OctopusDeploy,
$FullPath = "C:\MyFolder"
if ($OctopusEnvironmentName -ceq 'Development')
{
  Write-Host "Console app will be execute"
  & "$FullPath\yourconsolefile.exe" | Write-Host
  Write-Host "Console app execution has finied"
}

You should try "Write-Output" instead of "Write-Host" Review the Octopus deploy task log.

A: If you found this question because you really need to get the console output following executables run in your Octopus deployment steps you can use the following code. It took a bit of research to write the following function I happily re-use accross Octopus steps where I need the console output:
Function Invoke-CmdCommand{
    param(
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [ValidateScript({(Test-Path $_.Trim('"').Trim(''''))})]
        [string]$Executable,
        [string]$Parameters = '',
        [switch]$CmdEscape
    )
    BEGIN{
        Write-Verbose "Start '$($MyInvocation.Mycommand.Name)'"
        $nl = [Environment]::NewLine
        $exitCode = 0
        $cmdOutput = [string]::Empty
        # next line wrap string in quotes if there is a space in the path
        #$Executable = (Format-WithDoubleQuotes $Executable -Verbose:$([bool]($PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent)))
        $command = "{0} {1}" -f $Executable, $Parameters
        Write-Verbose "COMMAND: $command"
        $terminatePrompt = "/C" # https://ss64.com/nt/cmd.html
        $comSpec = $env:ComSpec

        if($CmdEscape.IsPresent){
            $command = "`"$command`""
            Write-Verbose "ESCAPED COMMAND: $command"
        }
    }
    PROCESS{
        $cmdResult = .{
            # script block exec: dot does not create local scope as opposed to ampersand
            .$comSpec $terminatePrompt $command '2>&1' | Out-String | Tee-Object -Variable cmdOutput
            return $LastExitCode
        }

        $exitCode = $cmdResult[$cmdResult.length-1]

        if($exitCode -ne 0){
          Write-Host "FAILED with ExitCode: $exitCode; ERROR executing the command:$nl$command$nl" -ForegroundColor Red
          Write-Host "ERROR executing the command:$nl$command" -ForegroundColor Yellow
        }else{
            Write-Host "SUCCESSFULLY executed the command:$nl$command$nl"
        }
    }
    END{
        if($Host.Version.Major -le 3){
        return ,$cmdOutput # -NoEnumerate equivalent syntax since it is not available in version 2.0
        }else{
            Write-Output -NoEnumerate $cmdOutput
        }
        Write-Verbose "End '$($MyInvocation.Mycommand.Name)'"
    }
}

USAGE:
Invoke-CmdCommand -Executable (Join-Path (Split-Path $env:ComSpec) ping.exe) -Parameters 'localhost'

OUTPUT:
Pinging localhost [::1] with 32 bytes of data:
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Reply from ::1: time<1ms
Ping statistics for ::1:
        Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
    Approximate round trip times in milli-seconds:
        Minimum = 0ms, Maximum = 0ms, Average = 0ms

A: We just add a Deploy.ps1 to the package, with the following code:
& .\MyCompany.Foo.Bar.exe 2>&1

Resources:
In the shell, what does " 2>&1 " mean?


text:
Q: How to replace value of variable within function in python 3 I am new to python, and I am likely over complicating this. I am having problem with values in variables within a function not being replaced. Instead, it seems to just be adding the new value to it. With this function, if you select 1 or 2, it is supposed to perform certain actions, if you select anything else, it is supposed to say that is not an option and have you try again. Here is the output if I select a wrong option before selecting a valid option:
Select Option

[1] Option 1
[2] Option 2

You selected Option 1
1
9
7
6

So instead of replacing the value of my variable to 1 and clearing previous values, it seems to just add to it. Here is my code:
def testfunc():

    testvar = input('Select Option\n\n[1] Option 1\n[2] Option 2\n\n    >')
    if testvar in ('1', 'Option 1', 'option 1'):
        print("\nYou selected Option 1")
    elif testvar in ('2', 'Option 2', 'option 2'):
        print("\nYou Selected Option 2")
    else:
        print("\n\nThat is not an option, please select another option")
        testfunc()
    print(testvar)

testfunc()

If I could have someone explain why its storing multiple values and how I can prevent this, I would really appreciate it. Thanks!

A: Your problem is that you use recursion to go back and get another value (the call to testfunc() within testfunc() itself).
If you enter an invalid value, it will call the function again, saving its current position (before the print) so it can return to there.
Then, when you finally enter a good value, it will eventually unwind the stack, printing out the invalid ones as you go.
You are better off using a loop for this sort of validation, something like:
def testfunc():
    ok = False
    while not ok:
        testvar = input('Select Option\n\n[1] Option 1\n[2] Option 2\n\n    >')
        if testvar in ('1', 'Option 1', 'option 1'):
            print("\nYou selected Option 1")
            ok = True
        elif testvar in ('2', 'Option 2', 'option 2'):
            print("\nYou Selected Option 2")
            ok = True
        else:
            print("\n\nThat is not an option, please select another option")

    print(testvar)

testfunc()


text:
Q: Procedure to restore site collection from a sql db of a different farm I need to restore a site collection from a SQL DB of a different farm. This SQL DB holds only a single site collection. Both (destination and source) farms are identical except that they are in different domains.
The documentation suggests that restoring SQL DB itself is enough for restore. Is it really the case or would I need to detach the content db before sql db restore and attach it back after restore? If so, why? or is there a standard way of achieving this?
Env: SP 2010 & SQL Server 2008 R2

A: things are as simple as you mentioned in your question. Here are the steps.

*

*You have to perform the SQL backup of the Content Database from Source Farm

*Move the back file to destination server(sql)

*Restore the Database on destination SQL Server

*now you have two options over here

*

*if you overwrite the destination  dB while restoring, then no need to attach it as it is already attached. You all set.

*but if you are restoring as a new db then attach the restored Content DB to your Destination farm web app.


text:
Q: How to get all validation regular expressions for a model field? I'd like to get all regular expressions (validators) corresponding to a model field to pass them to javascript (to validate on a client side).
However I can take all validators, but validators don't have regex field in validator.__dict__:
# from django.core.validators, URLValidator
class URLValidator(RegexValidator):
    regex = re.compile(
        r'^(?:http|ftp)s?://'  # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'  # domain...
        r'localhost|'  # localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|'  # ...or ipv4
        r'\[?[A-F0-9]*:[A-F0-9:]+\]?)'  # ...or ipv6
        r'(?::\d+)?'  # optional port
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)
    message = _('Enter a valid URL.')

    def __call__(self, value):
        ... # and so on

The code trying to collect the regular expressions for models.URLField:
def get_regexes( model_obj, name ):
    field = model_obj._meta.get_field_by_name( name )[ 0 ]

    # A list of all validators
    validators = field.validators

    # Each validator can have attrs: 'regex', or '<some>_regex'

    for valid in validators:
        print "# valid={0}".format( valid ) # the dict has not regex field
        print "# valid_dict={0}".format( valid.__dict__ ) # the dict has not regex field

        obj_fields = valid.__dict__

        regexes = []

        if 'regex' in obj_fields:
            regexes.append( obj_fields.regex )

        # check if there are another regexes

        for key, val in obj_fields.iteritems():
            if '_regex' in key:
                regexes.append( obj_fields[ key ] )

    return regexes

print get_regexes( User, 'url' )

'url is a usual URLField in User model class:
class User(AbstractBaseUser):
    email = models.EmailField(unique=True, db_index=True)
    name = models.CharField(max_length=64, db_index=True)
    surname = models.CharField(max_length=64, db_index=True)
    lname = models.CharField(max_length=64, db_index=True) # Отчество

    url = models.URLField()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

    class Meta:
        db_table = 'user'

So, my code outputs:
# valid=<django.core.validators.URLValidator object at 0x0202AB70>
# valid_dict={}
# valid=<django.core.validators.MaxLengthValidator object at 0x02158670>
# valid_dict={'limit_value': 200}

I see the validator objects but I can't realize where is the attribute regex (which is in the code of URLValidator).

A: Why are you bothering to writer server-side code to do this? If you want to validate URLs in the browser, write code in the browser to validate URLs.


text:
Q: Using different languages in one project I recently heard about the use of several different languages in a (big) project, I also read about famous services such as Twitter using Rails as frontend, mixed with some other languages, and Scala I think it was as backend.

*

*Is this common practice? Who does that?

*I'm sure there are disadvantages to this. I think that you will have problems with the different interpreters/compilers and seamlessly connecting the different languages. Is this true?

*Why is this actually done? For performance?

A: The question essentially comes down to Domain Specific Languages (DSLs). Sometimes one language is better suited for one part of the program, and another language for another program. The benefits (execution speed, or ease of development) often outweigh the drawbacks of mixing multiple languages.

*

*Is this common practice? Who does that?

Very common; I'd say nearly every large application is written in more than one language.
Consider the example of a game. The core engine is usually written in C or C++ for speed and low-level hardware access, but behaviour of objects and characters are scripted in a higher-level language like Lua.

*

*I'm sure there are disadvantages to this. I think that you will have problems with the different interpreters/compilers and seamlessly connecting the different languages. Is this true?

Yes, there is a certain amount of overhead to enable scripts to access the game objects and such.

*

*Why is this actually done? For performance?

Yes and no. If performance were not an issue, the entire game could be written in a scripting language. Some other reasons are:

*

*Speed of development; imagine the overhead if all the little objects and characters in a game like World of Warcraft were written in C++. The program would have to be compiled and restarted for every little change.

*Modularity; new objects can easily be downloaded and added/removed at runtime, and savvy users can even mod them.

*Portability; the same scripts will run unmodified on different platforms.

A: Consider the average web project, and how many languages it involves:
HTML, CSS, JavaScript/JQuery, Java, SQL/HSQL.
When each language is far better suited to the domain than the languages you're already using, toss another language in.
I've also had data-heavy programs with a web front end written in Java, but a back end (to actually crunch numbers) written in C, hosted on different servers, and so on.
And I've gotta say, don't model off of Twitter.  You're unlikely to have an idea that tons of people want that much, that has no built in profitability, that investors shower you at money for.  They're also absolutely terrible at the fit and finish in places; if you ever put your Gmail password in, odds are it was transmitted in the clear, for example, and for at least two years, you could friend people without their permission through the text message interface.  (Gah.)

A: I believe that in the case of Twitter it was performance related; Scala is quite a bit quicker than Ruby, and they use it to power their queue systems.
Aside from maintenance issues, using multiple languages together can help offset the downsides in each language. With Twitter, Ruby (on Rails) is great for running the frontend of their site, but it makes more sense to use a faster language to process the menial background tasks. Integration between the languages isn't difficult when it comes to queueing systems, as they can be entirely separate from the application itself and still perform their tasks correctly.

A: I have several projects with mixed languages
In one case i have some F# mixed with c# because f# allowed me to code a problem easier (and was a challenge)
other cases would be mixing silverlight and .net in the same project - they use different CLR
in other cases i have vb.net and c# when companies had programmers that use multiple languages - most people i work with can't read c ... any code done in that would probably be not in the best interests of the employer.
The major disadvantage is that everyone who works on the code needs to know all the languages.
It's not soemthing i do often, but really its about the tools for the job imo.
I wouldn;t say it is done for performance usually ... although i have linked to c++ dll's when i need something to be done very veyr fast (graphics algorithms before i could do any cuda) ... the decisions surrounding performance are greater than computation time. Allt he usual overheads like sdcalability, ease of reading still come into it.
Ie i think you can say its about performance as long as you dont limit performance to mean the speed o fthe programs execution

A: In a typical embedded application I write for the 8051, I have multiple languages involved:

*

*C - the bulk of the application is in C since it is much faster to write, but its easy to produce tight code that fits into 64k (or less) of code space.

*Assembly language - sometimes you can't get by with compiler generated code.  When every byte counts, assembly language rules.

*Perl - Several of my build tools are written in Perl.  A powerful, flexible, dynamic language like Perl makes it easy to work with ROM images, and handle many aspects of the build process.

*GNU make - Huh?  Yes, make is a language.  It is a declarative language (which is another category of language on par with "object oriented", "functional" and "imperative").  Make is the foundation of my build system.

I do this because I like to use the right tool for each job.  I must use C and assembler for the tiny 8 bit micro.  I use C as much as possible because I get more work done.  I use Perl to handle complex build related tasks, because it is more productive than C and more powerful and portable than bash.  I use GNU make as the foundation of my build because it is very well tailored for handling dependency relationships and makes it easy to create and maintain this metadata and apply it to my project build process--in other words: productivity.
The big disadvantage of this approach is the obvious one: understanding my app requires an engineer to understand C, assembly language, Perl and make.

A: Lots of projects are mixed language. One of the most commonly mixed-with languages is SQL, and it is showing a key feature of mixed-language projects: each language is focussing on the parts of the problem that it is good at, and compensating for the weaknesses of the other(s). In the case of SQL, it handles the relational database access, leaving other things (be it the GUI or the webservice or …) to other languages that are better at them. I'd go as far as to say that using a single language is almost like just using a hammer to make a house; yes, you need a hammer, but you need a bunch of other tools too.
I know of projects which use a mix of jQuery, Tcl, C, Fortran and SQL in the one project. (It's a web application, driven by a web server written in Tcl, with computational components in C and Fortran and a database accessed via SQL.)

A:
Is this common practice? Why is this actually done? For performance?

Yes.  People who do it are generally trying to reuse existing software (which you'll have noticed is written in multiple languages) or are trying to use several different languages, each one what it's good for.
Performance may sometimes be related; for example, I may want to use Lua for its rapid-prototyping abilities but connect it to a highly performant email parser written in C.

I think that you will have problems with the different interpreters/compilers and seamlessly connecting the different languages. Is this true?

Sometimes.  The state of practice in multi-language is roughly that if a language will talk to anything other than itself, it will talk to C.  So it's often possible to get things to work together through some sort of C-like interface.
Otherwise, the first problems typically surface either in memory management or in a VM layer, which we might consider examples of "managed code".  It's very hard to get a Haskell program to exchange heap-allocated objects with a JVM, for example.  A typically workaround is to treat these kinds of calls like remote procedure calls, just as if the programs were running in different processes or even on different machines.  Such calls can involve substantial overhead, often making it prohibitively expensive for two different languages to share mutable objects, for example.   If you don't have to mutate things, however, the overheads aren't so bad.
Summary: there are sound reasons to use different languages to solve different problems, and it would be surprising if a large software system did not use multiple languages (except maybe in single-language silos like Squeak Smalltalk, which simply don't talk to the rest of the world).  There are certainly difficulties with interoperability, but the problem is an old one and workarounds are known.


text:
Q: Entity Framework add row with id based on regex I've got two tables with a one to many relationship.
CREATE TABLE Super (
  SuperId VARCHAR(20) PRIMARY KEY
)

CREATE TABLE Sub (
  SubId VARCHAR(20) PRIMARY KEY,
  SuperId VARCHAR(20) FOREIGN KEY REFERENCES Super(SuperId)
)

What I'm trying to do is let the entity framework take care of generating the SubId based on a regex sequence. The db I'm working with has the SubId start with the SuperId. What comes after doesn't matter as long as it's unique.
INSERT INTO Super(SuperId) VALUES
('12345')

INSERT INTO Sub(SubId, SuperId) VALUES
('123451', '12345'),
('123452', '12345')

I'm looking to be able to do something like this:
Sub mySub = new Sub();
mySub.SuperId = 12345;

db.Sub.Add(mySub, mySub.SuperId + "*");

Where "*" is something unique.
I'm looking to get out of having to query the db in my code to generate a unique id. I know the entity framework can generate a unique id, but that's not what I'm looking for.
No big deal if that functionality isn't in there though. I just don't wanna keep querying the db to check if a key exists, but I will if I have to.


text:
Q: Calculating limit without using logarithms or exponentials Hello everyone I really need to calculate this limit without using $\ln$ or $\log$ or exponential function. Here it is:
$$\lim_{n\rightarrow\infty} \left[n\left(1-\frac1{\sqrt[n]x}\right)-n(\sqrt[n]x-1)\right]$$
where $n\in\mathbb{N}$ and $n\geq2$, $x\in\mathbb{R}$ and $x>1$
Thanks

A: Put $f_n(x)=x^{1/n}$. As $x>1$ there exists $c\in ]1,x[$ such that $\displaystyle f_n(x)-f_n(1)=\frac{1}{n}\frac{x-1}{c^{1-1/n}}\leq (x-1)/n$. So we have $0<n(x^{1/n}-1)\leq x-1$. Now your expression is $\displaystyle u_n=-n\frac{(x^{1/n}-1)^2}{x^{1/n}}$.
We have, as $x^{1/n}\geq 1$:
$$|u_n|\leq (x-1)\frac{x^{1/n}-1}{x^{1/n}}\leq (x-1)( x^{1/n}-1)\leq \frac{(x-1)^2}{n}$$
and we are done.

A: Hint: Write $x^{1/n} = 1+ a_n.$ Our expression equals
$$(1/x^{1/n} - 1)na_n.$$
You know $x^{1/n} \to 1.$ What can you say about $na_n?$


text:
Q: Linear algebra and Multivariable calculus prerequisites for Stochastic Calculus Which topics are considered "graduate-level" for the following subjects:

*

*Linear algebra

*Multivariable calculus

On Internet, it is said that you need "graduate level" Linear algebra and multi-variable calculus for understanding Stochastic calculus, but topics are not mentioned.

A: Basically, you need to understand the abstract properties of Linear Algebra, e.g. group theoretic properties, etc. This is in contrast to "undergraduate" Linear Algebra, which focuses primarily on computational aspects and some basic algebraic properties (e.g. rank-nullity theorem, etc.).
For graduate-level multivariable calculus, you need to understand rigorous proofs regarding integration and differentiation in $\Bbb R^n$, as well as analytic properties of differential forms. This differs from undergraduate multivariable calculus, which again is typically computational, and focuses on vector calculus and use of Green's/Stoke's Theorems, rather than their construction and proof.


text:
Q: Subquery in SQL with LOOP I am getting an error when trying to run a select statement in a PLSQL loop. How can I get it to work?
DECLARE
    v_gsp_cnt number := 0;
BEGIN
    WHILE v_gsp_cnt > (select max(eachesrem) from salesplan)
    LOOP
        insert into salesplanexp (select SPNUM,ORDNUM,DMDTYPE,ORDSTATUS,ITEM,LOC,ITEMDESCR,FCST,ORDTYPE,DELSERVLVL,SHIPMETHOD,CARRIER,EACHES,SHIPPEDEACHES,EACHESREM,WEIGHT,VOLUME,STARTSHIPDATE,ENDSHIPDATE,ACTSHIPDATE,STARTDELDATE,ENDDELDATE,ACTDELDATE,ORDCREATEDATE,ORDCONFDATE,BILLCUSTNAME,BILLADD1,BILLADD2,BILLCITY,BILLSTATE,BILLCOUNTRY,BILLZIP,SHIPCUSTNAME,SHIPADD1,SHIPADD2,SHIPCITY,SHIPSTATE,SHIPCOUNTRY,SHIPZIP,LOCPHONE,LOCEMAIL,ACTITEMCOST,ACTITEMPRICE,ACTITEMMARGIN,ACTSHIPCOST,ACTSHIPPRICE,ACTSHIPMARGIN,ACTTOTCOST,ACTTOTPRICE,ACTTOTMARGIN,BRAND,CHANNEL,EXTORDID,EXTLINEID,SOURCESYS,CREATEDATE,LASTUPDATEDDATE from salesplan);
        commit;
        select x.new_cnt into v_gsp_cnt from (select v_gsp_cnt+1 from dual) x;
        commit;
    END LOOP;
END;

The error is
ORA-06550: line 4, column 23:
PLS-00405: subquery not allowed in this context
ORA-06550: line 4, column 5:
PL/SQL: Statement ignored

The error, I believe, is from the select statement. But with the loop, I'm not sure another way to make it run properly

A: The error is coming from this line:
WHILE v_gsp_cnt > (select max(eachesrem) from salesplan)

the actual error is a bit deceiving, but that's the source (note it says "line 4" .. count from DECLARE).
You can't have a query like this in this place.
try this instead:
select max(eachesrem) into v_max from salesplan;

WHILE v_gsp_cnt > v_max

(and as well mentioned by JNevill:  you need to alias the inner "v_gsp_cnt+1" as new_cnt ... ) but that's a different error which will show up after you fix the one above. ;)


text:
Q: Extreme Laplacian eigenvalues For each undirected (and unweighted) graph $G$ we define the Laplacian matrix by $L(G) = D(G)-A(G)$, where $A(G)$ should denote the adjacency matrix and $D(G)$ the diagonal matrix, where $D(G)_{ii}$ denotes the degree of the $i$-th vertex of $G$ (after some ordering of the vertex set). We denote the eigenvalues of $L(G)$ by $\lambda_0 = 0 \leq \lambda_1 \leq \ldots$
If we consider the $n$-dimensional hypercube graph (see http://en.wikipedia.org/wiki/Hypercube_graph for more information), we obtain that the laplacian eigenvalues are $2i$ with multiplicity $\binom{n}{i}$ for $i=0,\ldots,n$. Hence, $\lambda_1 = 2$.
The graph has $n\cdot 2^{n-1}$ edges.
My question is now: Is there any method known to construct for increasing $n$ a graph $G$ with $2^n$ vertices and $n\cdot 2^{n-1}$ edges, where the $\lambda_1$ of $L(G)$ is bigger than 2 (the more the better)? And is there any estimate to these $\lambda_1$ then?
Furthermore, it would interest me to consider such a kind graphes $G$, where $\lambda_1$ is still bigger than 2, but the graph itself looks quite similar to the $n$-dimensional hypercube graph, but this is only optional.

A: Here is something which seems to work. Consider a circulant graph with vertices $v_0,\cdots,v_{2^n-1}$ and $v_i$ adjacent to $v_{i\pm d}$ where $d$ ranges over a set $D$ of  $\lceil\frac{n+1}{2}\rceil$ distances. For even $n,$ the distance $2^{n-1}$ is forbidden and the eigenvalues are $n-2\sum_D\cos(jd\omega)$ where $\omega=\frac{\pi }{2^{n-1}}$ and $j$ ranges from $1$ to $2^{n-1}.$ For $n$ odd, the distance $2^{n-1}$ is required and the eigenvalues are as before except that $\cos{j\pi}$ is subtracted only once.
This gives a whole class of easily examined graphs. I would expect that picking distances which allow any vertex to get to any other in relatively few steps would lead to a large second eigenvalue.
If I calculated correctly, then

*

*For $n=5$ we get $\lambda_1=2 $ with $D=\lbrace 1,4,16 \rbrace.$

*For $n=6$ we get $\lambda_1\approx 2.29637 $ with $D=\lbrace 1,7,18 \rbrace$

*For $n=7$  again $\lambda_1\approx 2.29637 $ is optimal using  $D=\lbrace 1,7,18,64 \rbrace.$

*The case $n=8$ was taking too long (with a naive program) but  the best value when  $D=\lbrace 1,7,a,b \rbrace$ is $\lambda_1 \approx 2.550198$  attained by $D=\lbrace 1,7,18,99 \rbrace.$

A: Let me turn the previous remarks into a tentative answer. Fix distinct primes $p,q$ and consider the Ramanujan graphs $X^{p,q}$ of Lubotzky-Phillips-Sarnak [A. Lubotzky, R. Phillips, P. Sarnak (1988). "Ramanujan graphs". Combinatorica 8 (3): 261–277]. These are $(p+1)$-regular graphs, which are Cayley graphs of $PSL_2(q)$ or $PGL_2(q)$ (depending on the Legendre symbol $(\frac{p}{q})$); at any rate $X^{p,q}$ has roughly $q^3$ vertices, and $\lambda_1(X^{p,q})\geq 2\sqrt{p}$ by the Ramanujan property.
So if you take $q$ of the order of magnitude of $2^{(p+1)/3}$, you get a $(p+1)$-regular graph on approximately $2^{p+1}$ vertices, with $\lambda_1(X^{p,q})\geq 2\sqrt{p}$. However these graphs are very far from the hypercubes: they have large girth, they have large chromatic number (unless they are bipartite), etc...


text:
Q: How can I go about creating a scrollable page content using arrow keys? I'm just experimenting around with HTML and JavaScript and I'm a bit stumped on how I can do this.
I want to create a page that can be scrolled using arrow keys on the keyboard or pressing a button to scroll to the next page.
The idea is to have the content spread out but by using the arrow keys it'll go to the next piece of content without reloading the web page. I've tried a few things including AngularJS but I'd rather have it hardcoded and not using a framework (unless it's extremely difficult without)

So you can see that there'd be an arrow button/arrow key pressed which would trigger the next page. Could this be done in multiple HTML files or would it be better doing it all in one file and having each page of content in different divs?
Once I'd figured that out I'd be looking to implement an animation so that when the arrow is pressed you can see the next page overlap the previous one.

A: Try something like this

var selected = 2;

window.onkeyup = function(e) {
  if (e.key == 'ArrowRight') {
    right();
  } else if (e.key == 'ArrowLeft') {
    left();
  }
}

function left() {
  var section1 = document.getElementById('1');
  var section2 = document.getElementById('2');
  var section3 = document.getElementById('3');

  if (selected == 2) {
    section1.style.left = '0vw';
    section2.style.left = '100vw';
    section3.style.left = '200vw';

    selected = 1;
  } else if (selected == 3) {
    section1.style.left = '-100vw';
    section2.style.left = '0vw';
    section3.style.left = '100vw';

    selected = 2;
  }
}

function right() {
  var section1 = document.getElementById('1');
  var section2 = document.getElementById('2');
  var section3 = document.getElementById('3');

  if (selected == 1) {
    section1.style.left = '-100vw';
    section2.style.left = '0vw';
    section3.style.left = '100vw';

    selected = 2;
  } else if (selected == 2) {
    section1.style.left = '-200vw';
    section2.style.left = '-100vw';
    section3.style.left = '0vw';

    selected = 3;
  }
}
body, html {
  margin: 0px;
  font-family: Arial;
  overflow: hidden;
}

.header {
  width: calc(100vw - 32px);
  height: 10vh;
  padding: 16px;
  background-color: black;
  color: white;
  font-size: 32px;
  text-align: center;
}

.scrollale {
  width: 100vw;
  height: calc(90vh - 32px); /* For the padding of the header */
  overflow: hidden; /* Remove the scroll bar from the bottom */
}

.scroll {
  position: absolute;
  top: 40vh;
  font-size: 48px;
  user-select: none;
  z-index: 10;
}

.scroll:hover {
  cursor: pointer;
  color: grey;
}

.left {
  left: 16px;
}

.right {
  right: 16px;
}

.section {
  position: absolute;
  width: 100vw;
  height: calc(90vh - 32px); /* For the padding of the header*/
  font-size: 72px;
  text-align: center;
  transition: 0.5s;
}

.part1 {
  left: -100vw;
}

.part2 {
  left: 0vw;
}

.part3 {
  left: 100vw;
}

Header

If the arrow keys don't work try clicking the buttons frist (to select it).
Edit
I the key detection method to use the key value which should be more consistent.


text:
Q: Intercept opening android setting of apps with BroadcastReceiver I declared in AndroidManifest permission and receiver
<uses-permission android:name="android.permission.REAL_GET_TASKS"/>

<receiver android:name=".UninstallIntentReceiver">
            <intent-filter android:priority="0">
                <action android:name="android.intent.action.QUERY_PACKAGE_RESTART" />
                <data android:scheme="package" />
            </intent-filter>
        </receiver>

And here is my java class receiver
public class UninstallIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    String[] packageNames = intent.getStringArrayExtra("android.intent.extra.PACKAGES");

    if(packageNames!=null){
        for(String packageName: packageNames){
            Log.d("User selected: ",packageName);
        }
    }
}

When I open settings of other apps it works well - I get notification
 (I can see in logs package name of chosen application), but
when I open settings my own application, I don't receive anything


text:
Q: how to change the email typing color when you type it in the input field how to change the email typing color when you type it in the input field
 <form action="">

                <input type="email" name="mail" id="" placeholder="Your Email">

            </form>

A: <form>
    <input type="email" name="email" placeholder="Your Email..." />
</form>

input {
    border: 2px solid black;
}
input.typed {
    border: 2px solid red;
}

const input = document.querySelector("input");
input.oninput = function () {
    if (input.value.length == 0) input.classList.remove("typed");
    else input.classList.add("typed");
};

Or if your looking for when its clicked and in focus you can use :focus like below:
input:focus {
    border: 2px solid blue;
}


text:
Q: Shows an output as Undefined in jquery val () attribute in flask template The below code shows an output as Undefined... but the value is displayed in alert box
$(document).on("click", ".open-homeEvents", function () {
  var eventId = $(this).data('id');
  alert(eventId); // It returns value as (1,2,3,...)
  $("input[name='bname']").val("{{business_field_data[" + eventId + "].business_name}}"); // Error eventId Undefined
 });

Can any one help me?

A: try this javascript code
$(document).ready(function() {
  "use strict";

  $(".open-homeEvents").on("click", function(e) {
    e.preventDefault();

    var eventId = $(this).data('id');
    console.log(eventId);

    // problem: see below
    $("input[name='bname']").val("{{ business_field_data[" + eventId + "].business_name}} ");

   ...

  });

})

you are mixing things, you can't evaluate javascript variables in jinja2 expression {{ .. }}.
jinja2 renders your template on the server-side and the HTML output is served to the client-side (the browser), whereas the javascipt (your code) manipulates the DOM of the received HTML on the client-side (the browser).


text:
Q: Go Live, Live Server, Vs Code Eu coloquei a extensão Live Server no meu VS Code para que a minha página de internet atualize automaticamente enquanto eu digite o meu código.
De vez em quando aparece o botão "Go Live" para que eu possa ligar o Live Server e de vez em quando não aparece o botão.
Alguém sabe como ligar o "Go Live" quando não aparece este botão ?

A: clique com o botão direito no arquivo html que você quer abrir e clique na opção "abrir com o Live server".
Caso essa opção nao apareça reinicie o VScode

A: Você pode usar os atalhos:
Alt+L ou Alt+O para começar o Live Server.
Abrir arquivos diretamente também pode fazer com que o botão não apareça, então procure abrir sempre a pasta do projeto.


text:
Q: How do i have a jar communicate with another jar Ok so i have 2 jars (Console, Core)
1st-Console) receives user input
2nd-Core) processes the input and gives an output
i'm trying to have the two "Communicate" with each other by exchanging input and output
now i have tried writing to a file to communicate when i ran into the problem of "Notifying" the other that there is input to receive and output to give
i'm a bit new to this ideal so if its an easy function, please don't criticize.

A: If you only have one process (which has nothing to do with having more than one Jar file), then you can simply use one Jar file in another.
But, if you are running your Jar files separately, then you have two different processes and what you need is Inter Process Communication which can be done in various ways:

*

*Remote Method Invocation(RMI): which allows a process to execute a function in another process in another address space

*Network Sockets: That allows you to send serialized data between various processes.


text:
Q: Android: Adding external library to project not working I am trying to add Jsoup library to my project, but I am getting an error in the program saying "Cannot resolve symbol 'Jsoup'". Below is what I have done, but not working.
1)From the Jsoup website, I downloaded the core library jsoup-1.10.2.jar
2)Dragged and dropped the .jar file under libs folder in my project
3)Under build.gradle in dependencies, I added the following line
compile files('libs/jsoup-1.10.2.jar')

4)In MainActivity.java file, I tried to add the following line
String url = "http://example.com";
try {
    Document document = Jsoup.connect(url).get();
    //more code here
}

Then, Jsoup turns red and says "Cannot resolve symbol 'Jsoup'".
Can anyone tell me what I am doing wrong? I visited many websites and watched a few tutorial videos and I followed them. But I am getting this error.

A: In the file build.gradle you should have the following:
dependencies {
    ...
    compile 'org.jsoup:jsoup:1.10.2'
    ...
}

You can see the instructions here, in Gradle section.


text:
Q: Can I use Google Mobile Vision API in IntelliJ IDEA or Atom IDE? I am exploring the APIs provided by Google. Firstly, I was experimenting with Google Cloud Vision API with Python in PyCharm in order to try to perform Optical Character Recognition (OCR) with various texts.
So I wrote a basic program in Python in PyCharm which was calling this API, I gave to it as an input an image which included text e.g. the image/photo of an ice-cream bucket and then the output was the text written on this bucket.
Now I want to test the barcode scanner of Google Mobile Vision API. ButGoogle Mobile Vision API is supported by Java and not Python so ideally I would like to call the Google Mobile Vision API in a Java program which calls this API, give as an input an image/photo of a barcode and take as an output the details saved in this barcode.
My question is if this can be (easily) done with IntelliJ IDEA or Atom IDE or if I should download Android Studio to do this simple task?
In other words, can I call easily call a mobile API in an IDE which is not specifically for mobile app development like Android Studio but it is for general java applications like IntelliJ IDEA or Atom IDE?

A: An API is just that: a programming interface.
Source code that you want to compile against that API only needs to see that API in the class path.
In other words: the editor you are using absolutely doesn't matter here.
The only thing that matters is that you understand how to efficiently setup a "project" that includes the JARs required for that API.
Meaning: Android studio is a powerful but complex tool. You typically use it for developing mobile android apps.
Just writing a java class that uses some kind of external API is not something that requires Android Studio. Or do you think you would need to use Visual Studio when going to experiment with a JAR originating from Microsoft?!
On the part "what would be easier" - that mainly depends on your knowledge of the tool.
If somebody knows Android Studio by heart, creating the required project setup might take 1 minutes. The same person might need 5 or 10 minutes with IntelliJ.
Having said that: of course, IntelliJ is primarily designed to work as Java IDE. So setting up new projects and adding the required setup to use some JAR libraries is a straight forward task here. Atom on the other hand is even "simpler" - it basically allows you to skip that "project" part and work directly on hierarchies defined by folders.
In any case: you simply have to do a bit of research and see what works for you. Like following this answer for atom, or this extensive guide for IntelliJ.


text:
Q: How can I animate my view resizing? I am resizing my tables headerView. I want to animate it, but I am not sure how.
-(void)layoutForBanner
{
    // Depending on if the banner has been loaded, we adjust the content frame and banner location
    // to accomodate the ad being on or off screen.
    // This layout is for an ad at the bottom of the view.
    if(banner.bannerLoaded)
    {
        headerView.frame = CGRectMake(0, 0, 320, 94);
    }
    else
    {
        headerView.frame = CGRectMake(0, 0, 320, 50);
    }

    [self.tableView setTableHeaderView:headerView];

}

A: This should do the trick.
[UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:.5];
    headerView.frame = CGRectMake(0, 0, 320, 50);
    [UIView commitAnimations];


text:
Q: Custom font iOS 8 not effect in device i am using Xcode 6.4 beta and i have issue with custom font

custom font ios 8 storyboard working but in device not working

A: Step 1: Include your fonts in your XCode project
Step 2: Make sure that the target you want to use your font in is checked under "Target Membership, double check that your fonts are included as Resources in your bundle
Step 3: Include your iOS custom fonts in your application plist
Step 4: Find the name of the font, the tricky part is that the font name may not be what you expect
for (NSString* family in [UIFont familyNames])
{
    NSLog(@"%@", family);

    for (NSString* name in [UIFont fontNamesForFamilyName: family])
    {
        NSLog(@"  %@", name);
    }
}

use above code to find the name
Step 5: Use UIFont and specify the name of the font
And finally, you can simply display your custom font using UIFont and whatever UILabel or text view you want.
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 60)];
label.textAlignment = NSTextAlignmentCenter;
label.text = @"Using Custom Fonts";
label.font = [UIFont fontWithName:@"Neutraface2Display-Titling" size:20];


text:
Q: Jersey and Google App Engine (GAE) not working for me I've seen some posts about this topic, but they didn't help me to find the issue. I'm trying to get Jersey 2.22 going with GAE SDK 1.9.25, but I keep getting 404.
The console says:
Nov 05, 2015 4:02:57 PM org.glassfish.jersey.server.ServerRuntime$Responder mapException
FINE: WebApplicationException (WAE) with no entity thrown and no ExceptionMappers have been found for this WAE. Response with status 404 is directly generated from the WAE.
javax.ws.rs.NotFoundException: HTTP 404 Not Found
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:323)

My class looks like this:
package com.jt.jjbackend;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/hello")
public class JJServlet {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHello(){
        return "Hello";
    }
}

and here is my web.xml:
<?xml version="1.0" encoding="utf-8" standalone="no"?><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <servlet>
        <servlet-name>jersey</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
             <param-name>com.sun.jersey.config.property.packages</param-name>
             <param-value>com.jt.jjbackend</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

I used http://localhost:8888/rest/hello which I think is correct, as I get a different error in the console when I enter a bogus link. I also added a regular test servlet which worked just fine.
What am I doing wrong or what am overlooking? Your help is much appreciated.
Stephan

A: Change com.sun.jersey.config.property.packages to jersey.config.server.provider.packages in your web.xml. The former is for Jersey 1.x, while the latter is for 2.x. They mean the same thing in their respective versions, but they are not interchangeable.


text:
Q: logrotate configuration file syntax - multiple wildcard entries possible? Since the man page doesn't answer my question and I don't want to force a rotation cycle, I decided to ask the question here.
The man page for logrotate gives the following example:
   "/var/log/httpd/access.log" /var/log/httpd/error.log {
       rotate 5
       mail www@my.org
       size 100k
       sharedscripts
       postrotate
           /usr/bin/killall -HUP httpd
       endscript
   }

All examples with wildcards contain only a single entry. Now, what I'm interested in is whether this one is also allowed:
   /var/log/httpd/*.log /var/log/httpd/*/*.log {
       # ... same as above
   }

Here's the reasoning: I have multiple vhosts and I split them up by the user that "owns" those vhosts. Since the log files are world-readable, I want to bind-mount a folder into the user home directory, but limit it to the log files that the user "owns", which is easiest achieved by separating the logs into folders (and bind-mounting requires that scheme anyway). So I'm looking for a solution to rotate both the log files under /var/log/httpd as well as all log files under subdirectories of that directory - without having to list each and every subdirectory by name.
In general the man page gives no clue whether multiple entries are at all possible for wildcard rules or only for full paths. I'm using logrotate version 3.7.8-6 which comes with Debian "Squeeze", but I reckon this is not necessarily specific to a distro or program version.

A: I just wanted to clarify, because that's what I got here looking how to do,
Multiple log files are allowed to be specified for a single config, eg
/var/log/httpd/access.log
/var/log/httpd/error.log
/var/log/httpd/mysite/*.log
{
    rotate 5
    mail nobody@example.org
    size 100k
    sharedscripts
    postrotate
        /usr/bin/killall -HUP httpd
    endscript
}

A: Yes, you can use multiple wild cards. You can test your file without performing the actual rotations by doing this:
logrotate -d -f /etc/logrotate.conf

*

*-d = Turns  on  debug mode.  In debug mode, no changes will be made to the logs or to the logrotate state file.

*-f = Tells logrotate to force the rotation, even if it doesn't  think
          this  is  necessary.   Sometimes this is useful after adding new
          entries to logrotate, or if old log files have been  removed  by
          hand,  as  the  new files will be created, and logging will con-
          tinue correctly.`

A: From man page for logrotate:

Note that  log  file  names  may  be enclosed in quotes (and that
  quotes are required if the name contains spaces).  Normal shell
  quoting rules apply, with ', ", and \ characters supported.

Please remember to modify or remove quotation marks when going from single to multiple patterns:
This works:
/var/log/*.log /var/log/*.blog {

this works too:
/var/log/*.log
/var/log/*.blog {

This does not work:
'/var/log/*.log /var/log/*.blog' {

and neither this:
"/var/log/*.log /var/log/*.blog" {

Compare with the single pattern case.
This works:
'/var/log/*.log' {

and this works too:
"/var/log/*.log" {

Tested with logrotate 3.10.0


text:
Q: Python Calculator Programming Errors def add(x,y):

  y = int( input("Enter First number "))
  x = int( input("Enter Second number "))
  answer = x + y
  print (answer)

def subtract(x,y):

  answer = x - y
  print (answer)
  y = int ( input("Enter First number "))
  x = int ( input("Enter Second number "))

operation = input("Subtract or Add ")

if operation == "add":

  add(x,y)

else:

  subtract(x,y)

I keep getting an error saying variables x and y aren't being used. Please help. I have been stuck on this for a while now.

A: You have problems with your scope. You can't call x or y before calling the function as those variables are declared inside the function. Do it once at a time. First you ask what function. Then once inside the function you ask for x and y
def add():

  x = int( input("Enter First number "))
  y = int( input("Enter Second number "))
  answer = x + y
  print (answer)

def subtract():

  x = int ( input("Enter First number "))
  y = int ( input("Enter Second number "))
  answer = x - y
  print (answer)

operation = input("subtract or add ")

if operation == "add":
  add()
else:
  subtract()

A: welcome to Stack Overflow and welcome to Python.
As you might know, in Python indents are really important, as they define which code belongs into which block.
Looking at your request, I must assume that this is a reflection of your code. So I think if you go with the following indentation, it might do what you want:
def add(x,y):
    answer = x + y
    return answer  # Please notice how i use RETURN to return a value from the function call

def subtract(x,y):
    answer = x - y
    return answer

y = int ( input("Enter First number "))
x = int ( input("Enter Second number "))

operation = input("Subtract or Add ")

result = None
if operation == "add":
    result = add(x,y)  # Please notice how I store what the function returns!
else:
    result = subtract(x,y)

if (result != None):
    print result
else:
    print "There is no result!"

Please read the comments and ask if you have any more questions.
Maybe you want to consider an elaborate introduction to Python

A: Your code has many problems and it is really confusing.

*

*as  ppperry commented, indentation .When writing python, you should use exact 4 space as indentation.

*you did not realize the difference between input and raw_input.
If you are using python2, and your input is not a number, input while try to eval your input. written in python doc.
If you are using python3, you do not need to worry about this because in python3 there is no more raw_input, and input equals old raw_input. This was asked here

*follow enpenax's answer. you should first define x and y  before you call them.