text:
Q: Python syntax for "if a or b or c but not all of them" I have a python script that can receive either zero or three command line arguments. (Either it runs on default behavior or needs all three values specified.)
What's the ideal syntax for something like:
if a and (not b or not c) or b and (not a or not c) or c and (not b or not a):

?

A: This returns True if one and only one of the three conditions is True. Probably what you wanted in your example code.
if sum(1 for x in (a,b,c) if x) == 1:

A: To be clear, you want to made your decision based on how much of the parameters are logical TRUE (in case of string arguments - not empty)?
argsne = (1 if a else 0) + (1 if b else 0) + (1 if c else 0)

Then you made a decision:
if ( 0 < argsne < 3 ):
 doSth()

Now the logic is more clear.

A: And why not just count them ?
import sys
a = sys.argv
if len(a) = 1 :
    # No arguments were given, the program name count as one
elif len(a) = 4 :
    # Three arguments were given
else :
    # another amount of arguments was given

A: If you don't mind being a bit cryptic you can simly roll with 0 < (a + b + c) < 3 which will return true if you have between one and two true statements and false if all are false or none is false.
This also simplifies if you use functions to evaluate the bools as you only evaluate the variables once and which means you can write the functions inline and do not need to temporarily store the variables. (Example: 0 < ( a(x) + b(x) + c(x) ) < 3.)

A: As I understand it, you have a function that receives 3 arguments, but if it does not it will run on default behavior. Since you have not explained what should happen when 1 or 2 arguments are supplied I will assume it should simply do the default behavior. In which case, I think you will find the following answer very advantageous:
def method(a=None, b=None, c=None):
    if all([a, b, c]):
        # received 3 arguments
    else:
        # default behavior

However, if you want 1 or 2 arguments to be handled differently:
def method(a=None, b=None, c=None):
    args = [a, b, c]
    if all(args):
        # received 3 arguments
    elif not any(args):
        # default behavior
    else:
        # some args (raise exception?)

note: This assumes that "False" values will not be passed into this method.

A: The question states that you need either all three arguments (a and b and c) or none of them (not (a or b or c))
This gives:
(a and b and c) or not (a or b or c)

A: I'd go for:
conds = iter([a, b, c])
if any(conds) and not any(conds):
    # okay...

I think this should short-circuit fairly efficiently
Explanation
By making conds an iterator, the first use of any will short circuit and leave the iterator pointing to the next element if any item is true; otherwise, it will consume the entire list and be False. The next any takes the remaining items in the iterable, and makes sure than there aren't any other true values... If there are, the whole statement can't be true, thus there isn't one unique element (so short circuits again). The last any will either return False or will exhaust the iterable and be True.
note: the above checks if only a single condition is set

If you want to check if one or more items, but not every item is set, then you can use:
not all(conds) and any(conds)

A: If you mean a minimal form, go with this:
if (not a or not b or not c) and (a or b or c):

Which translates the title of your question.
UPDATE: as correctly said by Volatility and Supr, you can apply De Morgan's law and obtain equivalent:
if (a or b or c) and not (a and b and c):

My advice is to use whichever form is more significant to you and to other programmers. The first means "there is something false, but also something true", the second "There is something true, but not everything". If I were to optimize or do this in hardware, I would choose the second, here just choose the most readable (also taking in consideration the conditions you will be testing and their names). I picked the first.

A: How about:
conditions = [a, b, c]
if any(conditions) and not all(conditions):
   ...

Other variant:
if 1 <= sum(map(bool, conditions)) <= 2:
   ...

A: The English sentence:

"if a or b or c but not all of them"

Translates to this logic:
(a or b or c) and not (a and b and c)

The word "but" usually implies a conjunction, in other words "and".  Furthermore, "all of them" translates to a conjunction of conditions: this condition, and that condition, and other condition. The "not" inverts that entire conjunction.
I do not agree that the accepted answer. The author neglected to apply the most straightforward interpretation to the specification, and neglected to apply De Morgan's Law to simplify the expression to fewer operators:
 not a or not b or not c  ->  not (a and b and c)

while claiming that the answer is a "minimal form".

A: If you work with an iterator of conditions, it could be slow to access. But you don't need to access each element more than once, and you don't always need to read all of it. Here's a solution that will work with infinite generators:
#!/usr/bin/env python3
from random import randint
from itertools import tee

def generate_random():
    while True:
        yield bool(randint(0,1))

def any_but_not_all2(s): # elegant
    t1, t2 = tee(s)
    return False in t1 and True in t2 # could also use "not all(...) and any(...)"

def any_but_not_all(s): # simple
    hadFalse = False
    hadTrue = False
    for i in s:
        if i:
            hadTrue = True
        else:
            hadFalse = True
        if hadTrue and hadFalse:
            return True
    return False

r1, r2 = tee(generate_random())
assert any_but_not_all(r1)
assert any_but_not_all2(r2)

assert not any_but_not_all([True, True])
assert not any_but_not_all2([True, True])

assert not any_but_not_all([])
assert not any_but_not_all2([])

assert any_but_not_all([True, False])
assert any_but_not_all2([True, False])

A: This question already had many highly upvoted answers and an accepted answer, but all of them so far were distracted by various ways to express the boolean problem and missed a crucial point:

I have a python script that can receive either zero or three command
line arguments. (Either it runs on default behavior or needs all three
values specified)

This logic should not be the responsibility of library code in the first place, rather it should be handled by the command-line parsing (usually argparse module in Python). Don't bother writing a complex if statement, instead prefer to setup your argument parser something like this:
#!/usr/bin/env python
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--foo', nargs=3, default=['x', 'y', 'z'])
args = parser.parse_args()

print(args.foo)

And yes, it should be an option not a positional argument, because it is after all optional.

edited:  To address the concern of LarsH in the comments, below is an example of how you could write it if you were certain you wanted the interface with either 3 or 0 positional args.  I am of the opinion that the previous interface is better style (because optional arguments should be options), but here's an alternative approach for the sake of completeness.  Note we're overriding kwarg usage when creating your parser, because argparse will auto-generate a misleading usage message otherwise!
#!/usr/bin/env python
import argparse

parser = argparse.ArgumentParser(usage='%(prog)s [-h] [a b c]\n')
parser.add_argument('abc', nargs='*', help='specify 3 or 0 items', default=['x', 'y', 'z'])
args = parser.parse_args()
if len(args.abc) != 3:
    parser.error('expected 3 arguments')

print(args.abc)

Here are some usage examples:
# default case
$ ./three_or_none.py
['x', 'y', 'z']

# explicit case
$ ./three_or_none.py 1 2 3
['1', '2', '3']

# example failure mode
$ ./three_or_none.py 1 2
usage: three_or_none.py [-h] [a b c]
three_or_none.py: error: expected 3 arguments

A: What about: (unique condition)
if (bool(a) + bool(b) + bool(c) == 1):

Notice, if you allow two conditions too you could do that
if (bool(a) + bool(b) + bool(c) in [1,2]):

A: When every given bool is True, or when every given bool is False...
they all are equal to each other!
So, we just need to find two elements which evaluates to different bools
to know that there is at least one True and at least one False.
My short solution:
not bool(a)==bool(b)==bool(c)

I belive it short-circuits, cause AFAIK a==b==c equals a==b and b==c.
My generalized solution:
def _any_but_not_all(first, iterable): #doing dirty work
    bool_first=bool(first)
    for x in iterable:
        if bool(x) is not bool_first:
            return True
    return False

def any_but_not_all(arg, *args): #takes any amount of args convertable to bool
    return _any_but_not_all(arg, args)

def v_any_but_not_all(iterable): #takes iterable or iterator
    iterator=iter(iterable)
    return _any_but_not_all(next(iterator), iterator)

I wrote also some code dealing with multiple iterables, but I deleted it from here because I think it's pointless. It's however still available here.

A: This is basically a "some (but not all)" functionality (when contrasted with the any() and all() builtin functions).
This implies that there should be Falses and Trues among the results. Therefore, you can do the following:
some = lambda ii: frozenset(bool(i) for i in ii).issuperset((True, False))

# one way to test this is...
test = lambda iterable: (any(iterable) and (not all(iterable))) # see also http://stackoverflow.com/a/16522290/541412

# Some test cases...
assert(some(()) == False)       # all() is true, and any() is false
assert(some((False,)) == False) # any() is false
assert(some((True,)) == False)  # any() and all() are true

assert(some((False,False)) == False)
assert(some((True,True)) == False)
assert(some((True,False)) == True)
assert(some((False,True)) == True)

One advantage of this code is that you only need to iterate once through the resulting (booleans) items.
One disadvantage is that all these truth-expressions are always evaluated, and do not do short-circuiting like the or/and operators.


text:
Q: PC to MAC Ethernet LAN I'm trying to setup VNC between a (Windows XP) PC and a MAC (OS X) for semi-permanent installation in a space, but I can't even get the PC to ping the mac. I've got an ethernet cable running between my PC and my Mac, firewall is disabled on the PC. Is there some windows setting that would block outgoing TCP connections? Static IP addresses are set on both machines. (This system will never be connected to the internet so no worries on security). I intend to use Vineserver and RealVNC once I get around this issue.

A: I had the two machines on different subnet masks, they are now connecting.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL Server Default value for columns When you use default value for a column in SQL Server Management Studio table designer, SSMS change your default and stand Parenthesis around of that (In all editions and all versions of SQL Server). For example if you set 0 as default value, this default changed to (0). I don't know why sql server use parenthesis, and is there a practical reason.
Thanks in advance.

A: There are certain types of objects, such as DEFAULTs and CHECK constraints that SQL Server doesn't store the original, textual form of - in contrast with, say, stored procedures, where you can (absent encryption) always retrieve it in the exact form you gave it to the server - complete with any white space, formatting, comments, etc.
Because SQL Server doesn't store the textual form, it always has to re-generate textual forms to show to users when they ask for such objects. When and where it chooses to insert parentheses can be a bit of a mystery (it's not documented) but since they don't change the meaning of the expression, they shouldn't be a concern.

A: Actually, 0 and (0) will evaluate to the same result, so there is nothing to really overcome. Ignore it. It's just how SQL stores them internally and a visibility issue.
It does that is you do it interactively as well. Not sure why does this , but not to worry.


text:
Q: Implement a multimodel control system I am asking you how would i be able to implement a multimodel system using RC filters.I need a nonlinear model and my teacher told me to use RC filters.By using  a RC filter i get a first order system and i would need a switch that would add to the circuit another RC filter which would make the system a second order.
I would then use my development board and implement 2 PID controls that would commute depending on the situation.
I am not sure about the electrical design still.
Any ideas?


text:
Q: How to monitor system audio with js Using code below I'm able to generate array with frequences based on audio element (which "plays" audio from file), but what I want to do is to generate this array for system audio - the thing that speakers play for example for the sound that is played by another program.
AUDIO=document.getElementById("myHtmlAudioElement");
audioCtx = new AudioContext();
analyser = audioCtx.createAnalyser();
source = audioCtx.createMediaStreamSource(AUDIO);
source.connect(analyser);
source.connect(audioCtx.destination);
function getData(){
    return new Uint8Array(analyser.frequencyBinCount);
}


text:
Q: Discrete maths proving a random observation Suppose you had 6 points. Each point can choose to either visit another point, or choose not to visit another point. However, it can't visit itself. In addition, visiting another point works in both directions; if point 1 visits point 2, that implies point 2 visits point 1.
I want to prove that for any arrangement, either A) there is a group of 3 points that have each visited each other or B) there is a group of 3 points that have not visited each other.
I've convinced myself its true by drawing a bunch of random hexagons, but exactly how do I go about proving this?

A: You can use the following table:
 Number of singles | Number of doubles | Number of triples | Implies
-------------------|-------------------|-------------------|---------
         6         |         0         |         0         |    B
-------------------|-------------------|-------------------|---------
         4         |         1         |         0         |    B
-------------------|-------------------|-------------------|---------
         3         |         0         |         1         |   A,B
-------------------|-------------------|-------------------|---------
         2         |         2         |         0         |    B
-------------------|-------------------|-------------------|---------
         1         |         1         |         1         |   A,B
-------------------|-------------------|-------------------|---------
         0         |         3         |         0         |    B
-------------------|-------------------|-------------------|---------
         0         |         0         |         2         |    A

Where:

*

*Single means an unvisited point

*Double means a group of $2$ points which visit each other

*Triple means a group of $3$ points which visit each other

Obviously, cases of $4$ or $5$ or $6$ points visiting each other, imply A (and possibly B).

Another way to show it is by depicting all possible ways to write $6$ as a sum of positive integers:

*

*$1,1,1,1,1,1 \implies   B$

*$1,1,1,1,2   \implies   B$

*$1,1,1,3     \implies A,B$

*$1,1,2,2     \implies   B$

*$1,2,3       \implies A,B$

*$2,2,2       \implies   B$

*$3,3         \implies A  $

*$4,1,1       \implies A,B$

*$4,2         \implies A  $

*$5,1         \implies A  $

*$6           \implies A  $

A sum that contains a value of $3$ or more implies A.
A sum that contains $3$ or more elements implies B.
Since any sum must be either one or both of those, A and/or B always hold.
This is because any sequence of positive integers whose sum is equal to $N$, either contains a value equal to or greater than $\lceil\sqrt{N}\rceil$, or contains a number of elements equal to or greater than $\lceil\sqrt{N}\rceil$.

A: There are two cases:
a. Assume that there is a point $v$ that connected to 3 or more other points
say $v_1,v_2,v_3$. if a pair of the points $v_1,v_2,v_3$ is connected (say $v_1,v_2$) then you have a $3$ points which are connected. If not, then the points $v_1,v_2,v_3$ do not visit each other.
b. Assume that there is no point which is connected to three other points. Take a point $v$. Then she is not connected to at least $3$ other points, say $v_1,v_2,v_3$. If a pair of the points $v_1,v_2,v_3$ is not connected (say $v_1,v_2$) then you have a $3$ points which are not connected. If not, then the points $v_1,v_2,v_3$ are all connected.


text:
Q: Using different assets for a different namespace in Rails 4 I have a Rails 4 app that uses the assets in app/assets/javascripts and app/assets/stylesheets throughout the application. However, I have made a nested resource for the admin portion of the app. I'd like for the admin interface to differ from what the end-user sees (different layout, different assets).
I tried changing the following in my application.css file:
*= require_tree .

to
*= require_directory

but the entire app still seems to be using the same resources. Could anyone please illuminate me on how to use different assets for different portions of a Rails 4 app?

A: The problem here is not how you're including files in your assets manifests, just that you're using the same manifest for the public and private/admin parts of your application.
You should create a new file called app/assets/stylesheets/admin.css and include within it the assets you require for your admin layout. Perhaps something like this:
*= require_tree ./admin

And then change your existing application.css not to use require_tree . but rather something more specific, such as this:
*= require_tree ./main

And move all of your public CSS files into that directory within your stylesheets directory.
Finally, you need to create a new layout for your admin pages, or modify the application layout such that the stylesheet and javascript includes are dynamic based on which part of the application you're using.
For simplicity you might want to just go with a new layout for the admin section, called app/views/layouts/admin.html.erb and then update any controllers for the application pages to use layout :admin.

A: I know the three combinations
 *= require_tree . # for base asset directory
 *= require_tree ./path # a specific path
 *= require filename # some file


text:
Q: Typescript: Generic Component Discriminating Between Different Input Props I have an enum with two members,
enum Step {
  ONE = "StepOne",
  TWO = "StepTwo"
}

each of which are assigned to a property, step in a discriminating union
type Props =
  | { type: Step.TWO; headline: string }
  | { type: Step.ONE; headline: string[] };

There is a generic component that takes props of either shape in the union and returns a matching component from a "componentMap", object
const Component = <T extends Step>(props: Extract<Props, { step: T }>) => {
  const compMap = { StepOne, StepTwo };

  // This works but I don't want to need to cast Comp
  // const Comp = compMap[props.type] as React.ComponentType<any>;

  const Comp = compMap[props.step];

  return <Comp {...props} />;
};

If I cast compMap[props.step] as React.ComponentType<any> (or as React.FunctionComponent<any> etc) I don't have a type error, but I'd like to not need to do this.
The specific error I get when not casting compMap[props.step] is:
Type '{ step: T; } & { step: Step.TWO; headline: string; }' has no properties in common with type 'IntrinsicAttributes'

So theres a mismatch happening somewhere...
Is there a way to correctly type this Component function so that it can infer the appropriate component it is meant to return?
Here is a codesandbox with an example of the implementation for context

A: I don't see why you've chosen to make the call signature of Component generic; the input is of type Props and the output is of type JSX.Element.  Since the T parameter appears only once, there's no useful distinction from the caller's side between <T extends Step>(props: Extract<Props, { step: T }>) => ... and (props: Props) => ....
You might hope that the implementation of Component would find the extra type information useful, but unfortunately it does not.  Nothing stops T from being the full union Step, and therefore props could be of type Extract<Props, {step: Step}>, i.e, just Props.  So T is not being helpful in the implementation either.  (See microsoft/TypeScript#24085 and microsoft/TypeScript#27808 for open feature requests related to narrowability of generic type parameters.)
Therefore, I'll switch to a non-generic function signature (props: Props) => JSX.Element from here on out.

I think the only way you will be able avoid a type assertion is by explicitly walking the compiler through the different possible Props cases.  This will allow control flow analysis to take place:
const Component = (props: Props) => {
    return props.step === Step.ONE ? <StepOne {...props} /> : <StepTwo {...props} />;
};

That is, unfortunately, redundant.  It certainly doesn't scale if you've got StepNinetySeven.

It would be nice if the compiler could just understand that compMap[props.step] will always be able to accept props; but this would require support for what I've been calling correlated types, and there isn't any such support now.  See microsoft/TypeScript#30581 for a feature request around this.  Without being able to keep track of correlations between different union-typed values, the compiler only sees that compMap[props.step] is of type StepOne | StepTwo while props is of type { type: Step.TWO; headline: string } | { type: Step.ONE; headline: string[] }.  The compiler treats these as uncorrelated or independent; for all it understands, compMap[props.step] might be StepOne while props is of type {type: Step.TWO; headline: string }.  So you get an error.
If you don't want redundant code, you currently have no choice but to use a type assertion to tell the compiler not to fret about the "wrong" pairings of compMap[props.step] and props.  This is giving up some type safety (the compiler no longer will catch certain errors).  You can do this with any, as you've done, which is the easiest.  More complicated is to take a union-of-functions and narrow it to a single function that accepts a union-of-its-parameters:
type UnifyFunctions<F extends (...args: any) => any> =
    (...x: Parameters<F>) => ReturnType<F>;

const Component = (props: Props) => {
    const compMap = { StepOne, StepTwo };
    const Comp = compMap[props.step] as
      UnifyFunctions<typeof compMap[keyof typeof compMap]>;
    return <Comp {...props} />;
}

That pretends Comp will be happy with either of the two types of props, and thus {...props} is accepted; it's less unsafe than any, at least.

Playground link to code


text:
Q: C4251 warning is not produced if export member functions only Such class declaration produces warning C4251 when compiled in DLL, because std::vector<int> is header-only and doesn't have a dll-interface:
#ifdef IS_DLL
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __declspec(dllimport)
#endif

#include <vector>

class EXPORT Foo
{
public:
    Foo();
    ~Foo();
private:
    std::vector<int> m_vec;
};

But the following declaration doesn't produce any warnings:
class Foo
{
public:
    EXPORT Foo();
    EXPORT ~Foo();
private:
    std::vector<int> m_vec;
};

For me it's unclear why warnings are not generated in the second case (or, on the contraty, generated in the first case), because
1) m_vec in both examples is private so there is no possibility to access it from client code, if using correct headers (or the access is possible in both cases if use hacked headers where private is replaced by public).
2) In both cases dumpbin /exports command shows that only methods are exported. Output for the first version (export of the whole class):
1    0 00001000 ??0Foo@@QAE@ABV0@@Z = ??0Foo@@QAE@ABV0@@Z (public: __thiscall Foo::Foo(class Foo const &))
2    1 00001040 ??0Foo@@QAE@XZ = ??0Foo@@QAE@XZ (public: __thiscall Foo::Foo(void))
3    2 00001060 ??1Foo@@QAE@XZ = ??1Foo@@QAE@XZ (public: __thiscall Foo::~Foo(void))
4    3 00001020 ??4Foo@@QAEAAV0@ABV0@@Z = ??4Foo@@QAEAAV0@ABV0@@Z (public: class Foo & __thiscall Foo::operator=(class Foo const &))

and the second version (methods only):
1    0 00001000 ??0Foo@@QAE@XZ = ??0Foo@@QAE@XZ (public: __thiscall Foo::Foo(void))
2    1 00001020 ??1Foo@@QAE@XZ = ??1Foo@@QAE@XZ (public: __thiscall Foo::~Foo(void))

Could you please explain the difference between two cases and give a small example in which for the first case we have an error while for the second case everything is fine (if follow the warnings logic)?


text:
Q: Google Analytics Page Load Times vs Pingdom Page Load Times. I am examining the page load time numbers in GA and Pingdom. My avg via pingdom is consistently 3 seconds, or around that. My page load time in GA is consistently around 10 seconds. Can anyone explain the technical reason for this difference. Please.
Any Reference to this information would be helpful, I haven't been able to find a straight answer.

A: This is an old question, and you've probably moved on, but Pingdom only tests the response time from the server (how long it takes the server to return a 200, 4XX or 5XX status), not even the time to receive the HTML doc; while Google Analytics shows the load time of the entire page, including all content and every asset loaded.


text:
Q: Complex matrices and sets question I'm having some problems answering a question set for my undergrad maths course. The question is:

Find the set $S=\left\{(x,y)\in\mathbb C\times\mathbb C:\begin{pmatrix}x&i\\iy&0\end{pmatrix}A^ T=\begin{pmatrix}0&0\\0&i+1\end{pmatrix}\right\}$
  where $A=\begin{pmatrix}1+i&-1\\1&-i\end{pmatrix}$.

I evaluated $\begin{pmatrix}x&i\\iy&0\end{pmatrix}A^ T$ to equal $\begin{pmatrix}(1+i)x-i&x-i\\(-1+i)y&iy\end{pmatrix}$ but $(1+i)x-i$ and $x-i$ cannot both equal $0$?
Obviously i'm doing something wrong but my tutors aren't much help.
*Edit - the question was 'fixed' to

Find the set $S=\left\{(x,y)\in\mathbb C\times\mathbb C:\begin{pmatrix}x&i\\iy&0\end{pmatrix}^TA^ T=\begin{pmatrix}0&-5i\\i&2i\end{pmatrix}\right\}$

but I still can't solve it?

A: Actually, $$\begin{pmatrix}x & i\\iy & 0\end{pmatrix}A^T=\begin{pmatrix}x & i\\iy & 0\end{pmatrix}\begin{pmatrix}1+i & 1\\-1 & -i\end{pmatrix}=\begin{pmatrix}(1+i)x-i & x+1\\(-1+i)y & iy\end{pmatrix},$$
but in any case, there is no $x$ or $y$ that satisfies the given conditions. Hence, $S=\emptyset.$

A: As $\det(A)=(2-i)\ne0$, $A$ is invertible. Hence the defining equation of $S$ is equivalent to
$$
\underbrace{\pmatrix{x&i\\ iy&0}}_M
= \underbrace{\pmatrix{0&0\\ 0&i+1}}_B\ (A^\top)^{-1}.\tag{1}
$$
Since the first row of $B$ is zero, the first row of $B(A^\top)^{-1}$ must be zero too. Yet the $(1,2)$-th entry of $M$ is nonzero, hence $(1)$ cannot be satisfied regardless of the value of $x$. Therefore $S$ is empty.


text:
Q: Merge successive descendant nodes into one XML:
<t>
  <ScreenSize>
    <Width>1440</Width>
    <Height>900</Height>
  </ScreenSize>
  <ConfigurationHotSpots>
    <Rectangle>
      <Location>
        <X>0</X>
        <Y>0</Y>
      </Location>
      <Size>
        <Width>50</Width>
        <Height>50</Height>
      </Size>
      <X>0</X>
      <Y>0</Y>
      <Width>50</Width>
      <Height>50</Height>
    </Rectangle>
  </ConfigurationHotSpots>
</t>

Desired Output XML:
<t>
  <ScreenSizeWidth>1440</ScreenSizeWidth>
  <ScreenSizeWidth>900</ScreenSizeWidth>
  <ConfigurationHotSpotsRectangleLocationX>0</ConfigurationHotSpotsRectangleLocationX>
  <ConfigurationHotSpotsRectangleLocationY>0</ConfigurationHotSpotsRectangleLocationY>
  <ConfigurationHotSpotsRectangleSizeWidth>50</ConfigurationHotSpotsRectangleSizeWidth>
  <ConfigurationHotSpotsRectangleSizeHeight>50</ConfigurationHotSpotsRectangleSizeHeight>
  <ConfigurationHotSpotsRectangleX>0</ConfigurationHotSpotsRectangleX>
  <ConfigurationHotSpotsRectangleY>0</ConfigurationHotSpotsRectangleY>
  <ConfigurationHotSpotsRectangleWidth>50</ConfigurationHotSpotsRectangleWidth>
  <ConfigurationHotSpotsRectangleHeight>50</ConfigurationHotSpotsRectangleHeight>
</t>

Rules:

*

*For every element in a defined nodeset (in this case <ScreenSize> | <ConfigurationHotSpots>), do the following: process all leaf descendants (i.e., those without children) such that a new element is created; the name of this new element should be the concatenation of all elements between the current node and the childless descendant.

*There is a variable number of these "blocks" throughout the document, so no manual templates (i.e., one that processes only descendants of <ScreenSize>, one that processes only descendants of <ConfigurationHotSpots>, etc.)

What I Currently Have:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
  <xsl:output omit-xml-declaration="no" indent="yes" />
  <xsl:strip-space elements="*" />

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="ScreenSize|ConfigurationHotSpots">
    <xsl:apply-templates select="descendant::*[not(*)]" mode="descendants" />
  </xsl:template>

  <xsl:template match="*" mode="descendants">
    <xsl:element name="{concat(name(ancestor::*[not(self::t)]), name())}">
      <xsl:apply-templates />
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>

The problem seems to be the name(ancestor::*[not(self::t)]) portion; it's not doing what I would like it to be doing (magically outputting the names of those elements, one after another). Instead, this is what I get:
<?xml version="1.0" encoding="UTF-8"?>
<t>
  <ScreenSizeWidth>1440</ScreenSizeWidth>
  <ScreenSizeHeight>900</ScreenSizeHeight>
  <ConfigurationHotSpotsX>0</ConfigurationHotSpotsX>
  <ConfigurationHotSpotsY>0</ConfigurationHotSpotsY>
  <ConfigurationHotSpotsWidth>50</ConfigurationHotSpotsWidth>
  <ConfigurationHotSpotsHeight>50</ConfigurationHotSpotsHeight>
  <ConfigurationHotSpotsX>0</ConfigurationHotSpotsX>
  <ConfigurationHotSpotsY>0</ConfigurationHotSpotsY>
  <ConfigurationHotSpotsWidth>50</ConfigurationHotSpotsWidth>
  <ConfigurationHotSpotsHeight>50</ConfigurationHotSpotsHeight>
</t>

Thanks in advance!

A: Doing name(ancestor::*[not(self::t)]) will not return a list of names, but just the name of the last one it matches (or is it the first?).
A slightly different approach you can take, not that far off from what you are currently doing, is rather than jumping straight to the 'leaf' element, match each level in turn, but keep a running concatenation of the element names, which are passed from one level to anoter by parameters.
Try this XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="ScreenSize|ConfigurationHotSpots">
        <xsl:apply-templates mode="descendants">
            <xsl:with-param name="name" select="local-name()" />
        </xsl:apply-templates>
    </xsl:template>

    <xsl:template match="*" mode="descendants">
        <xsl:param name="name" />
        <xsl:apply-templates mode="descendants">
            <xsl:with-param name="name" select="concat($name, local-name())" />
        </xsl:apply-templates>
    </xsl:template>

    <xsl:template match="*[not(*)]" mode="descendants">
        <xsl:param name="name" />
        <xsl:element name="{concat($name, local-name())}">
            <xsl:value-of select="." />
        </xsl:element>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

When applied to your sample XML, the following is output
<t>
   <ScreenSizeWidth>1440</ScreenSizeWidth>
   <ScreenSizeHeight>900</ScreenSizeHeight>
   <ConfigurationHotSpotsRectangleLocationX>0</ConfigurationHotSpotsRectangleLocationX>
   <ConfigurationHotSpotsRectangleLocationY>0</ConfigurationHotSpotsRectangleLocationY>
   <ConfigurationHotSpotsRectangleSizeWidth>50</ConfigurationHotSpotsRectangleSizeWidth>
   <ConfigurationHotSpotsRectangleSizeHeight>50</ConfigurationHotSpotsRectangleSizeHeight>
   <ConfigurationHotSpotsRectangleX>0</ConfigurationHotSpotsRectangleX>
   <ConfigurationHotSpotsRectangleY>0</ConfigurationHotSpotsRectangleY>
   <ConfigurationHotSpotsRectangleWidth>50</ConfigurationHotSpotsRectangleWidth>
   <ConfigurationHotSpotsRectangleHeight>50</ConfigurationHotSpotsRectangleHeight>
</t>

A: This is one of the shortest possible solutions. It isn't as efficient as passing the accumulated path as parameter, but for not too-deeply nested structures this will not be significant:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match=
 "*[not(*) and (ancestor::ScreenSize or ancestor::ConfigurationHotSpots)]">

    <xsl:variable name="vName">
        <xsl:for-each select=
        "ancestor-or-self::*
           [not(descendant::*
                   [self::ScreenSize or self::ConfigurationHotSpots])
           ]">
           <xsl:value-of select="name()"/>
      </xsl:for-each>
  </xsl:variable>
  <xsl:element name="{$vName}"><xsl:value-of select="."/></xsl:element>
 </xsl:template>
 <xsl:template match="text()"/>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:
<t>
  <ScreenSize>
    <Width>1440</Width>
    <Height>900</Height>
  </ScreenSize>
  <ConfigurationHotSpots>
    <Rectangle>
      <Location>
        <X>0</X>
        <Y>0</Y>
      </Location>
      <Size>
        <Width>50</Width>
        <Height>50</Height>
      </Size>
      <X>0</X>
      <Y>0</Y>
      <Width>50</Width>
      <Height>50</Height>
    </Rectangle>
  </ConfigurationHotSpots>
</t>

the wanted, correct result is produced:
<ScreenSizeWidth>1440</ScreenSizeWidth>
<ScreenSizeHeight>900</ScreenSizeHeight>
<ConfigurationHotSpotsRectangleLocationX>0</ConfigurationHotSpotsRectangleLocationX>
<ConfigurationHotSpotsRectangleLocationY>0</ConfigurationHotSpotsRectangleLocationY>
<ConfigurationHotSpotsRectangleSizeWidth>50</ConfigurationHotSpotsRectangleSizeWidth>
<ConfigurationHotSpotsRectangleSizeHeight>50</ConfigurationHotSpotsRectangleSizeHeight>
<ConfigurationHotSpotsRectangleX>0</ConfigurationHotSpotsRectangleX>
<ConfigurationHotSpotsRectangleY>0</ConfigurationHotSpotsRectangleY>
<ConfigurationHotSpotsRectangleWidth>50</ConfigurationHotSpotsRectangleWidth>
<ConfigurationHotSpotsRectangleHeight>50</ConfigurationHotSpotsRectangleHeight>

A: Here is a tweak on Dimitre's solution. It is simpler and leverages off the known root element and known positions of the ScreenSize etc., as per OP's comments...
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/*">
   <xsl:copy>
     <xsl:apply-templates select="@*|node()" />
   </xsl:copy>
 </xsl:template>

 <xsl:template match="*[not(*)]
                       [ancestor::ScreenSize|ancestor::ConfigurationHotSpots]">
    <xsl:variable name="vName">
        <xsl:for-each select="ancestor-or-self::*[not(self::t)]">
           <xsl:value-of select="local-name()"/>
        </xsl:for-each>
    </xsl:variable>
  <xsl:element name="{$vName}"><xsl:value-of select="."/></xsl:element>
 </xsl:template>
 <xsl:template match="text()"/>
</xsl:stylesheet>

Here is an alternate form of the match condition...
 <xsl:template match="(ScreenSize//* | ConfigurationHotSpots//*)[not(*)]">

I'm not actually sure which is better. If performance isn't a big deal, go with which ever reads easier. Just beware that this means two whole document scans for each template match attempt.


text:
Q: Mapping keys in hash - if, exists, map I'm trying to compare the contents of a file with a Hash of hashes. For this I am using map, if and exists, though ineffectively yet.
Basically, I want to know if columns 0 to 2 of the file exist in a hash. If so, then I want to find whether column 3 exists as key in the inner hash. My "old file.txt" is a tab separated file from which I produce the following hash:
old file.txt:
A    s.av    u
B    s.bv    u
C    s.av    u
C    s.cv    m

Hash:
my %oldhash = {
  'A' => {'s.av' => ['u']},
  'B' => {'s.bv' => ['u']},
  'C' => {'s.av' => ['u'], 's.cv' => ['m']},
};

Look if the following tab-separated columns from "new file.txt" exist in the hash:
D    Db    Dc    s.av   #cols 0 - 2 do not exist in hash
E    A     Ab    d.ef   #column 1 exists, but column 3 doesn't, so nothing is done
E    A     Ac    s.av   #col 1 and 3 exist, so the new file will have the value of $oldhash{A}{s.av}
B    Bb    B     s.bv   #col0 and 3 exist, so I'll include the value of $oldhash{B}{s.bv}

Notice that cols 0 and 2 both exist in the hash, but this is not important since I only need one of the columns to exist.
The output can be exactly as the testing file with an added column that takes u or m from the other file. Example:
D    Db    Dc    s.av       #inserts empty column
E    A     Ab    d.ef       #inserts empty column
E    A     Ac    s.av   u   #with u inserted
B    Bb    B     s.bv   u   #with u inserted

This is where I got so far, but I'm getting a exists argument is not a HASH or ARRAY element or a subroutine at myfile.pl line 24:
#!/usr/local/bin/perl
use strict;
use warnings;
use Data::Dumper;

my $dir='D:\\';

open my $oldfile, "<", "$dir\\old file.txt";
open my $newfile, "<", "$dir\\new file.txt";

my (%oldhash);

# creates the hash of hashes
while (my $odata = <$oldfile>){
    chomp $odata;
    my @oline = split /\t/, lc $odata;
    push @{$oldhash{$oline[1]}{$oline[2]}}, $oline[3];
}

# does the comparison between the file and the hash
while (my $newlines = <$newfile>){
    chomp $newlines;
    my @line = split /\t/, $newlines;
    if (exists map {$oldhash{$_}} @line[0..2]) {
        print $oldhash{$_};
    }
}

close $updatedtax;
close $oldtax;

I appreciate all the help that you can give me! Thank you in advance

A: exists requires a single array or hash element as its parameter. You have passed it a list of scalar values whose origin has been lost once they have gone through map.
You could write your test as
if ( grep { exists $oldhash{$_} }, @line[0..2] ) { ... }

but I think there are better ways to write a solution.
I think this does what you want, but with the data you've given it outputs just u twice. You haven't shown a required output as I requested, so is that right?
I've inverted the keys that you chose for your own %oldhash so that a case can be rejected immediately just by checking for the existence of the fourth column (s.av etc.) in the hash.
I've also added use autodie, as it's essential to check whether an open has been successful before you go ahead and use data from the file handle, and this avoids checking every case explicity.
Finally I've added chdir 'D:\\' so that you don't have to prefix the file names with the path for every open.
The output includes the final "comment" column from new_file.txt that gave rise to it. I am sure you can alter the print statement to give the output that you desire.
use strict;
use warnings;
use autodie;

use Data::Dump;

chdir 'D:\\';

open my $old_fh, '<', 'old_file.txt';

my %old_data;
while (<$old_fh>) {
  chomp;
  my @fields = split /\t/;
  $old_data{$fields[1]}{$fields[0]} = $fields[2];
  print "@fields\n";
}
close $old_fh;

open my $new_fh, '<', 'new_file.txt';

while (<$new_fh>) {

  chomp;
  my @fields = split /\t/;

  my $new = '';
  if (my $list = $old_data{$fields[3]}) {
    my @possible = grep defined, @{$list}{@fields[0,1,2]};
    $new = $possible[0] if @possible;
  }

  print join("\t", @fields[0..3], $new, $fields[4]), "\n";
}

The contents of %old_data after reading the file look like this
(
  "s.av" => { A => "u", C => "u" },
  "s.bv" => { B => "u" },
  "s.cv" => { C => "m" },
)

output
D Db  Dc  s.av    #cols 0 - 2 do not exist in hash
E A Ab  d.ef    #column 1 exists, but column 3 doesn't, so nothing is done
E A Ac  s.av  u #col 1 and 3 exist, so the new file will have the value of $oldhash{A}{s.av}
B Bb  B s.bv  u #col0 and 3 exist, so I'll include the value of $oldhash{B}{s.bv}


text:
Q: htaccess RewriteRule for url alias My website has several files and folders:
mywebsite.com/index.php
mywebsite.com/files/...

Our users asked me if it would be possible to create url alias like this:
mywebsite.com/thisalias -> mywebsite.com/index.php?var=thisalias

With other words: if the folder/file "thisalias" doesn't exist, it should redirect. I have tried several code samples from StackOverflow but for some reason it didn't work on my host. Any suggestions? I'm not really good with .htaccess coding.

A: I believe this is what you are looking for.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^/([a-zA-Z0-9]+)$ index.php?var=$1 [L]
</IfModule>


text:
Q: Why Is Wrapped Text Off by 1 Space? I'm using a centered navbar-brand in Bootstrap 3, and when viewed on a phone sized screen, the text wraps, but the top line has a leading space, whereas the bottom does not, leading to their being misaligned.

            Testing Testing

In this example, "title-card" sets the font-size to 2em; and navbar-brand along with navbar-header were modified to be:
.navbar-header {
    float: left;
    padding: 15px;
    text-align: center;
    width: 100%;
}

.navbar-brand {
    float: none;
}

This produces the following output:

How would one go about aligning them?

A: Give a margin:0 and padding:0 to your #title-card.
#title-card {
margin: 0;
padding: 0;
}


text:
Q: Why is "Implement Interface Explicitly" only available sometimes and not also "Implement Interface" (i.e. implicitly)? I was just trying to (re)implement my interface on a class where it was already implemented because I added some properties to the interface.  The existing properties were implicitly implemented, i.e. I had chosen this option when I first implemented it:

Now when I went to re-implement it doing the same thing after I added the new properties to the interface, I only had the option to implement explicitly:

Why does this happen sometimes?  I've done this plenty of times before where it's worked as "expected", and it always just adds the missing member implementations.

A: If the option where actually there, and it would actually add in the stubs for the methods to implicitly implement the interface, then the code wouldn't compile, as you'd have two methods with the same signature (since you already have the interface's methods as methods of the class).  The only other real sensible behavior for that option, were it to be left in, would be for it to just do nothing (as there is already an implicit implementation).


text:
Q: Xcode 3.2.3 - No SDK 3.1.3 after having installed Xcode 3.2.3 with iPhone SDK 4 (Seed) on OSX 10.6 there is no SDK 3.1.3 more available. Is there any possibility to reactivate it?
BR
Sven

A: Do the following

*

*sudo /Developer/Library/uninstall-devtools –mode=all (This will uninstall the current XCode installation)

*reboot

*Then install first old Xcode (3.2 final) in default folder (/Developer)

*Then install the new Xcode (3.2.3 GM) in other folder (/DeveloperBeta)

*This way you will have both. And can launch xcode from either /Developer/Applications/Xcode.app or /DeveloperBeta/Applications/Xcode.app

3.2.3 last beta did remove all other SDK's cause to many people tried publish Apps developed with the beta SDK, which will not be accepted and I guess that's still happening with the GM release.

A: You have to install both in different folders. In iOS4 there is only SDK 3.2 and 4.0

A: You could just leave the Base SDK on 4.0 and just change the iPhone OS Deployment Target to be 3.1.3 or whatever you need it to be.

A: Yes, I agree with Toby, above... AFAI understand it, there's no longer any need to set your project's Base SDK to 3.x, simply use 4.x for that -- and then set your "deployment target" to whatever lowest version of the (device) OS you want to support for your app. HTH clarify... ;-) cheers.


text:
Q: Is possible create distinct query from BooleanBuilder querydsl or get result without duplicate records? I found similar question. But I use BooleanBuilder for creating predicate and using him in a JpaRepository.
Is possible create distinct query with help BooleanBuilder or get result without duplicate records?


text:
Q: Refreshing the latest git submodule in repo I'm somewhat of a git newb so please bear with me here. I have a project that has a submodule that needs to be refreshed.
The project is using version 1 of the submodule and there are changes so I want to bump it to use the latest version.
How do I refresh the submodule and apply the changes so other users who clone or pulling from the project will use the latest updated version 1.5?
Here's how the project looks:
ProjectA: remote repo configured to repoA
It relies on a submodule that points to repoB.
The .git/config file in the project root directory looks like:
[remote "origin"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        url = git@/github.com/foo/foo.git

There is also .gitmodules file in the project root directory:
[submodule "Vendor/some-external-library"]
        path = Vendor/some-external-library
        url = https://github.com/some-external-library/some-external-library.git

Within 'some-external-library' directory, there is no .gitmodules file, just the standard .git directory with the appropriate files. .git/config points to repoB.

A: Submodules are actually git repos that are checked out inside your main repo, and your main repo knows stuff about them, like which commit they have checked out.
So, what you probably want to do is go to the folder of the sumbodule and go git pull origin master(or the commit you want to pull instead of master) and then do a commit that set reflects this change(the change on the submodule) on your main repo
In short:
cd submodule_dir
git pull origin master
cd main_dir
git add submodule_dir
git commit

You can also do git submodule foreach git pull to update all the submodules references at on time, but that's probably a bad idea regarding repo mantainability.
More info at git help submodule


text:
Q: Iframe in mobile browsers width goes outside of the page I have an iframe inside a web page that loads perfectly in desktop browsers.  Inside mobile browsers, the width of the content inside the iframe goes way outside of the page.  If I load the content that the iframe is loading, it looks perfect.  Does anyone know what might cause this incorrect content size in the iframe?

A: You could try placing this in your document's <HEAD>:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

You could play with the options if you like, for instance, removing user-scalable, etc.  This should be in the document inside the iframe as well as the containing document, if you're having problems there.


text:
Q: Navigating through stack in assembly Ok , so I have to write an assembly function (i32 x86 little endian) to which i pass 1 unsigned number. The function has to swap first appearance of min and max digit in that number.
My idea was to push all the digits to a stack and then find min and max, save their addresses in registers and swap them.
I have a problem because i can't do the following cmp [eax],[esp+4*ecx]. I have 2 questions is there any way to compare values of 2 addresses and can i somehow place esp to eax : mov eax,esp (i want the pointer not the value).
Note: I'm a bit new to this assembly stuff.


text:
Q: Yammer background authentication without user/browser session I'm trying to build a background application without user interaction, which would synchronize data with Yammer. The problem is - how to authentication it with Yammer, given that there is no user and no browser session. My understanding is that Yammer has no support for this type of applications, running in server background. Is there any workaround?
UPDATE:
I've taken a look at Google implementation. They seem to be using OAuth 2.0 "refresh tokens", while it is still necessary to authenticate with browser UI for the first time. Yammer seem not to have those "refresh tokens", but they also don't set validity time for access tokens.
This leads me to conclude, that it is necessary to give such "background" apps access token for the first time through some administrative UI, keeping them using this token (or "refresh" token) while they run in background. Is this a valid conclusion?

A: You need to have a user that is able to to access Yammer via their browser to acquire an OAuth token. Once this has been acquired that token is long lived and will be killed off if a user is suspended, or they manually revoke the token.
If I was developing an application that did some kind of background processing:

*

*I'd present the user with a way to authenticate in the app.

*Then I would take the user through the OAuth flow and acquire a token.

*Finally I'd persist the token acquired for this background user.

This might require you to setup a "service" account in a Yammer network, but that's generally not too big a problem. I guess it depends on what you are trying to build.

A: My understanding was same as yours and I had built a custom .Net Web Application that was using Yammer access token. My application was working fine with this access token for more than a month and then, it suddenly stopped working.
After some analysis, I found that the access token had changed. Not sure why and how that happened.


text:
Q: Adjusting position of google linechart I need to center a google line chart.
The problem is, I cannot use align = "center" because it causes my tooltip hover to lag behind, I'm not sure why.
I found a way to center the chart in the inspector by removing position: relative two divs deep in my chart div.

I thought to override this with
#electricalLineChart div div{
position: static!important
}

But it ignores this code even with !important
I haven't found anything in the documentation that addresses positioning. I tried using legend just for kicks but it doesn't seem to do anything.
Here is my chart code:
// line chart
        var linechart1 = new google.visualization.ChartWrapper({
            'chartType': 'LineChart',
            'containerId': 'electricalLineChart',
            dataTable: joinedData,
            options: {
                colors: ['#4DC3FA', '#185875'],
                animation: {
                    duration: 1000,
                    easing: 'out',
                },
                width: 800,
                height: 500,
                legend: { position: 'static'},
                title: 'Line Chart',
                explorer: {},
                hAxis: {
                    title: 'Month'
                },
                vAxis: {
                    format: formatPattern
                    //title: 'Amount Billed ($), Consumption (kWh)',

                }
            },
        });

RELEVENT HTML:

                                .... other rows removed for clarity

RELEVENT CSS:
#electricalLineChart, #Request_line_chart1{
width: 80%;
margin: auto;

}

Essentially, the third div down in the image with dir= "ltr" needs to be position: static not position: relative.

A: the problem,
 elements are block elements, which means they expand the total width of their parent element.
even though the chart does not take up the entire width,
the
 still expands to the width of the parent.
to prevent this behavior, add the following css to the
,
which will allow it to be centered...
display: inline-block;

e.g.
#electricalLineChart, #Request_line_chart1{
  width: 80%;
  margin: auto;
  display: inline-block;
}


text:
Q: Resize parent div to fit child div This may be a long shot to do without using JavaScript...
If I have the following (stripped out code for the problem)

#container {
    position: relative;
}

#content {
    position: absolute;
}

The content box contains dynamic content so a fixed height cannot be used.
Position absolute has to be used on the content div as its using jQuery UI stuff...
How would I get the container box to resize its height to fit the content?
I understand this is probably impossible without using some sort of JavaScript, as placing a div positioned absolute takes it out of the flow etc etc, but just wondered if anyone knew of some sort of work around?
Thanks!

A: edit: I misunderstood the question the first time.
If all else fails, here's a jQuery solution:
$('#container').css('height',$('#content').height());

A: Ok, I have no idea what your content is (jQuery UI stuff).  However, say it's just an image:
#container {
    position: relative;
}

#content {
    position: absolute;
    top:0; bottom:0; left:0; right:0;
}

This will set your content area to at least 100% width and height of the parent.


text:
Q: Get actual location rather than mocked location Android has a option in developer options to mock location. If my understanding is correct, if you set this location, the applications will start getting this location rather then the actual location?
If that is the case, how can we get the actual location regardless of what is set in this option?
If this is not the case, when is the mock location actually used (only in emulators?)?

A: As per my knowledge, we cant't get actual location if we are using MOKE location,
Use of Moke location
Suppose you are developing a application in Australia region, and you want to test your application in USA environment (Location only) without going there, In that case we are using Moke location.
I think location coming from android frameworks library , and these apis written is such a way, if you was set Moke location, then api will give priority to moke location only. So if you want to use actual location you need to stop moke loaction.
You can write your own api which will directly talk to gps, then might be you will do it, But its major project itself
EDIT
You can check MockSetting option is on or off
/**
 *returns true if mock location enabled, false if not enabled.
**/
public static boolean isMockLocationStatus(Context context) {
  if (Settings.Secure.getString(context.getContentResolver(),
                                Settings.Secure.ALLOW_MOCK_LOCATION).equals("0"))
     return false;
  else
     return true;
 }


text:
Q: Convert Byte[64] array to minimum length string I have try to generate unlock key like XXXX-XXXX-XXXX or simply small length string or Hexstring. I am using RSA algorithm to encrypt and decrypt the Key. I got some long string like
Q65g2+uiytyEUW5SFsiI/c5z9NSxyuU2CM1SEly6cAVv9PdTpH81XaWS8lITcaTZ4IjdmINwhHBosvt5kdg==

when I convert the byte array (array size is 64 byte) using the below convert method.
Convert.ToBase64String(bytes);

My requirement is to generate the minimal length Key. Is there any way to convert the Byte array (array size is 64 byte) to minimal length and I need that back to byte array or any other suggestions (to minimize the string length) would be helpful.
I have tried to convert the output string to Hex decimal, but the output is too long than the string.

A: You may want to take a look at What is the most efficient way to encode an arbitrary GUID into readable ASCII (33-127)? There the Base 85 encoding is discussed which is used to compress PDF files.
Though, the difference between Base64 and Base85 in your case is 8 characters.
You can safely remove trailing '==' in Base64 string because it is used for alignment and will always be there for 64-byte values (Of course you will have to add these characters back to decode the string).

A: Since you mention you want users to be able to type in the string,
there will be an inverse correlation between easy-of-use from point of view of users and the length of string.
Even typing a Base64 string is prone to lot of errors. Base32 strings are much easier to type, but correspondingly the length will increase.
If the users can Copy-Paste the key, then the above is moot and there should not be any valid reason why the length of the string should be as small as possible.

A: Obviously, you can only fit a certain amount of data into a fixed number of characters. You have pretty much maxed out the limit with base64 already which gives you 6 bits per byte.
Therefore you need to reduce the amount of data that needs to be stored. Can you reduce the key length? You could use a 96 bit key (by always leaving all other bytes zero). That would require 16 base64 characters which is much better.
It seems you don't need much security against brute forcing. So you can reduce the key size even further.


text:
Q: How to get value of elements without using IDs in JavaScript Lets say I had the following code:

    The Post Title

    Jul 17, 2014

    Category:
    Staff Profile

How would I possibly get the values of "The Post Title" and "Staff Profile" using JavaScript without changing the HTML on the page at all? i.e. I couldn't use getElementbyID for example. I could use jQuery if I had to but would rather not if possible.

A: You can get these values using getElementsByTagName which returns an array
document.getElementsByTagName("a")[0].innerHTML // returns The Post Title
document.getElementsByTagName("a")[1].innerHTML // returns Staff Profile

If these links are the first ones you can use indexes 0 and 1, otherwise you should look for the right index
Update
Another way that may be simple is to select these links inside the div with the class post
var links = document.getElementsByClassName("post")[index].getElementsByTagName("a");
links[0].innerHTML; // returns The Post Title
links[1].innerHTML; // returns Staff Profile

This solution would be the best one if the index of the div with the class post doesn't change

A: For a jQuery based expression you can use this:
$('a').map(function() {
    return [this.href, this.textContent];
}).get();

which should return:
[ [ 'http://www.example.com', 'The Post Title' ],
  [ 'http://sitename/category/staff-profile/', 'Staff Profile' ] ]

Should you specifically want the original relative URLs instead of the normalised full URLs, use this.getAttribute(href) in place of this.href
For a pure (ES5) equivalent:
[].map.call(document.getElementsByTagName('a'), function (el) {
    return [el.href, el.textContent];
});

Older browsers that don't support the W3C standard .textContent property may require the .innerText property instead, e.g.:
return [el.href, el.textContent || el.innerText];

A: You can do:
var posts = document.querySelector('.post');

for (var i = 0; i < posts.length; i++) {
    var links = document.querySelectorAll('a');
    var title = links[0].innerText || links[0].textContent;
    var profile = links[1].innerText || links[1].textContent;
}

A: If you are using a more modern browser, you can use document.querySelectorAll() which takes in CSS style selector syntax.
var aList = document.querySelectorAll('.post a');
for (var i = 0; i < aList.length; ++i) {
  alert(aList[i].innerHTML);
}

JSFiddle
I used '.post a' rather than just 'a' because I assume your page may have other 'a' tags in it that you don't necessarily want.


text:
Q: Popup menu seems not working I am trying to trigger a popup menu when user type a specific character .In my case It's dot key.But nothing happens.I think; I missed out something . Could you tell me what is wrong.Because I am completly confused
public class d extends  JPanel  {
   String phase="Some Clue ";
   final JTextArea area;
   final JPopupMenu menu;

   public d(){
       super(new BorderLayout());

       area=new JTextArea();
       area.setLineWrap(true);
       JButton button=new JButton("Clear");

       menu=new JPopupMenu();
       JMenuItem item=new JMenuItem(phase);
       menu.add(item);

       add(area,BorderLayout.NORTH);
       add(button,BorderLayout.SOUTH);
       add(menu);
  }

  public static void main(String...args){
      JComponent c=new d();
      JFrame frame=new JFrame();
      frame.setContentPane(c);
      frame.setSize(300,300);
      frame.setVisible(true);
  }

  ActionListener listener=new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent ae) {
        PopupMenu  menu=new PopupMenu();
        int pos=area.getCaretPosition();
        try {
            Rectangle r= area.modelToView(pos);
            menu.show(area, r.x, r.y);
        } catch (BadLocationException ex) {
            System.out.print(ex.toString());
        }
        KeyStroke ks=KeyStroke.getKeyStroke(KeyEvent.VK_P,0,false);
        area.registerKeyboardAction(listener, ks,JComponent.WHEN_FOCUSED);
    }
};

A: Move these statements into the constructor of your class d
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_P, 0, false);
area.registerKeyboardAction(listener, ks, JComponent.WHEN_FOCUSED);

so that the KeyStroke is registered with the JTextArea area
Also there's no need to create another (AWT) popup menu in the listener - re-use menu declared at class level.
ActionListener listener = new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent ae) {

        int pos = area.getCaretPosition();
        try {
            Rectangle r = area.modelToView(pos);
            menu.show(area, r.x, r.y);
        } catch (BadLocationException ex) {
            System.out.print(ex.toString());
        }

    }
};

Aside: Using Java Naming Conventions classes start with an uppercase letter, for example PopupTest rather than d


text:
Q: java mysql connection link failure After run well for 34 nodes.. my program get some message error looks like this :
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago.
The driver has not received any packets from the server.
        at sun.reflect.GeneratedConstructorAccessor8.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance
                      (DelegatingConstructorAccessorImpl.java:27)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
        at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
        at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2260)
        at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:787)
        at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:49)
        at sun.reflect.GeneratedConstructorAccessor4.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(
                       DelegatingConstructorAccessorImpl.java:27)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
        at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:357)
        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
        at java.sql.DriverManager.getConnection(DriverManager.java:582)
        at java.sql.DriverManager.getConnection(DriverManager.java:207)
        at org.sc.timetable.core.Database.Koneksi2DBMS(Database.java:77)
        at org.sc.timetable.core.Node.jumlahNode(Node.java:55)
        at org.sc.timetable.core.Node.DataPemetaan(Node.java:73)
        at org.sc.timetable.core.Node.matriknode(Node.java:123)
        at org.sc.timetable.core.Node.main(Node.java:158)

Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
        at sun.reflect.GeneratedConstructorAccessor8.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance
                      (DelegatingConstructorAccessorImpl.java:27)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
        at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
        at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
        at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2181)
        ... 15 more
Caused by: java.net.SocketException: No buffer space available (maximum connections reached?): connect
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
        at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
        at java.net.Socket.connect(Socket.java:529)
        at java.net.Socket.connect(Socket.java:478)
        at java.net.Socket.<init>(Socket.java:375)
        at java.net.Socket.<init>(Socket.java:218)
        at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
        at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:293)
        ... 16 more

Java Result: 1
Can somebody help me?

A: See the following links,
https://serverfault.com/questions/89955/unable-to-connect-to-mysql-through-jdbc-connector-through-tomcat-or-externally
http://forums.mysql.com/read.php?39,199085,388953#msg-388953
http://bugs.mysql.com/bug.php?id=35353
Mostly it talks about the version of the driver. Please check.


text:
Q: How to put an argument in a RegEx? So, I am trying to use an argument in a RegEx pattern and I can't find a pattern because the argument is a simple String which is contained in the bigger string. Here is the the task itself, which I took from this codingbat.com, so everything to be clear:

THE Precondition and explanation of the task.
Given a string and a non-empty word string, return a version of the
  original String where all chars have been replaced by pluses ("+"),
  except for appearances of the word string which are preserved
  unchanged.

My code:
public String plusOut(String str, String word) {
  if(str.matches(".*(<word>.*<word>){1,}.*") || str.matches(".*(<word>.*<word>.*<word>){1,}.*")) {
  return str.replaceAll(".", "+");  //after finding the argument I can easily exclude it but for now I have a bigger problem in the if-condition
  } else {
  return str;
  }
}

Is there a way in Java to match an argument? The above code doesn't work for obvious reasons (<word>). How to use the argument word in the string RegEx?
UPDATE
This is the closest I got but it works only for the last char of the word String.
public String plusOut(String str, String word)
{
  if(str.matches(".*("+ word + ".*" + word + "){1,}.*") || str.matches(".*(" + word + ".*" + word + ".*" + word + "){1,}.*") || str.matches(".*("+ word + "){1,}.*"))
  {
     return str.replaceAll(".(?<!" + word + ")", "+");
  } else {
     return str;
  }
}

Input/Output
plusOut("12xy34", "xy") → "+++y++"  (Expected "++xy++")
plusOut("12xy34", "1") → "1+++++" (Expected "1+++++")
plusOut("12xy34xyabcxy", "xy") → "+++y+++y++++y" (Expected "++xy++xy+++xy")
It`s because of the ? in the RegEx.

A: You need to concatenate it using + operator of Java
if(str.matches("<"+word+">")){ // Now word will be replaced by the value
//do Anything
}

A: You cannot place arguments inside the regex pattern. You can create a regex object by concatenating variables with the regex pattern parts like this:
public String plusOut(String str, String word)
{
  if(str.matches(".*("+ word + ".*" + word + "){1,}.*") || str.matches(".*(" + word + ".*" + word + ".*" + word + "){1,}.*"))
  {
     return str.replaceAll(".", "+");
  }
  else
  {
     return str;
  }
}

A: You can't do it with only patterns, you'll have to write some code apart from the pattern. Try this:
public static String plusOut(String input, String word) {

    StringBuilder builder = new StringBuilder();
    Pattern pattern = Pattern.compile(Pattern.quote(word));
    Matcher matcher = pattern.matcher(input);
    int start = 0;

    while(matcher.find()) {
        char[] replacement = new char[matcher.start() - start];
        Arrays.fill(replacement, '+');
        builder.append(new String(replacement)).append(word);
        start = matcher.end();
    }
    if(start < input.length()) {
        char[] replacement = new char[input.length() - start];
        Arrays.fill(replacement, '+');
        builder.append(new String(replacement));
    }

    return builder.toString();
}


text:
Q: ¿Como puedo enviar un mail con php y laravel 5.4? Buenas tardes compañeros, me encuentro realizando un formulario para enviar correos, el detalle que tengo es que al momento de enviar el mail, si me encuentro en mi localhost si envia el email exitosamente, al subirlo a un servidor me arroja un error y por ende no se envia dicho email.
Les comparto la funcion que estoy realizando para el envio del email.
public function postStoreJobsForm(request $request){

    $nombre = $request['nombre'];
    $email = $request['email'];
    $telefono= $request['telefono'];
    $marca= $request['marca'];
    $modelo= $request['modelo'];
    $puertas= $request['puertas'];
    $color= $request['color'];
    $trasmision= $request['trasmision'];
    $cilindros= $request['cilindros'];
    $kilometraje= $request['kilometraje'];
    $estadoInterior= $request['estadoInterior'];
    $precio= $request['precio'];

    $input = Input::all();

    Mail::send('web.front.email.jobs', [
        'nombre' => $nombre,
        'email' => $email,
        'telefono' => $telefono,
        'marca' => $marca,
        'modelo' => $modelo,
        'puertas' => $puertas,
        'color' => $color,
        'trasmision' => $trasmision,
        'cilindros' => $cilindros,
        'kilometraje' => $kilometraje,
        'estadoInterior' => $estadoInterior,
         'precio' => $precio], function ($message) use ($input, $nombre, $email) {
            $message->from($email, $nombre);
            $message->sender('ing.magalylf@hotmail.com', 'Bolsa de trabajo');
         /*Correo para enviar a otras personas */
            $message->to('magaly.lopez@metodika.mx', 'Magaly');
            /*$message->cc('ALSanchez@terza.com', 'ALSanchez');
            $message->cc('rrodriguez@terza.com', 'rrodriguez');
            $message->cc('rjagarza@terza.com', 'rjagarza');
            $message->cc('rjagarza@terza.com', 'rjagarza');
            $message->bcc('bruno.chavez@metodika.mx', 'Bruno Chavez');;*/
            $message->bcc('azeneth.futurite@gmail.com', 'Azeneth');

            $message->subject('Quiero Vender Mi Auto');

            $message->priority(3);

            $message->attach($input['archivo']->getRealPath(), array(
            'as' => 'archivo.' . $input['archivo']->getClientOriginalExtension(),
            'mime' => $input['archivo']->getMimeType()));

             return view('web.front.ofreceAuto');
        });
return redirect()->intended('/web.front.ofreceAuto/');

 }

Y este es el error que me arroja:
(1/1) ReflectionException
Class Swift_Transport_Esmtp_AuthHandler does not exist

Si alguien puede ayudarme les agradecere mucho...
les comparto el enlace para que puedan ver el error a detalle:
PD. rellenan el formulario con cualquier dato e intentan enviar el email
http://testingmetodika.com/autos-dieck/public/ofrece-tu-auto
Espero haberme explicado bien, de antemano muchas gracias


text:
Q: Господа Java-гуру - объясните плз доходчиво для изучающего дженерики данную конструкцию     public static class Box<T> {
       private T object;

       public T getObject() {
            return object;
       }

       public static <T> Box<T> getBox() {
            return new Box<T>();
       }
   }

Я очень долго пытался въехать в смысл написанного и синтаксис объявления метода getBox, но так и не понял, почему после static нужно писать "<T> Box<T>", если тип возвращаемого значения просто Box<T>?..


text:
Q: Proper way to document a Class in JSDoc Given
function Just (x) {
    this.some = x;
    this.other = 1;
}

what is the most recommended way to document this class in JSDoc? (Take x to be a string).

A: /**
 * Creates a new Just.
 * @class
 */

Source: http://usejsdoc.org/tags-class.html


text:
Q: Using liac-arff package instead of arff in python. How to uninstall? Python has two packages to read arff files. One is liac-arff, while the other is arff. To use either in a code, the import statement is:
import arff

I installed both these packages accidently. The way both of them function is different, and I need to use the liac-arff package, but python everytime tries to import the arff one. I tried uninstalling the arff package, but I am stuck. I tried the following but to no success:
pip2 uninstall arff
apt-get uninstall python-arff

Please suggest to how to uninstall the arff package, or how to make python import liac-arff when the import statement is same?


text:
Q: Effective Strategies for debugging websites on iPad When you receive an issue about your website not functioning on an iPad, what effective strategies do you use to debug the issue?
For example, a user mentioned that a website I maintain is not accessible on his iPad.  We were able to look at his iPad and noticed all the HTML/CSS had rendered, but the Javascript component did not.  The only data I was able to capture about his iPad was that he was on iOS 8.1.2 and his User Agent was: UserAgent: Mozilla/5.0 (iPad; CPU OS 8_1_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B440 Safari/600.1.4
Because I do not have the device to continue testing, I used BrowserStack to try and recreate the issue.  I emulated every iPad version that BrowserStack had and the javascript component rendered fine on all of them.
I also reached out to other people who owned iPads (v1 and v2) with iOS 8.1.2 installed and asked them to try to reproduce the issue.  It also worked fine on their iPad.
How can I reproduce this issue so that I can effectively debug it?

A: It is quite easily possible to use the safari remote debugging features in order to debug a website on an iOS device.
Note: This only applies when using a Mac
Hav a look here: http://www.hongkiat.com/blog/ios-debugging/


text:
Q: CSS trying too center a list and a header Im having such a weird offset when i try too center a h1 and a horizontal align list ...

The list has a slightly offset too the right, but why?
How can i center both perfectly?

*   {
    box-sizing: border-box;
}

body {
    background-color: black;
}

header h1  {
    position: relative;
    text-align: center;
    font-size: 5.5em;
    font-weight: bold;
    font-family: Arial;
    letter-spacing: 11px;
    color: white;
}

nav {
    font-family: Verdana;
    font-size: small;
    text-align: center;
    word-spacing: 15px;
    list-style-type: none;
}

li  {
    display: inline;
}

li a    {
    text-decoration: none;
    display: inline-block;
    color: white;
}

Header

Leben

Karriere

Alben

Filme

Auszeichnungen

Thanks for the help, very appreciate it

A: Just remove the margin/padding from the ul:
nav ul {
  margin: 0;
  padding: 0;
}

*   {
    box-sizing: border-box;
}

body {
    background-color: black;
}

header h1  {
    position: relative;
    text-align: center;
    font-size: 5.5em;
    font-weight: bold;
    font-family: Arial;
    letter-spacing: 11px;
    color: white;
}

nav {
    font-family: Verdana;
    font-size: small;
    text-align: center;
    word-spacing: 15px;
    list-style-type: none;
}

nav ul {
  margin: 0; padding: 0;
}

li  {
    display: inline;
}

li a    {
    text-decoration: none;
    display: inline-block;
    color: white;
}

Header

Leben

Karriere

Alben

Filme

Auszeichnungen


text:
Q: Google Guice with Junit and Mockito how can i inject EntityManager(jpa) with Mockito?
I wanna bind Mockito.spy(UserService.class) to guice injector.
but UserService.class has EntityManager for query execution.
When installing 'JunitServiceModule' in guice injector, EntityManager is not found.
See below for error details
com.google.inject.CreationException: Unable to create injector, see the following errors:

1) Error in custom provider, java.lang.NullPointerException
  while locating com.google.inject.persist.jpa.JpaPersistService
  while locating javax.persistence.EntityManager

My code is below.
(The test code just made the error situation similar.)
(actually 'EntityManager' is located in UserRepository... It's just example!)
(@Transactional is belong to guice)
public class UserServiceTest {
    @Inject
    private UserService userService;

    @Before
    public void setUp() {
        Injector injector = new TestBuilder().init();
        injector.initMembers(this);
        Mockito.doReturn(10).when(userService).getEntityCount(UserEntity.class);
    }

    @Test
    public void test() {
        assertEquals(10, userService.getEntityCount(UserEntity.class));
    }
}

public class TestBuilder {

    public TestBuilder() {
    }

    public Injector init() {
        Injector injector = Guice.createInjector(
            new TestDBInjectModule("test"),
            new JunitServiceModule()
        );
    }
}

public class TestDBInjectModule extends AbstractModule {
    private String unitName;

    public TestDBInjectModule(String unitName) {
        this.unitName = unitName;
    }

    @Override
    protected void configure() {
        install(new JpaPersistModule(unitName));
        bind(JpaInitializer.class).asEagerSingleton();
    }

    @Singleton
    private static class JpaInitializer {
        @Inject
        public JpaInitializer(final PersistService persistService) {
            persistService.start();
        }
    }
}

public class JunitServiceModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(UserService.class).toInstance(Mockito.spy(UserService.class));
    }
}

public class UserService {
  @Inject
  private EntityManager entityManager;

  public UserService {} // <-- throw NullPointerException!!! since EntityManager

  @Transactional
  public void addUser(User user) {
    return entityManager.persist(user);
  }

  public Number getCount() {
    return entityManager.createQuery("select count(*) from user", Number.class).getSingleResult();
  }
}


text:
Q: VSTS Deploy failed with error -1073740791 I'm getting a very tricky error when I run my deployment task to my second environment on my release pipeline that I can't solve. Seems to be something related to NodeJS. We don't use note at all. And what is that timer.c? Any help?  I just pasted here the end of the log file where the error is. Let me know if the full log is needed and I will update my question.
2018-07-31T14:32:47.6409251Z ##[debug]Processing drop/Captura.PDV.Pagadoria.Web.deploy.cmd
2018-07-31T14:32:47.7084467Z ##[debug]Got download stream for item: drop/Captura.PDV.Pagadoria.Web.deploy-readme.txt
2018-07-31T14:32:47.7085150Z ##[debug]testing directory 'C:\vstsagent\A1\_work\r1\a\_Captura-CI\drop'
2018-07-31T14:32:47.7087739Z Downloading drop/Captura.PDV.Pagadoria.Web.deploy-readme.txt to C:\vstsagent\A1\_work\r1\a\_Captura-CI\drop\Captura.PDV.Pagadoria.Web.deploy-readme.txt
2018-07-31T14:32:47.7094967Z Assertion failed: new_time >= loop->time, file src\win\timer.c, line 37
2018-07-31T14:32:47.8022545Z ##[error]Exit code -1073740791 returned from process: file name 'C:\vstsagent\A1\externals\node\bin\node.exe', arguments '"C:\vstsagent\A1\_work\_tasks\DownloadBuildArtifacts_a433f589-fce1-4460-9ee6-44a624aeb1fb\0.137.2\main.js"'.
2018-07-31T14:32:47.8058568Z ##[debug]Microsoft.VisualStudio.Services.Agent.Util.ProcessExitCodeException: Exit code -1073740791 returned from process: file name 'C:\vstsagent\A1\externals\node\bin\node.exe', arguments '"C:\vstsagent\A1\_work\_tasks\DownloadBuildArtifacts_a433f589-fce1-4460-9ee6-44a624aeb1fb\0.137.2\main.js"'.
   at Microsoft.VisualStudio.Services.Agent.Util.ProcessInvoker.<ExecuteAsync>d__26.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Services.Agent.ProcessInvokerWrapper.<ExecuteAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Services.Agent.Worker.Handlers.DefaultStepHost.<ExecuteAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Services.Agent.Worker.Handlers.NodeHandler.<RunAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Services.Agent.Worker.TaskRunner.<RunAsync>d__24.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.VisualStudio.Services.Agent.Worker.StepsRunner.<RunStepAsync>d__1.MoveNext()
2018-07-31T14:32:47.8065131Z ##[section]Finishing: Download artifact - _Captura-CI

A: I was able to solve the problem restarting the server. It is an EC2 instance on AWS.
https://github.com/libuv/libuv/issues/1268#issuecomment-371829176


text:
Q: Is it safe to use Provider to store a JWT during a session in Flutter? I am using flutter_secure_storage to store a JWT for authentication right now, but since I'm using provider as state management, my question is if it would be safe to save the JWT in a provider as well. Or is that less secure than retrieving it from secure storage every time I make a request to the server?

A: Provider (and the recommended new Riverpod) store items within the memoryspace of the app, and will be alive only as long as the app.  However, apps are sometimes killed by the OS, so you can trap that and persist the value in SharedPreferences if you need it after the app goes away.


text:
Q: How to set MVC Razor View TextBox Default Value I would like to set the default value of a textbox in razor view when the model value is null/empty. This is how I have set the default value, but it is currently overriding the value of the model even if it exists:

    @Html.LabelFor(Function(model) model.PostAction, htmlAttributes:=New With {.class = "control-label col-md-2"})

        @Html.EditorFor(Function(model) model.PostAction, New With {.htmlAttributes = New With { .Value = "Active", .class = "form-control"}})
        @Html.ValidationMessageFor(Function(model) model.PostAction, "", New With {.class = "text-danger"})

I would like the default value to be an optional value to be set only when the model value is null

A: I figured this out:

        @If String.IsNullOrEmpty(Model.PostAction) Then
            @Html.EditorFor(Function(model) model.PostAction, New With {.htmlAttributes = New With {.Value = "Active", .class = "form-control"}})
        Else
            @Html.EditorFor(Function(model) model.PostAction, New With {.htmlAttributes = New With {.class = "form-control"}})
        End If
        @Html.ValidationMessageFor(Function(model) model.PostAction, "", New With {.class = "text-danger"})


text:
Q: Windows from Dreamspark related questions I am a computer science student and my university is participating the Dreamspark program, as such I can get Dreamspark licenses for Windows operating systems. I am planning to install Windows 7 Professional from Dreamspark on my computer. However understandably I want to know what I'm getting into before I go ahead.
Here are the questions to which, despite an extensive search, I was unable to find complete answers to:

*

*I have read on a few forums that apparently there exists an activation limit which limits how many times I can reinstall Windows. However on a few other forums I read the limit is about how often I reinstall which seems to imply I should be able to reinstall as many times as I want as long as I don't do it too often (which seems like a contradiction to me ;) ). If said limit does exist does anyone know what it is?

*I have also read that if said limit is met I will not be able to activate Windows until I phone Microsoft's automated system and it resets that limit. If this is true can anyone tell me if I can accomplish the same via the Internet? Even ignoring the fact I hate dealing with automated phone systems if I have to phone Microsoft in the USA then this is going to pose a significant problem as I live in Europe and thus the roaming fees are going to be huge.

*I have also read that hardware changes can cause problems with Windows activation. Is that true? What would happen if I were to change my graphic's card or replace my RAM?

*As my hard drive is getting quite old I am well aware that sooner or later it's going to fail (although right now everything, SMART included, appears to be ok). If my hard drive has a head crash one year from now will I be able to reinstall windows on a new hard drive (with all other hardware staying the same)?

*I know that software from Dreamspark works even after I stop being a student (which is probably going to happen 2.5 years from now). However can I still reinstall Windows from Dreamspark after I'm no longer a student?

A: *

*There's no specific limit.  A certain amount of auto-activations within a certain time period will often cause it to force you to call to complete activation.

*If you get to the point where it won't auto-activate over the Internet you have to call them. They have toll-free phone numbers for just about every continent/country.

*Yes, hardware changes can trigger a need to reactivate.  Usually you need to change two of the key hardware elements before it triggers a need to reactivate. See What causes windows 7 activation requests?

*Yes, you can reinstall.  See: Will Windows fail activation on a new hard drive after previous hard drive failed, Reinstalling Windows 8 from Dreamspark

*Yes you can keep using it as needed, but not for commercial purposes.  From Microsoft Software License Terms - MICROSOFT DREAMSPARK DIRECT SUBSCRIPTION AGREEMENT:

2b. End of Student Status.
  The DreamSpark Direct Subscription is a special offering for students. Once you no longer qualify for the DreamSpark Direct Subscription (due to graduation or otherwise no longer meeting the definition of "you" above), your DreamSpark Direct Subscription will terminate; however, you may continue to use the software you obtained prior to termination of your student status subject to the terms of this agreement.

...

3d. No commercial use.
  Except as provided below, you may not use the DreamSpark Direct Subscription software for commercial purposes or commercial software application development, publication or distribution unless you first purchase the appropriate commercial license(s) for the software.

A: Dreamspark answers most of these questions when you sign up.
First off, they don't advertise the limit of activations; they expect you to only use it as licensed (for educational purposes). You can't use it for commercial use or gains, and you must remove it when you cease to be a student/faculty member of an educational institution.
You need to read through the Dreamspark EULA for the exact details of what you're allowed to do. Hardware changes are only going to affect your activation status when they are MAJOR changes (i.e. motherboard, hard drive, video card, CPU). Do small changes, and you'll be fine.


text:
Q: Preprocessing 400 million tweets in Python -- faster I have 400 million tweets ( actually I think its almost like 450 but never mind ) , in the form :
T    "timestamp"
U    "username"
W    "actual tweet"

I want to write them to a file initially in the form  "username \t tweet" and then load into a DB . The problem is that before loading into a db, there are a few things I need to do :
1. Preprocess the tweet to remove RT@[names] and urls
2. Take the username out of "http://twitter.com/username".
I am using python and this is the code . Please let me know how this can be made faster :)
'''The aim is  to take all the tweets of a user and store them in a table.  Do this for all the users and then lets see what we can do with it
   What you wanna do is that you want to get enough information about a user so that you can profile them better. So , lets get started
'''
def regexSub(line):
    line = re.sub(regRT,'',line)
    line = re.sub(regAt,'',line)
    line = line.lstrip(' ')
    line = re.sub(regHttp,'',line)
    return line
def userName(line):
    return line.split('http://twitter.com/')[1]

import sys,os,itertools,re
data = open(sys.argv[1],'r')
processed = open(sys.argv[2],'w')
global regRT
regRT = 'RT'
global regHttp
regHttp = re.compile('(http://)[a-zA-Z0-9]*.[a-zA-Z0-9/]*(.[a-zA-Z0-9]*)?')
global regAt
regAt = re.compile('@([a-zA-Z0-9]*[*_/&%#@$]*)*[a-zA-Z0-9]*')

for line1,line2,line3 in itertools.izip_longest(*[data]*3):
    line1 = line1.split('\t')[1]
    line2 = line2.split('\t')[1]
    line3 = line3.split('\t')[1]

    #print 'line1',line1
    #print 'line2=',line2
    #print 'line3=',line3
    #print 'line3 before preprocessing',line3
    try:
        tweet=regexSub(line3)
        user = userName(line2)
    except:
        print 'Line2 is ',line2
        print 'Line3 is',line3

    #print 'line3 after processig',line3
    processed.write(user.strip("\n")+"\t"+tweet)

I ran the code in the following manner:
python -m cProfile -o profile_dump TwitterScripts/Preprocessing.py DATA/Twitter/t082.txt DATA/Twitter/preprocessed083.txt

This is the output I get : ( Warning : its pretty big and I did not filter out the small values, thinking, they may also hold some significance )
Sat Jan  7 03:28:51 2012    profile_dump

         3040835560 function calls (3040835523 primitive calls) in 2500.613 CPU seconds

   Ordered by: call count

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
528840744  166.402    0.000  166.402    0.000 {method 'split' of 'str' objects}
396630560   81.300    0.000   81.300    0.000 {method 'get' of 'dict' objects}
396630560  326.349    0.000  439.737    0.000 /usr/lib64/python2.7/re.py:229(_compile)
396630558  255.662    0.000 1297.705    0.000 /usr/lib64/python2.7/re.py:144(sub)
396630558  602.307    0.000  602.307    0.000 {built-in method sub}
264420442   32.087    0.000   32.087    0.000 {isinstance}
132210186   34.700    0.000   34.700    0.000 {method 'lstrip' of 'str' objects}
132210186   27.296    0.000   27.296    0.000 {method 'strip' of 'str' objects}
132210186  181.287    0.000 1513.691    0.000 TwitterScripts/Preprocessing.py:4(regexSub)
132210186   79.950    0.000   79.950    0.000 {method 'write' of 'file' objects}
132210186   55.900    0.000  113.960    0.000 TwitterScripts/Preprocessing.py:10(userName)
  313/304    0.000    0.000    0.000    0.000 {len}

Removed the ones which were really low ( like 1, 3 and so on)
Please tell me what other changes can be made. Thanks !

A: This is what multiprocessing is for.
You have a pipeline that can be broken into a large number of small steps.  Each step is a Process which does to get for an item from the pipe, does a small transformation and puts an intermediate result to the next pipe.
You'll have a Process which reads the raw file three lines at a time, and the puts the three lines into a Pipe.  That's all.
You'll have a Process which gets a (T,U,W) triple from the pipe, cleans up the user line, and puts it into the next pipe.
Etc., etc.
Don't build too many steps to start with.  Read - transform - Write is a good beginning to be sure you understand the multiprocessing module.  After that, it's an empirical study to find out what the optimum mix of processing steps is.
When you fire this thing up, it will spawn a number of communicating sequential processes that will consume all of your CPU resources but process the file relatively quickly.
Generally, more processes working concurrently is faster.  You eventually reach a limit because of OS overheads and memory limitations.

A: Until you run it through a profiler, it is difficult to know what needs to be changed. However, I would suggest that the most likely slowdowns occur where you are creating and running the regular expressions.
Since your file follows a specific format, you may see significant speed increases by using a lex+yacc combo. If you use python lex+yacc, you won't see as much of a speed increase, but you won't need to muck about with c code.
If this seems like overkill, try compiling the regular expressions before you start the loop. You can also have chunks of the file run by independent worker threads/processes.
Again though, profiling will reveal what actually is causing the bottleneck. Find that out first, then see if these options will solve the problem.

A: str.lstrip is probably not doing what you were expecting:
>>> 'http://twitter.com/twitty'.lstrip('http://twitter.com/')
'y'

from the docs:
S.lstrip([chars]) -> string or unicode

Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping

A: Looking at the profiling information, you're spending a lot of time in regexSub. You may find that you can combine your regexps into a single one, and do a single substitution.
Something like:
regAll = re.compile(r'RT|(^[ \t]+)|((http://)[a-zA-Z0-9]*.[a-zA-Z0-9/]*(.[a-zA-Z0-9]*)?)|...')

(The intention of this is to not only replace all the things you are doing with re.sub, but also the lstrip). I've ended the pattern with ...: you'll have to fill in the details yourself.
Then replace regexSub with just:
line = regAll.sub(line)

Of course, only profiling will show if this is faster, but I expect that it will as there will be fewer intermediate strings being generated.

A: For preprocessing the tweets, you can use the tweetprep Python library.
It can also be used for translating tweets to any other language.
Link to library:
https://pypi.org/project/tweetprep/
Installation:
pip install tweetprep

Usage:
from tweetprep import preprocess
#from tweetprep import lang_translator

tweet = "#COVID-19 is the worst pandemic @2020!! :,("
# get translated tweet
lang="es"
print(preprocess.lang_translator.translate(tweet,dest=lang).text)

# Get processed version of tweet
print(preprocess.clean(tweet))

Output:
# COVID-19 es la peor pandemia @ 2020!! :,(
covid19 is the worst pandemic crying smiley


text: Q: How to make sum of column value ? in parse I just wanted to know is there a feature in parse to get the SUM of the column value. I read in the link https://www.parse.com/questions/how-to-make-sum-of-column-value that this feature is not supported through query we need to use cloud code. Is this the same till now? Any updates on this?


text:
Q: Cannot set body as FormDataMultiPart on exchange in apache Camel I have a use-case where I need to send FormDataMultiPart through exchange body, which goes in a REST service call.
REST end point:
public Response sendttachments(final FormDataMultiPart bodyPart) {
//Do Something
}

Camel Processor:
FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
File file = new File("pathToFile");
InputStream targetStream = new FileInputStream(file);
FormDataBodyPart fdp1 = new FormDataBodyPart(FormDataContentDisposition.name("emailRequest").build(),
                    someObject, MediaType.APPLICATION_JSON_TYPE);
FormDataBodyPart fdp2 = new FormDataBodyPart(
FormDataContentDisposition.name("file").fileName("fileName").build(), targetStream,MediaType.APPLICATION_OCTET_STREAM_TYPE);

formDataMultiPart.bodyPart(fdp1).bodyPart(fdp2);

    exchange.getIn().setBody(Entity.entity(formDataMultiPart, MediaType.MULTIPART_FORM_DATA));

I get the following exception :

Caused by: org.apache.camel.NoTypeConversionAvailableException: No
  type converter available to convert from type:
  javax.ws.rs.client.Entity to the required type: java.io.InputStream
  with value
  Entity{entity=org.glassfish.jersey.media.multipart.FormDataMultiPart@3e90d6b2,
  variant=Variant[mediaType=multipart/form-data, language=null,
  encoding=null], annotations=[]}

Am I missing some conversion type? or something else. Any help would be appreciated


text:
Q: How to make a list of strings using a 'ScrollView' (Android Studio) In my Layout I have made a TextView which is meant to contain a large amount of text.
Under the TextView I added this two characteristics:
android:maxLines = "100"
android:scrollbars = "vertical"
android:text="@string/infoestring"

and this in the Java file:
TextView INFO=(TextView)findViewById(R.id.info);
INFO.setMovementMethod(new ScrollingMovementMethod());

All that just to make like a ScrollView in the TextView(info) and it
works just fine. The problem is in my strings.xml file under the directory Values.
I have the String named 'infostring':
<string name="infostring">A:B:C:D:E:F:G:H:I:J:K:L:M:N:O:P:Q:R:S:T:U:V:W:X:Y:Z:</string>

The TextView is wide and what I want is to put every Letter(From the string 'infostring') in one single line of the TextView, I try adding spaces between the letters in the string but it doesn't work, is there a way to do it?.

A: If you want each letter on a line, how about :
<string name="infostring">"A\nB\nC\nD\nE"</string>

But I don't understand what you're trying to achieve here, it looks painful to do. There should be another solution for your bigger problem.
To actually make a list of strings, you should check out ListView, which takes care of the scrolling and everything.