text:
Q: `getResources().getString` generating exception In my application I have the following line:
String ci = getResources().getString(R.string.cidades);
This is throwing an exception while running the application. This only occurs in version 7.1 and 8 of Android, in the previous normal wheel, does anyone know why?
Logcat:

java.lang.RuntimeException: Unable to start activity ComponentInfo{insidetechnology.studio.ostdor.anestesiaanimal/insidetechnology.studio.ostdor.anestesiaanimal.autenticacao.state}: java.lang.IndexOutOfBoundsException
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                                Caused by: java.lang.IndexOutOfBoundsException
                                                                                at android.content.res.StringBlock.nativeGetString(Native Method)
                                                                                at android.content.res.StringBlock.get(StringBlock.java:82)
                                                                                at android.content.res.AssetManager.getResourceValue(AssetManager.java:236)
                                                                                at android.content.res.AssetManager.getResourceText(AssetManager.java:164)
                                                                                at android.content.res.Resources.getText(Resources.java:334)
                                                                                at android.content.res.Resources.getString(Resources.java:432)
                                                                                at insidetechnology.studio.ostdor.anestesiaanimal.autenticacao.state.onCreate(state.java:38)
                                                                                at android.app.Activity.performCreate(Activity.java:6975)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

A: A workaround can be using string-array instead of string
<string-array name="items">
<item>item0</item>
<item>item1</item>
...
</string-array>

then
String[] items = getResources().getStringArray(R.array.items);

I dont know why but maybe your string exceeds the limitation of string resource in new Android versions


text:
Q: Locus of image of point in a line. I am given the following question:

Find the locus of the image of the point $(2,3)$ in the line
$$\text{L}:(2x-3y+4)+k(x-2y+3)=0$$ where $k$ is any real number.

Attempt at solution.
I used a formula to arrive at (image of a point):
$\dfrac{x-2}{(2+k)}=\dfrac{y-3}{-(2k+3)}=\dfrac{2(1+k)}{(k+2)^2+(2k+3)^2}$
I know that it is a circle centred at $(1,2)$ with radius $\sqrt{2}$.
But I am having trouble solving the parametric equation. I need a quick way to do it or maybe to solve this problem in other way. It appeared in a recent National exam in India known as JEE - Mains 2015.
Addendum : Here's a graph https://www.desmos.com/calculator/5bweaiyj3a

A: The given line is actually a variable line (or you can say a family of lines) that pass through the intersection of the following two lines:
$$2x-3y+4=0 \qquad \text{ and } \qquad x-2y+3=0.$$
Their intersection point is $J=(1,2)$.
Let $P=(a,b)$ be the reflection of $Q=(2,3)$, then the mid-point $M=\left(\dfrac{a+2}{2}, \dfrac{b+3}{2}\right)$ of segment $PQ$ lies on the given line.
Now use a bit of geometric imagination to see that the lines $JM$ and $PQ$ will be perpendicular to each other (except in the degenerate case which happens when the variable line passes through the point $(2,3)$ itself). Thus  the slopes will follow:
$$m_{JM} \cdot m_{PQ}=-1$$
This is same as saying
$$\left(\frac{\frac{b+3}{2}-2}{\frac{a+2}{2}-1}\right).\left(\frac{b-3}{a-2}\right)=-1.$$
As you can see there is no parameter in this equation. Once you solve this you get:
$$a^2+b^2-2a-4b+3=0$$
which is same as
$$(a-1)^2+(b-2)^2=2$$

A: After getting the point of intersection of the given family of lines we need to simply calculate the distance between the given point $(2,3)$ and the point of intersection of the family of lines i.e., $(1,2)$ which is equal to
$$d=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}$$
so $$d= \sqrt{(2-1)^2+(3-2)^2}=\sqrt2$$
Now by the definition of locus of a point (locus of a point at a distance d from a given point is a circle of radius $d$) we can say that the locus of the required point is a circle of radius $\sqrt2$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Auto-format Code in Python in NPP or Online I do most of my Python coding in Notepad++. I would like a way to quickly and easily reformat my code using the default rules from PyCharm - things like spacing,  number of blank lines between functions etc.
I find black playground too harsh for my requirements, and opening up PyCharm to paste code and reformat it defeats to purpose of using Notepad++ (for it's lightness).
So do you know of either a plugin for Notepad++ which does this (and I'm not just referring to Python Indent), or an online resource which applies PyCharm style formatting to pasted code?

A: PyCharm comes with a CLI, like documented here https://www.jetbrains.com/help/pycharm/command-line-formatter.html.
Alternatively and making the call slightly shorter: parallel to the mentioned there general batch file, you probably also have 'format.bat'. You can integrate this into Notepad++ via the [F5] button "Run...":
Put there
C:\__YourPyCharmRoot__\bin\format.bat "$(FULL_CURRENT_PATH)"

and press the [Save] button in this "Run..." dialog to assign a short-cut.
Pressing the newly defined short-cut on a saved and writable Python file should let Notepad++ ask you after a while (of running PyCharm in Windows cmd.exe) to reload the changed file .


text:
Q: When is a comma appropriate before when? I have always refrained from using a comma before "when" but I heard that it is appropriate in certain circumstances. I can't picture a scenario where a comma is necessary before "when" to clarify the meaning of a sentence.
Thanks for the help.

A: If the when clause is restrictive, don't use a comma:

Do you remember that birthday party when I got drunk?

I've been to lots of birthday parties, but I'm talking about one in particular when I had too much to drink.  On the other hand:

Drive me home from the party under two conditions, when I'm drunk or when I start to sing

has a compound appositive naming the two conditions, and appositives are preceded by a comma.


text:
Q: compiling fileZilla on ubuntu 14.04 LTS I am trying to compiler FileZilla from its source code.
It requires C++ 14 support for which gcc4.9 is required.
Whatever higher version than 4.8, I try to install, there's no change.
Is gcc4.9 not available for the above ubuntu version?
The error I get is:
checking whether g++ supports C++14 features by default... no
checking whether g++ supports C++14 features with -std=gnu++14... no
checking whether g++ supports C++14 features with -std=gnu++1y... no
checking whether g++ supports C++14 features with -std=c++14... no
checking whether g++ supports C++14 features with -std=c++1y... no
configure: error: *** A compiler with support for C++14 language features is required

Can someone help ?

A: To install gcc-4.9 g++-4.9 may be helpful, and set it as your default gcc.
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install gcc-4.9 g++-4.9
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.9 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.9

Then gcc-4.9 will be available in your ubuntu version.
Notes : my version is ubuntu 14.04


text:
Q: jQuery class tabs removing It is a tabs, the active tab has a red dot and the inactive tab has grey dot but when i click the grey dot it will turn red all dot (remove all inactive class). Why happens this?

Profile

The Dic Approach

The partners

1Some content

2Some content

3Some content

Javascript
$(document).ready(function() {
    $("#tabs .dots .dot:not(:first)").addClass("inactive");
    $('.container').hide();
    $('.container:first').show();

    $("#tabs .dots .menu").click(function(){
      var t = $(this).attr("id");
      if($(".dot").hasClass("inactive")){
        $(".dot").addClass("inactive");
        $(".dot").removeClass("inactive");

        $(".container").hide();
        $("#" + t + "C").fadeIn("slow");
      }
    })
  });

A: If you change
$(".dot")

to
$(this).closest(".dots").find(".dot")

(or similar) then it will use the dot that matches the currently clicked-on menu
Updated snippet:

    $("#tabs .dots .dot:not(:first)").addClass("inactive");
    $('.container').hide();
    $('.container:first').show();

    $("#tabs .dots .menu").click(function(){
      var t = $(this).attr("id");
      var dot = $(this).closest(".dots").find(".dot");
      if (dot.hasClass("inactive")){
        $(".dot").addClass("inactive");
        dot.removeClass("inactive");

        $(".container").hide();
        $("#" + t + "C").fadeIn("slow");
      }
    })

.dot { color: red; float:left; }
.dot.inactive { color: #CCC; }

[.]

Profile

[.]

The Dic Approach

[.]

The partners

1Some content

2Some content

3Some content

A: when you are using global selector like $(".dot") it's get all elements with that (dot) class name


text:
Q: How can I declare and use Boolean variables in a shell script? I tried to declare a Boolean variable in a shell script using the following syntax:
variable=$false

variable=$true

Is this correct? Also, if I wanted to update that variable would I use the same syntax? Finally, is the following syntax for using Boolean variables as expressions correct?
if [ $variable ]

if [ !$variable ]

A: POSIX (Portable Operating System Interface)
I miss here the key point, which is portability. That's why my header has POSIX in itself.
Essentially, all of the voted answers are correct, with the exception they are Bash-specific too much.
Basically, I only wish to add more information about portability.

*

*[ and ] brackets like in [ "$var" = true ] are not necessary, and you can omit them and use the test command directly:
test "$var" = true && yourCodeIfTrue || yourCodeIfFalse

Important note: I no longer recommend this as it's being slowly deprecated and more difficult to combine multiple statements.

*Imagine what those words true and false mean to the shell, test it yourself:
echo $(( true ))

0

echo $(( false ))

1

But using quotes:
echo $(( "true" ))

bash: "true": syntax error: operand expected (error token is ""true"")
sh (dash): sh: 1: arithmetic expression: expecting primary: ""true""

The same goes for:
echo $(( "false" ))

The shell can't interpret it other than a string. I hope you are getting the idea of how good it is using proper keyword without quotes.
But no one said it in previous answers.

*What does this mean? Well, several things.

*

*You should get used to the Boolean keywords are actually treated like numbers, that is true = 0 and false = 1, remember all non-zero values are treated like false.

*Since they are treated as numbers, you should treat them like that too, i.e. if you define variable say:
var_bool=true
echo "$var_bool"

 true

you can create an opposite value of it with:
var_bool=$(( 1 - $var_bool ))  # same as $(( ! $var_bool ))
echo "$var_bool"

1

As you can see for yourself, the shell does print true string for the first time you use it, but since then, it all works via number 0 representing trueor 1 representing false, respectively.

Finally, what you should do with all that information

*

*First, one good habit would be assigning 0 instead of true; 1 instead of false.

*Second good habit would be to test if the variable is / isn't equal to zero:
if [ "$var_bool" -eq 0 ]; then
     yourCodeIfTrue
else
     yourCodeIfFalse
fi

A: Use arithmetic expressions.
#!/bin/bash

false=0
true=1

((false)) && echo false
((true)) && echo true
((!false)) && echo not false
((!true)) && echo not true

Output:

true
    not false

A: Long story short:
There are no Booleans in Bash
The true and false commands
Bash does have Boolean expressions in terms of comparison and conditions. That said, what you can declare and compare in Bash are strings and numbers. That's it.
Wherever you see true or false in Bash, it's either a string or a command/builtin which is only used for its exit code.
This syntax...
if true; then ...

is essentially...
if COMMAND; then ...

where the command is true. The condition is true whenever the command returns exit code 0. true and false are Bash builtins and sometimes also standalone programs that do nothing but returning the corresponding exit code.

Conditions in if..then..fi
When using square brackets or the test command, you rely on the exit code of that construct. Keep in mind that [ ] and [[ ]] are also just commands/builtins like any other. So ...
if [[ 1 == 1 ]]; then echo yes; fi

corresponds to
if COMMAND; then echo yes; fi

and the COMMAND here is [[ with the parameters 1 == 1 ]]
The if..then..fi construct is just syntactic sugar. You can always just run the commands separated by a double ampersand for the same effect:
[[ 1 == 1 ]] && echo yes

When using true and false in these testing constructs you are actually only passing the string "true" or "false" to the testing command. Here is an example:
Believe it or not but those conditions are all yielding the same result:
if [[ false ]]; then ...
if [[ "false" ]]; then ...
if [[ true ]]; then ...
if [[ "true" ]]; then ...

TL;DR; always compare against strings or numbers
To make this clear to future readers, I would recommend always using quotes around true and false:
DO
if [[ "${var}" == "true" ]]; then ...
if [[ "${var}" == "false" ]]; then ...
if [[ "${var}" == "yes" ]]; then ...
if [[ "${var}" == "USE_FEATURE_X" ]]; then ...
if [[ -n "${var:-}" ]]; then echo "var is not empty" ...

DON'T
# Always use double square brackets in bash!
if [ ... ]; then ...
# This is not as clear or searchable as -n
if [[ "${var}" ]]; then ...
# Creates impression of Booleans
if [[ "${var}" != true ]]; then ...
# `-eq` is for numbers and doesn't read as easy as `==`
if [[ "${var}" -eq "true" ]]; then ...

Maybe
# Creates impression of Booleans.
# It can be used for strict checking of dangerous operations.
# This condition is false for anything but the literal string "true".
if [[ "${var}" != "true" ]]; then ...

A: In many programming languages, the Boolean type is, or is implemented as, a subtype of integer, where true behaves like 1 and false behaves like 0:

*

*Boolean in C

*Boolean in Python

*Boolean in Java
Mathematically, Boolean algebra resembles integer arithmetic modulo 2. Therefore, if a language doesn't provide native Boolean type, the most natural and efficient solution is to use integers. This works with almost any language. For example, in Bash you can do:
# val=1; ((val)) && echo "true" || echo "false"
true
# val=0; ((val)) && echo "true" || echo "false"
false

man bash:

((expression))
The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION. If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. This is exactly equivalent to let "expression".

A: Regarding syntax, this is a simple methodology that I use (by example) to consistently and sanely manage Boolean logic:
# Tests
var=
var=''
var=""
var=0
var=1
var="abc"
var=abc

if [[ -n "${var}" ]] ; then
    echo 'true'
fi
if [[ -z "${var}" ]] ; then
    echo 'false'
fi

# Results
# var=        # false
# var=''      # false
# var=""      # false
# var=0       # true
# var=1       # true
# var="abc"   # true
# var=abc     # true

If the variable is never declared the answer is: # false
So, a simple way to set a variable to true (using this syntax methodology) would be, var=1; conversely, var=''.
Reference:
-n = True if the length of var string is non-zero.
-z = True if the length of var string is zero.

A: Bill Parker is getting voted down, because his definitions are reversed from the normal code convention. Normally, true is defined as 0 and false is defined as nonzero. 1 will work for false, as will 9999 and -1. The same with function return values - 0 is success and anything nonzero is failure. Sorry, I don't have the street credibility yet to vote or to reply to him directly.
Bash recommends using double brackets now as a habit instead of single brackets, and the link Mike Holt gave explains the differences in how they work. 7.3. Other Comparison Operators
For one thing, -eq is a numerical operator, so having the code
#**** NOTE *** This gives error message *****
The_world_is_flat=0;
if [ "${The_world_is_flat}" -eq true ]; then

will issue an error statement, expecting an integer expression. This applies to either parameter, as neither is an integer value. Yet, if we put double brackets around it, it will not issue an error statement, but it will yield a wrong value (well, in 50% of the possible permutations). It will evaluate to [[0 -eq true]] = success, but also to [[0 -eq false]] = success, which is wrong (hmmm.... what about that builtin being a numerical value?).
#**** NOTE *** This gives wrong output *****
The_world_is_flat=true;
if [[ "${The_world_is_flat}" -eq true ]]; then

There are other permutations of the conditional which will give wrong output as well. Basically, anything (other than the error condition listed above) that sets a variable to a numerical value and compares it to a true/false builtin, or sets a variable to a true/false builtin and compares it to a numerical value. Also, anything that sets a variable to a true/false builtin and does a comparison using -eq. So avoid -eq for Boolean comparisons and avoid using numerical values for Boolean comparisons. Here's a summary of the permutations that will give invalid results:
# With variable set as an integer and evaluating to true/false
# *** This will issue error warning and not run: *****
The_world_is_flat=0;
if [ "${The_world_is_flat}" -eq true ]; then

# With variable set as an integer and evaluating to true/false
# *** These statements will not evaluate properly: *****
The_world_is_flat=0;
if [ "${The_world_is_flat}" -eq true ]; then
#
if [[ "${The_world_is_flat}" -eq true ]]; then
#
if [ "${The_world_is_flat}" = true ]; then
#
if [[ "${The_world_is_flat}" = true ]]; then
#
if [ "${The_world_is_flat}" == true ]; then
#
if [[ "${The_world_is_flat}" == true ]]; then

# With variable set as an true/false builtin and evaluating to true/false
# *** These statements will not evaluate properly: *****
The_world_is_flat=true;
if [[ "${The_world_is_flat}" -eq true ]]; then
#
if [ "${The_world_is_flat}" = 0 ]; then
#
if [[ "${The_world_is_flat}" = 0 ]]; then
#
if [ "${The_world_is_flat}" == 0 ]; then
#
if [[ "${The_world_is_flat}" == 0 ]]; then

So, now to what works. Use true/false builtins for both your comparison and your evaluations (as Mike Hunt noted, don't enclose them in quotes). Then use either or single or double equal sign (= or ==) and either single or double brackets ([ ] or [[ ]]). Personally, I like the double equals sign, because it reminds me of logical comparisons in other programming languages, and double quotes just because I like typing. So these work:
# With variable set as an integer and evaluating to true/false
# *** These statements will work properly: *****
#
The_world_is_flat=true/false;
if [ "${The_world_is_flat}" = true ]; then
#
if [[ "${The_world_is_flat}" = true ]]; then
#
if [ "${The_world_is_flat}" = true ]; then
#
if [[ "${The_world_is_flat}" == true ]]; then

There you have it.

A: My receipe to (my own) idiocy:
# setting ----------------
commonMode=false
if [[ $something == 'COMMON' ]]; then
    commonMode=true
fi

# using ----------------
if $commonMode; then
    echo 'YES, Common Mode'
else
    echo 'NO, no Common Mode'
fi

$commonMode && echo 'commonMode is ON  ++++++'
$commonMode || echo 'commonMode is OFF xxxxxx'

A: Another way of using booleans is to test the emptyness of values. This has the advantage of making shorter tests:
first=1  # A true value
second=   # A false value

[ -n "$first" ]  && echo 'First var is true'
[ -z "$first" ]  && echo 'First var is false'
[ -n "$second" ] && echo 'Second var is true'
[ -z "$second" ] && echo 'Second var is false'

Output:
First var is true
Second var is false

Here is an alternative test syntax with bash: [[ -n $one ]]

A: Long ago, when all we had was sh, Booleans where handled by relying on a convention of the test program where test returns a false exit status if run without any arguments.
This allows one to think of a variable that is unset as false and variable set to any value as true. Today, test is a builtin to Bash and is commonly known by its one-character alias [ (or an executable to use in shells lacking it, as dolmen notes):
FLAG="up or <set>"

if [ "$FLAG" ] ; then
    echo 'Is true'
else
    echo 'Is false'
fi

# Unset FLAG
#    also works
FLAG=

if [ "$FLAG" ] ; then
    echo 'Continues true'
else
    echo 'Turned false'
fi

Because of quoting conventions, script writers prefer to use the compound command [[ that mimics test, but has a nicer syntax: variables with spaces do not need to be quoted; one can use && and || as logical operators with weird precedence, and there are no POSIX limitations on the number of terms.
For example, to determine if FLAG is set and COUNT is a number greater than 1:
FLAG="u p"
COUNT=3

if [[ $FLAG  && $COUNT -gt '1' ]] ; then
    echo 'Flag up, count bigger than 1'
else
    echo 'Nope'
fi

This stuff can get confusing when spaces, zero length strings, and null variables are all needed and also when your script needs to work with several shells.

A: There seems to be some misunderstanding here about the Bash builtin true, and more specifically, about how Bash expands and interprets expressions inside brackets.
The code in miku's answer has absolutely nothing to do with the Bash builtin true, nor /bin/true, nor any other flavor of the true command. In this case, true is nothing more than a simple character string, and no call to the true command/builtin is ever made, neither by the variable assignment, nor by the evaluation of the conditional expression.
The following code is functionally identical to the code in the miku's answer:
the_world_is_flat=yeah
if [ "$the_world_is_flat" = yeah ]; then
    echo 'Be careful not to fall off!'
fi

The only difference here is that the four characters being compared are 'y', 'e', 'a', and 'h' instead of 't', 'r', 'u', and 'e'. That's it. There's no attempt made to call a command or builtin named yeah, nor is there (in miku's example) any sort of special handling going on when Bash parses the token true. It's just a string, and a completely arbitrary one at that.
Update (2014-02-19): After following the link in miku's answer, now I see where some of the confusion is coming from. Miku's answer uses single brackets, but the code snippet he links to does not use brackets. It's just:
the_world_is_flat=true
if $the_world_is_flat; then
  echo 'Be careful not to fall off!'
fi

Both code snippets will behave the same way, but the brackets completely change what's going on under the hood.
Here's what Bash is doing in each case:
No brackets:

*

*Expand the variable $the_world_is_flat to the string "true".

*Attempt to parse the string "true" as a command.

*Find and run the true command (either a builtin or /bin/true, depending on the Bash version).

*Compare the exit code of the true command (which is always 0) with 0. Recall that in most shells, an exit code of 0 indicates success and anything else indicates failure.

*Since the exit code was 0 (success), execute the if statement's then clause

Brackets:

*

*Expand the variable $the_world_is_flat to the string "true".

*Parse the now-fully-expanded conditional expression, which is of the form string1 = string2. The = operator is bash's string comparison operator. So...

*Do a string comparison on "true" and "true".

*Yep, the two strings were the same, so the value of the conditional is true.

*Execute the if statement's then clause.

The no-brackets code works, because the true command returns an exit code of 0, which indicates success. The bracketed code works, because the value of $the_world_is_flat is identical to the string literal true on the right side of the =.
Just to drive the point home, consider the following two snippets of code:
This code (if run with root privileges) will reboot your computer:
var=reboot
if $var; then
  echo 'Muahahaha! You are going down!'
fi

This code just prints "Nice try." The reboot command is not called.
var=reboot
if [ $var ]; then
  echo 'Nice try.'
fi

Update (2014-04-14) To answer the question in the comments regarding the difference between = and ==: AFAIK, there is no difference. The == operator is a Bash-specific synonym for =, and as far as I've seen, they work exactly the same in all contexts.
Note, however, that I'm specifically talking about the = and == string comparison operators used in either [ ] or [[ ]] tests. I'm not suggesting that = and == are interchangeable everywhere in bash.
For example, you obviously can't do variable assignment with ==, such as var=="foo" (well technically you can do this, but the value of var will be "=foo", because Bash isn't seeing an == operator here, it's seeing an = (assignment) operator, followed by the literal value ="foo", which just becomes "=foo").
Also, although = and == are interchangeable, you should keep in mind that how those tests work does depend on whether you're using it inside [ ] or [[ ]], and also on whether or not the operands are quoted. You can read more about that in Advanced Bash Scripting Guide: 7.3 Other Comparison Operators (scroll down to the discussion of = and ==).

A: Here is an improvement on miku's original answer that addresses Dennis Williamson's concerns about the case where the variable is not set:
the_world_is_flat=true

if ${the_world_is_flat:-false} ; then
    echo "Be careful not to fall off!"
fi

And to test if the variable is false:
if ! ${the_world_is_flat:-false} ; then
    echo "Be careful not to fall off!"
fi

About other cases with a nasty content in the variable, this is a problem with any external input fed to a program.
Any external input must be validated before trusting it. But that validation has to be done just once, when that input is received.
It doesn't have to impact the performance of the program by doing it on every use of the variable like Dennis Williamson suggests.

A: In most cases you need "boolean" for boolean operations, such as ! && or ||. In some languages special boolean type do not exists at all (because in fact you do not need it technically), in most of interpreted languages (almost) all types automatically converted to some kind of boolean in operations like ! && or ||.
Boolean always is something that works with boolean operations. In Bash such operations are (no "" around $var, it's very important!):
[[ $var ]] - check if var is true
[[ ! $var ]] - check if var is false
[[ $var1 || $var2 ]] - var1 or var2
[[ $var1 && $var2 ]] - var1 and var2

[[ $var ]] is false only if var='' (or unset). So the only one correct 'false' value of variable in bash is '' (empty string). For true you can select any value, but I prefer var=1 (like in other languages, where true is any not-null int, but for readable purposes programmers always use 1).
NOTE: for var='false' var in boolean checks is true. In Bash string 'false' is actually true (same as in all other languages!). The only one difference between Bash and, e.g. Python, Perl or PHP, is that in Bash 0 is also true. But again: there are boolean operations in Bash, and they works like in all other interpreted languages, except that 0 in Bash is true.
It's absolutely irrational to use strings 'true' and 'false' as boolean replacement in Bash. It's like using same strange concept in Python, or Perl, or PHP. It works slower (in Bash too), and nobody do it in other languages, but in Bash there are a lot of coders that think it's a good solution. No. There are no reasons not to use boolean operations in Bash directly, without absolutely strange comparisons like $var == 'true' or $var == 'false'.
So again, boolean replacements in Bash are:
var=''  # false
var=1   # true (actually any non-empty string)

And direct usage of boolean checks in Bash also is a fastest way to do boolean-like checks. All other constructions will works much slower.
P.S. "old" style of "boolean" checks like a=true; if $a; then ... are absolutely idiotic, because:

*

*you can't use them directly in conditions [[ ]]

*they act as eval of bash code, stored in variable. Well, if you think it's a good idea, just do not ever write any program, please;)

P.P.S. If $var can be unset and you use very helpful set -u just replace $var in checks to ${var-}, e.g. [[ ${var-} ]] (also: no "" around, it's important for speed of code execution!)

A: Revised Answer (Feb 12, 2014)
the_world_is_flat=true
# ...do something interesting...
if [ "$the_world_is_flat" = true ] ; then
    echo 'Be careful not to fall off!'
fi

Original Answer
Caveats: https://stackoverflow.com/a/21210966/89391
the_world_is_flat=true
# ...do something interesting...
if $the_world_is_flat ; then
    echo 'Be careful not to fall off!'
fi

From: Using boolean variables in Bash
The reason the original answer is included here is because the comments before the revision on Feb 12, 2014 pertain only to the original answer, and many of the comments are wrong when associated with the revised answer. For example, Dennis Williamson's comment about bash builtin true on Jun 2, 2010 only applies to the original answer, not the revised.

A: Instead of faking a Boolean and leaving a trap for future readers, why not just use a better value than true and false?
For example:
build_state=success
if something-horrible; then
  build_state=failed
fi

if [[ "$build_state" == success ]]; then
  echo go home; you are done
else
  echo your head is on fire; run around in circles
fi

A:
How can I declare and use Boolean variables in a shell script?

Unlike many other programming languages, Bash does not segregate its variables by "type." [1]
So the answer is pretty clear. There isn't any Boolean variable in Bash.
However:
Using a declare statement, we can limit the value assignment to
variables.[2]
#!/bin/bash
declare -ir BOOL=(0 1) # Remember BOOL can't be unset till this shell terminates
readonly false=${BOOL[0]}
readonly true=${BOOL[1]}

# Same as declare -ir false=0 true=1
((true)) && echo "True"
((false)) && echo "False"
((!true)) && echo "Not True"
((!false)) && echo "Not false"

The r option in declare and readonly is used to state explicitly that the variables are readonly. I hope the purpose is clear.

A: TL;DR
my_bool=true

if [ "$my_bool" = true ]

Issues with Miku's (original) answer
I do not recommend the accepted answer1. Its syntax is pretty, but it has some flaws.
Say we have the following condition.
if $var; then
  echo 'Muahahaha!'
fi

In the following cases2, this condition will evaluate to true and execute the nested command.
# Variable var not defined beforehand. Case 1
var=''  # Equivalent to var="".      # Case 2
var=                                 # Case 3
unset var                            # Case 4
var='<some valid command>'           # Case 5

Typically you only want your condition to evaluate to true when your "Boolean" variable, var in this example, is explicitly set to true. All the other cases are dangerously misleading!
The last case (#5) is especially naughty because it will execute the command contained in the variable (which is why the condition evaluates to true for valid commands3, 4).
Here is a harmless example:
var='echo this text will be displayed when the condition is evaluated'
if $var; then
  echo 'Muahahaha!'
fi

# Outputs:
# this text will be displayed when the condition is evaluated
# Muahahaha!

Quoting your variables is safer, e.g. if "$var"; then. In the above cases, you should get a warning that the command is not found. But we can still do better (see my recommendations at the bottom).
Also see Mike Holt's explanation of Miku's original answer.
Issues with Hbar's answer
This approach also has unexpected behavior.
var=false
if [ $var ]; then
  echo "This won't print, var is false!"
fi

# Outputs:
# This won't print, var is false!

You would expect the above condition to evaluate to false, thus never executing the nested statement. Surprise!
Quoting the value ("false"), quoting the variable ("$var"), or using test or [[ instead of [, do not make a difference.
What I do recommend:
Here are ways I recommend you check your "Booleans". They work as expected.
my_bool=true

if [ "$my_bool" = true ]; then
if [ "$my_bool" = "true" ]; then

if [[ "$my_bool" = true ]]; then
if [[ "$my_bool" = "true" ]]; then
if [[ "$my_bool" == true ]]; then
if [[ "$my_bool" == "true" ]]; then

if test "$my_bool" = true; then
if test "$my_bool" = "true"; then

They're all pretty much equivalent. You'll have to type a few more keystrokes than the approaches in the other answers5, but your code will be more defensive.

Footnotes

*

*Miku's answer has since been edited and no longer contains (known) flaws.

*Not an exhaustive list.

*A valid command in this context means a command that exists. It doesn't matter if the command is used correctly or incorrectly. E.g. man woman would still be considered a valid command, even if no such man page exists.

*For invalid (non-existent) commands, Bash will simply complain that the command wasn't found.

*If you care about length, the first recommendation is the shortest.

A: My findings and suggestion differ a bit from the other posts. I found that I could use "booleans" basically as one would in any "regular" language, without the "hoop jumping" suggested...
There isn't any need for [] or explicit string comparisons... I tried multiple Linux distributions. I tested Bash, Dash, and BusyBox. The results were always the same. I'm not sure what the original top voted posts are talking about. Maybe times have changed and that's all there is to it?
If you set a variable to true, it subsequently evaluates as an "affirmative" within a conditional. Set it to false, and it evaluates to a "negative". Very straightforward! The only caveat, is that an undefined variable also evaluates like true! It would be nice if it did the opposite (as it would in most languages), but that's the trick - you just need to explicitly initialize your booleans to true or false.
Why does it work this way?  That answer is two fold. A) true/false in a shell really means "no error" vs "error" (i.e. 0 vs anything else). B) true/false are not values - but rather statements in shell scripting!  Regarding the second point, executing true or false on a line by itself sets the return value for the block you're in to that value, i.e. false is a declaration of "error encountered", where true "clears" that.  Using it with an assignment to a variable "returns" that into the variable. An undefined variable  evaluates like true in a conditional because that equally represents 0 or "no error encountered".
See the example Bash lines and results below. Test it yourself if you want to confirm...
#!/bin/sh

# Not yet defined...
echo "when set to ${myBool}"
if ${myBool}; then echo "it evaluates to true"; else echo "it evaluates to false"; fi;

myBool=true
echo "when set to ${myBool}"
if ${myBool}; then echo "it evaluates to true"; else echo "it evaluates to false"; fi;

myBool=false
echo "when set to ${myBool}"
if ${myBool}; then echo "it evaluates to true"; else echo "it evaluates to false"; fi;

Yields
when set to
it evaluates to true
when set to true
it evaluates to true
when set to false
it evaluates to false

A: I found the existing answers confusing.
Personally, I just want to have something which looks and works like C.
This snippet works many times a day in production:
snapshotEvents=true

if ($snapshotEvents)
then
    # Do stuff if true
fi

and to keep everyone happy, I tested:
snapshotEvents=false

if !($snapshotEvents)
then
    # Do stuff if false
fi

Which also worked fine.
The $snapshotEvents evaluates the contents of value of the variable.  So you need the $.
You don't really need the parentheses, I just find them helpful.

*

*Tested on: GNU Bash, version 4.1.11(2)-release

*Bash Guide for Beginners, Machtelt Garrels, v1.11, 2008

A: Here is a simple example which works for me:
temp1=true
temp2=false

if [ "$temp1" = true ] || [ "$temp2" = true ]
then
    echo "Do something."
else
    echo "Do something else."
fi

A: Here is an implementation of a short handed if true.
# Function to test if a variable is set to "true"
_if () {
    [ "${1}" == "true" ] && return 0
    [ "${1}" == "True" ] && return 0
    [ "${1}" == "Yes" ] && return 0
    return 1
}

Example 1
my_boolean=true

_if ${my_boolean} && {
    echo "True Is True"
} || {
    echo "False Is False"
}

Example 2
my_boolean=false
! _if ${my_boolean} && echo "Not True is True"

A: You can use shFlags.
It gives you the option to define: DEFINE_bool
Example:
DEFINE_bool(big_menu, true, "Include 'advanced' options in the menu listing");

From the command line you can define:
sh script.sh --bigmenu
sh script.sh --nobigmenu # False

A: This is a speed test about different ways to test "Boolean" values in Bash:
#!/bin/bash
rounds=100000

b=true # For true; b=false for false
type -a true
time for i in $(seq $rounds); do command $b; done
time for i in $(seq $rounds); do $b; done
time for i in $(seq $rounds); do [ "$b" == true ]; done
time for i in $(seq $rounds); do test "$b" == true; done
time for i in $(seq $rounds); do [[ $b == true ]]; done

b=x; # Or any non-null string for true; b='' for false
time for i in $(seq $rounds); do [ "$b" ]; done
time for i in $(seq $rounds); do [[ $b ]]; done

b=1 # Or any non-zero integer for true; b=0 for false
time for i in $(seq $rounds); do ((b)); done

It would print something like
true is a shell builtin
true is /bin/true

real    0m0,815s
user    0m0,767s
sys     0m0,029s

real    0m0,562s
user    0m0,509s
sys     0m0,022s

real    0m0,829s
user    0m0,782s
sys     0m0,008s

real    0m0,782s
user    0m0,730s
sys     0m0,015s

real    0m0,402s
user    0m0,391s
sys     0m0,006s

real    0m0,668s
user    0m0,633s
sys     0m0,008s

real    0m0,344s
user    0m0,311s
sys     0m0,016s

real    0m0,367s
user    0m0,347s
sys     0m0,017s

A: [[ "$x" == 'true' || "$x" -ne 0 ]] && ...

Is enough simple and has no dependencies.

A: Alternative - use a function
is_ok(){ :;}
is_ok(){ return 1;}
is_ok && echo "It's OK" || echo "Something's wrong"

Defining the function is less intuitive, but checking its return value is very easy.

A: Bash really confuses the issue with the likes of [, [[, ((, $((, etc.
All treading on each others' code spaces. I guess this is mostly historical, where Bash had to pretend to be sh occasionally.
Most of the time, I can just pick a method and stick with it. In this instance, I tend to declare (preferably in a common library file I can include with . in my actual script(s)).
TRUE=1; FALSE=0

I can then use the (( ... )) arithmetic operator to test thusly.
testvar=$FALSE

if [[ -d ${does_directory_exist} ]]
then
    testvar=$TRUE;
fi

if (( testvar == TRUE )); then
    # Do stuff because the directory does exist
fi

*

*You do have to be disciplined. Your testvar must either be set to $TRUE or $FALSE at all times.

*In (( ... )) comparators, you don't need the preceding $, which makes it more readable.

*I can use (( ... )) because $TRUE=1 and $FALSE=0, i.e. numeric values.

*The downside is having to use a $ occasionally:
testvar=$TRUE

which is not so pretty.
It's not a perfect solution, but it covers every case I need of such a test.


text:
Q: Convert a Pandas DataFrame with repetitive keys to a dictionary I have a DataFrame with two columns. I want to convert this DataFrame to a python dictionary. I want the elements of first column be keys and the elements of other columns in same row be values. However, entries in the first column are repeated -
Keys    Values
1       1
1       6
1       9
2       3
3       1
3       4

The dict I want is  - {1: [1,6,9], 2: [3], 3: [1,4]}
I am using the code - mydict=df.set_index('Keys').T.to_dict('list') however, the output has only unique values of keys. {1: [9], 2: [3], 3: [4]}

A: IIUC you can groupby on the 'Keys' column and then apply list and call to_dict:
In[32]:
df.groupby('Keys')['Values'].apply(list).to_dict()

Out[32]: {1: [1, 6, 9], 2: [3], 3: [1, 4]}

Breaking down the above into steps:
In[35]:
# groupby on the 'Keys' and apply list to group values into a list
df.groupby('Keys')['Values'].apply(list)
Out[35]:
Keys
1    [1, 6, 9]
2          [3]
3       [1, 4]
Name: Values, dtype: object

convert to a dict
In[37]:
# make a dict
df.groupby('Keys')['Values'].apply(list).to_dict()
Out[37]: {1: [1, 6, 9], 2: [3], 3: [1, 4]}

Thanks to @P.Tillman for the suggestion that to_frame was unnecessary, kudos to him

A: try this,
df.groupby('Keys')['Values'].unique().to_dict()

Output:
{1: array([1, 6, 9]), 2: array([3]), 3: array([1, 4])}


text: Q: How to make gnome-control-panel run on awesomewm? Gnome control panel does not properly run on awesomewm. Before GNOME 3, I used to run something called gnome-settings-daemon to get stuff like this working. How do I do this with GNOME 3, so that I can access my Ubuntu settings when running awesomewm? Should I maybe try a Xubuntu-based equivalent approach?


text:
Q: OnPostExecute is skipped When I call an Async class with new GiveMeJson2.execute(ref_id).get(),
my app goes into doInBackground, creates a JSON string and returns it.
At this point, I think that the app has to go into onPostExecute and parse that JSON.
public class LiveArrivalActivity extends AppCompatActivity {
ListViewLiveArrival adapter;
ListView listView;
public static ArrayList<LiveArrivalHelper> list = new ArrayList<LiveArrivalHelper>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_live_arrival);

    listView = findViewById(R.id.listView);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    Bundle b = getIntent().getExtras();
    Station station = (Station) b.get("Station");
    String ref_id = station.getRef_id();
    try {
        new GiveMeJson2().execute(ref_id).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    Log.i("OUT", list.toString());

    adapter = new ListViewLiveArrival(this, list);
    listView.setAdapter(adapter);
}    }

class GiveMeJson2 extends AsyncTask<String, Void, String> {
String jsonText = "";
@Override
protected String doInBackground(String... stations) {

    try {
        URL url = new URL("https://www.trola.si/" + stations[0]);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestProperty("Accept", "application/json");
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        jsonText = readAll(bufferedReader);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return jsonText;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    try {
        JSONArray jsonArray = new JSONObject(s).getJSONArray("stations");
        JSONArray buses = jsonArray.getJSONObject(0).getJSONArray("buses");
        for (int i = 0; i < buses.length(); i++) {
            JSONObject jsonObject = buses.getJSONObject(i);
            String direction = jsonObject.getString("direction");
            String number = jsonObject.getString("number");
            JSONArray arrivalsArray = jsonObject.getJSONArray("arrivals");

            if (arrivalsArray.length() > 0){
                String arrivals = "";
                for (int j = 0; j < arrivalsArray.length(); j++) {
                    arrivals += arrivalsArray.get(j) + " min ";
                }
                Log.i("OUT", number+direction+arrivals.toString());
                LiveArrivalHelper liveArrivalHelper = new LiveArrivalHelper(direction,number,arrivals);
                LiveArrivalActivity.list.add(liveArrivalHelper);
            }
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

private String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
        sb.append((char) cp);
    }
    return sb.toString();
} }

Any suggestions on why it's doing that?

A: When you call .get() on an AsyncTask, it forces it to be called synchronous. Which in this case is on the Main Thread.
That's not allowed.
So the AsyncTask enters doInBackground, then the Android system immediately throws an error.
If you look in your LogCat, the error will be printed there.
You need to remove .get() from your AsyncTask and actually handle it async.

A: When you call an AsyncTask class with .get() like new GiveMeJson2.execute(ref_id).get() than indeed onPreExecute and onPostExecute are not called.


text:
Q: Adding new attributes in existing coredata model I am a newbie to coredata never worked with it, right now, I am working on a project on which some work has already been done by the previous developer. Coredata is being used in saving data in the project, Now I need to add some new attributes in the existing coredata models but when I added the attribute (I added @property in the .h file and @dynamic in the .m), the setAttribute is working fine (though idk if it's getting written or not) but when I try to read the attribute the application gets crashed. I don't know much about the coredata, I tried a few blogs they're suggesting to use .xcdatamodel but in my case when I try to open this file the Xcode gets crashed. Now I am very much stuck in here. Kindly help me in this regard, right now I just need a pin point solution to just get through this situation. Thanks in advance for your consideration.

A: Yep, you need to blow away your old database file first. Do this whenever you make any model changes. On the simulator, select iOS Simulator -> Reset Content and Settings.
If it's on your device, delete the app completely.
Then, try again. This time the backing persistent store will be recreated according to your new model. You'll be good to go.

A: You should try to use Xcode 4 instead of Xcode 3.2.5


text:
Q: jquery datepicker not focussed after date is chosen, after postback datepicker doesn't work everytime the user selects a date from my datepicker the for some reason instead of staying focused on the are the date picker is in it scrolls to the top of the page.
Heres the function located at the bottom of my asp.net page under the

This is the code.

        <asp:Label ID="labdi1" runat="server" Text="*Date Issued:"></asp:Label>
        <asp:RequiredFieldValidator ID="p1divalidate" runat="server" ControlToValidate="pissued1"
        ErrorMessage="You Forgot The">*</asp:RequiredFieldValidator>

    <asp:TextBox ID="pissued1" runat="server" Width="45%"></asp:TextBox>

and also on postback my datepickers stop working. For example i have a dropdownlist that causes postback and if the user uses the drop downlist then the datepickers stop working

A: I'm not sure you're page is done loading before your datepicker() is initialized...Putting it at the bottom of the page kind of works, but I've stopped that myself personally and switched to:

my answer is not much, but it assures the page is done screwing around before your datepicker is started up.


text:
Q: Grid.RowDefinitions Height property not working with fixed value nor Auto in Xamarin.Forms It just won't happen. Here's the code (should someone notice, yeah, I posted almost the same code with a different problem a few hours ago, today is just not my day):
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:MovieDbApp.UI"
         x:Class="MovieDbApp.View.MoviesPage">
    <ContentPage.Content>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <ListView x:Name="listView" Grid.Row="0">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout VerticalOptions="FillAndExpand">
                                <Label Text="{Binding Title}"/>
                                <Image Source="{Binding PosterPath}" />
                                <Label Text="{Binding ReleaseDate}" />
                                <Label Text="{Binding DisplayGenre}" />
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </ContentPage.Content>
</ContentPage>

In StackLayout I've tried changing VerticalOptions to StartAndExpand, FillAndExpand, Fill and even EndAndExpand, but the row will always have the same height.
Out of spite, I removed VerticalOptions from StackLayout and set row height to 5000 but nope, it is still the same:

Running on Android emulator. No idea of what else to do.

A: Try setting HasUnevenRows="True" on the ListView or set the RowHeight property to some value. Without setting either of those two values, the ListView uses the default RowHeight for each cell.


text:
Q: mysql select to fetch rows grouped by columns in the same result row Table1:
bookid type
 1      A
 2      B
 3      A

Table 2
recordid bookid

  1         1
  1         2
  1         3

Is there a way to get the output as
recordid count(A) count(B)
  1           2       1

I tried grouping by left joining the two tables but that gives the output like this:
recordid type count
 1          A   2
 1          B   1

Please suggest the optimal way to get the required output.

A: You could try this:
SELECT
t2.recordid,
count(CASE WHEN t1.type='A' THEN 1 ELSE NULL END) as CountA,
count(CASE WHEN t1.type='B' THEN 1 ELSE NULL END) as CountB,
FROM Table1 t1
INNER JOIN Table2 t2 on t1.bookid=t2.bookid
GROUP BY t2.recordid

A: You can also use SUM() with expression,using sum with expression will result in a boolean 1 and 0 and you can get the count based on your conditions
SELECT
t2.recordid,
SUM( t1.type='A')  `CountA`,
SUM( t1.type='B')  `CountB`,
FROM Table1 t1
JOIN Table2 t2 USING(bookid)
GROUP BY t2.recordid

A: If you have limit column type value, I think very easy to do. But If you have so many column type value, seem have only one way is procedure with cursor to do.


text:
Q: Cannot insert explicit value for identity column in table 'MyTable' when IDENTITY_INSERT is set to OFF I added a new table called JobFieldMapping in my database, and set a field as a primary key, and the IDENTITY (1,1). I update the .edmx file.
So, all should be work well, but on the savechanges() I got the error:

Cannot insert explicit value for identity column in table 'JobFieldMapping' when IDENTITY_INSERT is set to OFF.

this is strange because I set nothing for the primary key field, in my code:
db.JobFieldMappings.Add(new JobFieldMapping {
            FKID = tempID,
            FieldName = "test",
            FieldTitle = "test"
        });
db.SaveChanges();

these are the properties for the PK field:

And this is the xml for the table
<EntityType Name="JobFieldMapping">
      <Key>
        <PropertyRef Name="JobFieldMappingID" />
      </Key>
      <Property Name="JobFieldMappingID" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
      <Property Name="FKID " Type="int" Nullable="false" />
      <Property Name="FieldName" Type="nvarchar" MaxLength="500" Nullable="false" />
      <Property Name="FieldTitle" Type="nvarchar" MaxLength="500" Nullable="false" />
 </EntityType>

I tried to update the .edmx file more times, delete and regenerate it, but I got always the same error.


text:
Q: Google Speech API unable to find a file on Google Storage: error 404 I am trying to convert audio clips [.flac format] to text using the google cloud speech api.I am using the python client library for making requests and  have a bucket on the GCP with a flat directory structure which is used to store the audio files and make asynchronous requests.Below is the python code for making requests
            from google.cloud import storage
            from google.cloud import speech
            from google.cloud.speech import enums
            from google.cloud.speech import types
            import json

            def AudioAnalyze(bucket_name):
                storage_client = storage.Client()
                speech_client = speech.SpeechClient()
                bucket = storage_client.get_bucket(bucket_name)
                bucket_contents = bucket.list_blobs()
                urls = []
                audio_content=[]
                for i in bucket_contents:
                        urls.append("gs://"+i.bucket.name+"/"+i.public_url.split("/")[-1])
                for gcs_uri in urls:
                    audio = types.RecognitionAudio(uri=gcs_uri)
                    config = types.RecognitionConfig(
                    encoding=enums.RecognitionConfig.AudioEncoding.FLAC,
                    sample_rate_hertz=44100,
                    language_code='en-US')
                    operation = speech_client.long_running_recognize(config,audio)
                    print(gcs_uri)
                    print('Waiting for operation to complete...')
                    response = operation.result(timeout=450)
                    speech2text=[]
                    for result in response.results:
                        for alternative in result.alternatives:
                            speech2text.append(alternative.transcript)
                    ad_content=" ".join(speech2text)
                    audio_content.append(ad_content)
                with open("path/to a/json file/file.json","w") as f:
                    json.dump(audio_content,f)

            if __name__=="__main__":
                    AudioAnalyze("adsaudiocontent")

I am encountering an error: google.api_core.exceptions.NotFound: 404 Requested entity was not found on a particular file present in the bucket while all the other files are being processed properly.The audio files have gone through a similar processing pipeline.The audio files are available on my public bucket:adsaudiocontent so that you can replicate the error.For Additional details here is the traceback.
                Traceback (most recent call last):
                  File "/home/pythonuser1/.virtualenvs/virtual_env/lib/python3.5/site-packages/google/api_core/grpc_helpers.py", line 54, in error_remapped_callable
                    return callable_(*args, **kwargs)
                  File "/home/pythonuser1/.virtualenvs/virtual_env/lib/python3.5/site-packages/grpc/_channel.py", line 487, in __call__
                    return _end_unary_response_blocking(state, call, False, deadline)
                  File "/home/pythonuser1/.virtualenvs/virtual_env/lib/python3.5/site-packages/grpc/_channel.py", line 437, in _end_unary_response_blocking
                    raise _Rendezvous(state, None, None, deadline)
                grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with (StatusCode.NOT_FOUND, Requested entity was not found.)>
                The above exception was the direct cause of the following exception:
                Traceback (most recent call last):
                  File "audioanalyze.py", line 40, in <module>
                    AudioAnalyze("adsaudiocontent")
                  File "audioanalyze.py", line 25, in AudioAnalyze
                    operation = speech_client.long_running_recognize(config,audio)
                  File "/home/pythonuser1/.virtualenvs/virtual_env/lib/python3.5/site-packages/google/cloud/speech_v1/gapic/speech_client.py", line 264, in long_running_recognize
                    request, retry=retry, timeout=timeout, metadata=metadata)
                  File "/home/pythonuser1/.virtualenvs/virtual_env/lib/python3.5/site-packages/google/api_core/gapic_v1/method.py", line 139, in __call__
                    return wrapped_func(*args, **kwargs)
                  File "/home/pythonuser1/.virtualenvs/virtual_env/lib/python3.5/site-packages/google/api_core/retry.py", line 260, in retry_wrapped_func
                    on_error=on_error,
                  File "/home/pythonuser1/.virtualenvs/virtual_env/lib/python3.5/site-packages/google/api_core/retry.py", line 177, in retry_target
                    return target()
                  File "/home/pythonuser1/.virtualenvs/virtual_env/lib/python3.5/site-packages/google/api_core/timeout.py", line 206, in func_with_timeout
                    return func(*args, **kwargs)
                  File "/home/pythonuser1/.virtualenvs/virtual_env/lib/python3.5/site-packages/google/api_core/grpc_helpers.py", line 56, in error_remapped_callable
                    six.raise_from(exceptions.from_grpc_error(exc), exc)
                  File "<string>", line 3, in raise_from
                google.api_core.exceptions.NotFound: 404 Requested entity was not found.

A: You are accidentally chopping part of the URL erroneously  with the "/" matching, which probably resulted in this error.
The bucket name from the class bucket can be used directly.


text:
Q: How to use default user properties with firebase Analytics I've read on the doc that firebase uses the Android Advertising ID or Apple IDFA to get demographics (age, gender) however this information doesn't show up in the analytics.
Is there some additional steps that need to be done in order to activate or link these informations to the Analytics? I'm currently using some custom userProperties but it would be good to know why the default ones doesn't work.

A: There are two places to check for demographics data:

*

*Analytics > Audiences section, what you probably want here is the audience that should be automatically created - "All users".

*Events > go into any event detail.

In both cases you should see location, gender, age. Also have in mind that because of privacy reasons

*

*you need at least a few users (I think the limit is 10) for some of this data to be shown, so it might not show up in small test project

*This data doesn't get exported to BigQuery at all - because then you could identify it with a particular user


text:
Q: Setting a value in MVC Sitemap node and accessing it in the action to differentiate, which button was clicked by user? How do I set a value in MVC SiteMap Node and Access it in the action.
I am attaching an image file with my problem scenario and my question?

Can some one suggest me, how do I solve this problem?


text:
Q: Determine where duplicate chars are in a string and add a hyphen between them I know similar questions have been asked but no answer was sufficient to what I am trying to obtain. I would like to write a program that takes a string and passes that string to a method. Once it is passed to the method the method shall take that string search through it and find where duplicate chars appear and add a hyphen between them. I would only like to use the charAt(), length() and or substring() methods from the java api. Just to clarify, if the string"Hello" is passed to my method, then the method would return "Hel-lo". I have written up a little bit of code below.
public class SeperateDuplicates
{
   public static void main(String[] args)
   {

      System.out.println(seperateDuplicatesChars("Hello"));
      /*System.out.println(seperateDuplicatesChars("Bookkeeper"));
      System.out.println(seperateDuplicatesChars("Yellowwood door"));
      System.out.println(seperateDuplicatesChars("Chicago Cubs"));
      */
   }

   public static String seperateDuplicatesChars(String str)
   {
      char[] arr = new char[str.length()];

      for(int i = 0; i < arr.length; i++)
      {
         arr[i] = str.charAt(i);
      }

      int counter = 0;

      for(int i = 0; i < arr.length; i++)
      {
         counter++;
         if(arr[i] == arr[i+1])
         {
            counter++;
         }

      }

   }

}

A: In case you task it to modify a String, but String is inmodifiable in java, and each time when you insert or remove character from it, a new string object is created. That's why in genral case, to create new string you have to use StringBuilder. You can get more info from JavaDoc of this class.
public static String separateDuplicatesChars(String str) {
    if (str == null)
        return null;
    if (str.trim().isEmpty())
        return str;

    char prv = '\0';
    StringBuilder buf = new StringBuilder(str.length());

    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);

        if (prv == ch)
            buf.append('-');

        buf.append(ch);
        prv = ch;
    }

    return buf.toString();
}

Or using length(), charAt() and substring() only:
public static String separateDuplicatesChars(String str) {
    if (str == null)
        return null;

    int size = str.length();
    int[] letters = new int[26];

    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        char base = ch >= 'A' && ch <= 'Z' ? 'A' : ch >= 'a' && ch <= 'z' ? 'a' : '\0';

        if (base == '\0')
            continue;

        int letter = str.charAt(i) - base;

        if (letters[letter] != 0)
            size++;

        letters[letter]++;
    }

    char[] arr = new char[size];

    for (int i = 0, j = 0; i < str.length(); i++, j++) {
        char ch = str.charAt(i);

        if (i > 0 && arr[i - 1] == ch)
            arr[j++] = '-';

        arr[j] = ch;
    }

    return new String(arr);
}

A: You're close. Just create a new String which you will return and as you loop through your char array build it up. In the case your need to add a hyphen, just add it as well.


text:
Q: Need to add custom values in Azure DevOps under Planning

How could I add custom values? I need to add custom values under the Planning section in work item for environments. I have tried to look in organizational settings, but I cannot really find the place where i can add such things. I have tried to Google this, but could not really found any relevant information. Any ideas? If you need more info, just ask!

A: I believe those are stored in Project Settings->Boards->Project Configuration, then click "Areas" or "Iterations" beneath the word "Boards".


text:
Q: How to use JQuery "after" selector I can't seem to figure out a good way to do this, but it seems like it should be simple.  I have an element that I want to append a div to.  Then I have another element that I want to clone and shove into that intermediate div.  Here's what I was hoping to do:
$("#somediv > ul").after("

").append($("#someotherdiv").clone());

This seems to be close, but not quite there.  The problem with this is that the "append" seems to be operating on the original #somediv > ul selector.  This sort of makes sense, but it's not what I wanted.  How can I most efficiently select that intermediate div that I added with the after and put my #someotherdiv into it?

A: Go the other way around and use insertAfter().
$("

")
    .append($("#someotherdiv").clone())
    .insertAfter("#somediv > ul")

Try to add your generated DOM nodes to the document only after finishing your work.
Once the nodes are added to the displayed document, the browser starts listening to any change to refresh the view. Doing all the work before adding the nodes to the displayed document does improve browser performance.

A: use insertAfter():
$("

").insertAfter("#somediv > ul").append($("#someotherdiv").clone())

A:
How can I most efficiently select that intermediate div that I added with the "after" and put my "#someotherdiv" into it?

@Vincent's solution is probably the fastest way to get the same result. However if for whatever reason you need add the div with after() then need to  select it and operate on it you can use

.nextAll( [expr] )
Find all sibling elements after the current element.
  Use an optional expression to filter the matched set.

So your js becomes:
$("#somediv > ul")
    .after("

")
    .nextAll('#xxx')
    .append($("#someotherdiv").clone());


text:
Q: how to access other file type through php im considering to create a resource file in php to read other file type??
for instance, instead of calling the image / javascript directly, i shall pass a query string to this resource.php indicating the type of file, and it would perform the same function as it is originally.
for instance:
using resource.php?type=js&file=alertme.js which would read alertme.js that alert("hello world");

A: Sounds like you want..
resource.php
<?php

if ( ! isset($_GET['type']) OR ! isset($_GET['file'])) {
   die('missing params');
}

$type = $_GET['type'];
$file = $_GET['file'];

if ( ! $file = realpath($file)) {
    die('file does not exist');
}

// Make sure the path does not go above our specific folder
$maxParentFolder = '/home/user/public_html/';

if ( ! preg_match('/^' . preg_quote($maxParentFolder, '/') . '/', $file)) {
   die('invalid path');
}

$mime = getMimeByExt($type);

header('Content-Type: ' . $mime);

readfile($file);

You need a function to get MIME types. Look here for further info.
Also, if type will always be the same as the file extension, you can omit it and get the extension using $ext = pathinfo($file, PATHINFO_EXTENSION).
Also, die() isn't the most useful error reporting. I have used it here just for an example.

A: I don't really know what the question is, but perhaps you're looking for readfile?


text:
Q: How do I use jQuery .when() function with a dynamic set of ajax calls? I'm using JqGrid and for each row in the grid I'm loading, I am making an ajax call to get additional data.
Once that's all complete, I need to apply some formatting.
I would like to use $.when(), but I'm not sure how to call it. I was researching the apply() method, but I still don't see how to use it appropriately.
Here is my code:
 $(rows).each(function () {
                        $.ajax(
                        {
                            url: url,
                            data: data,
                            success: function (result) {

                                }
                            }
                        });
                    });

   $.when(**What do i pass here??**).done(function () {

                    });

I had tried pushing each $.ajax call to an array, but I can't pass the array directly, and call everything.
Thanks in advance for your help!

A: This may not work at all, in fact I'm curious as to whether or not it will. Try building the array of promise objects, then call $.when.apply(null, arr).done(function () { ... });
apply allows you to trigger a function and pass an array of arguments dynamically, such as in this case.


text:
Q: C++; instantiating multiple instances of a class results in memory error Here is my source.cpp:
#include "BST.h"

using namespace std;

int main(){
    BST<int> test1;
    BST<int> test2;
    test1.insert(10);
    test1.insert(15);
    test1.insert(12);
    test1.insert(14);
    test1.insert(19);
    test1.test();
    cout << test1.contain(1) << endl;
    cout << test1.isEmpty() << endl;
    //cout << test2.isEmpty() << endl;
    cin.get();
    return 0;
}

And here is my header file:
//Haris
#include <iostream>
#include "Vector.h"

template <typename Comparable>
class BST
{
public:
    int size = 0;
    int currentRootindex = 0;
    BST(){
        for (int i = 0; i < 1000; i++){
            data[i] = NULL;
        }
    }
    ~BST(){

    }

    void insert(Comparable obj){

        if (data[0] == NULL){
            data[0] = obj;
            size++;

        }
        else{

            for (int index = 0; index < size; index++){
                if (data[currentRootindex] < obj && data[(2 * currentRootindex) + 2] == NULL){
                    data[(2 * currentRootindex) + 2] = obj;
                    size++;

                    break;
                }
                else if (data[currentRootindex] >= obj && data[(2 * currentRootindex) + 1] == NULL){
                    data[(2 * currentRootindex) + 1] = obj;

                    size++;
                    break;
                }
                else if (data[currentRootindex] < obj){
                    currentRootindex = ((2 * currentRootindex) + 2);

                }
                else{
                    currentRootindex = ((2 * currentRootindex) + 1);

                }

            }
        }
        currentRootindex = 0;
    }
    bool isEmpty(){
        if (data[0] == NULL){
            return true;
        }
        else
            return false;
    }
    bool contain(Comparable obj){
        for (int index = 0; index < size; index++){
             if (data[currentRootindex] < obj){
                currentRootindex = ((2 * currentRootindex) + 2);

            }
             else if (data[currentRootindex] > obj){
                 currentRootindex = ((2 * currentRootindex) + 1);

             }
             else
                 return true;

        }
        return false;
    }
    void test(){

        cout << data[5] << endl;

    }

private:
    Vector<Comparable> data;

};

if I comment out the BST<int>test2 from source.cpp, the code works as intended.
But when i instantiate BST<int>test2 after BST<int>test1, I get Application Error: The memory could not be read. I have not declared any static variables, so none of the variables is being shared across different objects.
Also, the Vector header file, I am using is
#ifndef VECTOR_H
#define VECTOR_H

#include <algorithm>
#include <iostream>

template <typename Object>
class Vector
{
public:
    explicit Vector( int initSize = 0 )
    : theSize{ initSize }, theCapacity{ initSize + SPARE_CAPACITY }
    { objects = new Object[ theCapacity ]; }

    Vector( const Vector & rhs )
    : theSize{ rhs.theSize }, theCapacity{ rhs.theCapacity }, objects{ nullptr }
    {
        objects = new Object[ theCapacity ];
        for( int k = 0; k < theSize; ++k )
            objects[ k ] = rhs.objects[ k ];
    }

    Vector & operator= ( const Vector & rhs )
    {
        Vector copy = rhs;
        std::swap( *this, copy );
        return *this;
    }

    ~Vector( )
    { delete [ ] objects; }

    Vector( Vector && rhs )
    : theSize{ rhs.theSize }, theCapacity{ rhs.theCapacity }, objects{ rhs.objects }
    {
        rhs.objects = nullptr;
        rhs.theSize = 0;
        rhs.theCapacity = 0;
    }

    Vector & operator= ( Vector && rhs )
    {
        std::swap( theSize, rhs.theSize );
        std::swap( theCapacity, rhs.theCapacity );
        std::swap( objects, rhs.objects );

        return *this;
    }

    bool empty( ) const
    { return size( ) == 0; }
    int size( ) const
    { return theSize; }
    int capacity( ) const
    { return theCapacity; }

    Object & operator[]( int index )
    {
        return objects[ index ];
    }

    const Object & operator[]( int index ) const
    {
        return objects[ index ];
    }

    void resize( int newSize )
    {
        if( newSize > theCapacity )
            reserve( newSize * 2 );
        theSize = newSize;
    }

    void reserve( int newCapacity )
    {
        if( newCapacity < theSize )
            return;

        Object *newArray = new Object[ newCapacity ];
        for( int k = 0; k < theSize; ++k )
            newArray[ k ] = std::move( objects[ k ] );

        theCapacity = newCapacity;
        std::swap( objects, newArray );
        delete [ ] newArray;
    }

    // Stacky stuff
    void push_back( const Object & x )
    {
        if( theSize == theCapacity )
            reserve( 2 * theCapacity + 1 );
        objects[ theSize++ ] = x;
    }
    // Stacky stuff
    void push_back( Object && x )
    {
        if( theSize == theCapacity )
            reserve( 2 * theCapacity + 1 );
        objects[ theSize++ ] = std::move( x );
    }

    void pop_back( )
    {
        --theSize;
    }

    const Object & back ( ) const
    {
        return objects[ theSize - 1 ];
    }

    // Iterator stuff: not bounds checked
    typedef Object * iterator;
    typedef const Object * const_iterator;

    iterator begin( )
    { return &objects[ 0 ]; }
    const_iterator begin( ) const
    { return &objects[ 0 ]; }
    iterator end( )
    { return &objects[ size( ) ]; }
    const_iterator end( ) const
    { return &objects[ size( ) ]; }

    static const int SPARE_CAPACITY = 2;

private:
    int theSize;
    int theCapacity;
    Object * objects;
};

#endif

A: You're accessing out of bounds indices of the data vector. The default vector constructor initialises with size 0 (although it allocates 2 extra elements) but then you immediately try to access up to index 999:
BST(){
    for (int i = 0; i < 1000; i++){
        data[i] = NULL;
    }
}

The second object isn't really related to the problem. Even with only one object, the code is still accessing memory it shouldn't.
Changing the data vector to initialise with size 1000 fixes the out of bounds errors for this particular code, but I suspect the BST class will cause more of these errors in future because I can't see any checks against the data vector's size.


text:
Q: Efficient ways of inserting a new cell into a sorted UITableView? I am trying to insert a new cell into a table view where the data is sorted. Is there an easy & efficient way to do this using the API?
The easiest way seems to be insert the new data into an NSMutableArray, sort using a sort descriptor, and call reloadData. This should only redisplay the visible rows, so it doesn't look too bad.
Would it be worthwhile to do a binary search on the data array, insert the data and then insert the cell?

A: It really depends on how many rows are in your table. If your table only has around 10 rows, simply adding the data to your NSMutableArray, resorting, and reloading the UITableView should be just fine.
On the other hand, if your table has hundreds or thousands of rows, you are definitely going to want to do something more efficient. Using a binary search to insert your data into your NSMutableArray is a good idea. Then all you have to do is call UITableView's insertRowsAtIndexPaths:withRowAnimation: to add the row to the actual table view. No reloading required.


text:
Q: Add product according to category in Django I am new in Django. I want to add product against the category which I select, but I don't know how can I do that. I select the category and add product but nothing happened. I don't know how can I do this. Thank you in advance
Model.py
    class Product(models.Model):
          category = models.ForeignKey(Category, on_delete=models.CASCADE)
          name = models.CharField(max_length=30)
          price = models.IntegerField()

view.py
  class SelectCategory(TemplateView):

        template_name = 'purchase/selectCategory.html'

        def get(self, request, *args, **kwargs):
            categories = CategoryModel.objects.all()
            args = {'categories': categories}
            return render(request, self.template_name, args)

       def post(self, request):
           try:
              data = self.request.POST.get
              categoryId = ProductModel.category['category.id'].id
              product = ProductModel(
                 category_id=data(categoryId),
                 name=data('name'),
                 price=data('price')
              )
              product.save()
              return redirect('menu')
         except Exception as e:
              return HttpResponse('failed{}'.format(e))

Template
 {% extends 'auth/home.html' %}

 {% block content %}
   <form method="get">
    {% csrf_token %}
       Select Category
         <select name="Select Category">
           <option disabled="disabled" selected> Select Category</option>
              {% for category in categories %}

              <option value={{ category.id }}>
                  {{ category.name }}
              </option>
              {% endfor %}
        </select>

  <input type="submit" value="Select">
  </form>
<form method="post">
{% csrf_token %}
     Name
        <input type="text" name="name" id="name" placeholder="Enter Product name">

    Price
         <input type="number" name="price" id="price" placeholder="Enter Price of Product">

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

    <button>Menu</button>

</form>

 {% endblock %}

A: Get the category instance first using data selected category id and then push that instance to as a parameter to productmodel.
def post(self, request):
           try:
              data = self.request.POST.get
              categoryObj= CategoryModel.objects.get(I'd=data[])
              product = ProductModel(
                 category_id= categoryObj
                 name=data('name'),
                 price=data('price')
              )
              product.save()
              return redirect('menu')
         except Exception as e:
              return HttpResponse('failed{}'.format(e))


text:
Q: Post as link type with Facebook Graph API I am using the Facebook Graph API to publish on a user's wall. I give it these parameters:
message
name
description
picture
link
caption

It posts to the wall, but it is not treating it as a link. I know this because it does not open a new tab when the link is clicked, there is no share action link, and Twitter does not pick it up because I have it filtering my wall by links only.
I see the Facebook docs has two separate documentation pages for publish "Post" and "Link" objects.. but the links is posting to the same graph path so I am not sure how it is supported to work:
http://developers.facebook.com/docs/reference/api/post
http://developers.facebook.com/docs/reference/api/link
Anyone got this working?

A: Use the facebook API's available on codeplex.com and try this out,
Facebook.Rest.attachment_media_image image1 = new attachment_media_image();

image1.href = "";
image1.src = "";

Facebook.Rest.attachment a = new Facebook.Rest.attachment();
a.media = new List<Facebook.Rest.attachment_media> { image1 };
a.href = "";
a.name = "";
a.caption = "{*actor*}";
a.properties = null;

if(fbapi.Users.HasAppPermission(Enums.ExtendedPermissions.publish_stream))
    fbapi.Stream.Publish(" Your message", a,
                         new List<action_link>()
                         {
                             new action_link()
                             {
                                 text = "",
                                 href = ""
                             }
                         },
                         null, 0);

A: What I do when using the open graph is this:
var uri = new Uri(
    "https://graph.facebook.com/me/links?access_token=" + AccessToken);

var data =
    message != null
        ? string.Format(
            "link={0}&message={1}",
            Uri.EscapeDataString(link),
            Uri.EscapeDataString(message))
        : string.Format("link={0}", Uri.EscapeDataString(link));

// (parameters other than link and message are grabbed from a website anyway)

WebClient client = new WebClient();
client.Headers["Content-type"] = "application/x-www-form-urlencoded";
client.Encoding = Encoding.UTF8;
client.UploadStringAsync(uri, "POST", data);


text:
Q: Remoting Event Handling: Specifying an available range of listening ports I have a client-server application that uses .NET remoting.
The server sends update event to the client via .NET events. (That was a big deal to get working, but it has been deployed for seven months without problems.)
To be able to listen to events, the client has to create a listening channel. My app.config file specifies port "0", meaning "any available port".
All good, but now the customer's network administrators are trying to tighten up the firewalls. They asked if we can use a fixed port. I replied that this would be possible, but then you wouldn't be able to have multiple clients running on the same machine. You also couldn't have multiple users using the application from the same Citrix server. (Please correct me if I'm wrong)
Now they are asking if I can specify a range of ports that the client application can pick from.
Does anyone know of a straightforward way to do this: make it so that the client creates a listening channel on the first available port within a range?


text:
Q: CSS in Master and regular pages I have some pages that use the master page and apply a theme. Some of my pages are not using master pages, instead they have individual css files linked
<link href="../Style/pck.css" rel="stylesheet" type="text/css" />

Although the css works for regular pages for most cases, the body css is taken from the theme. I do not want that. I want that the body css should be taken from pck.css.
What to do?

A: On the pages that the CSS file is not working, have you checked to make sure that it actually loading the CSS file? (with the relative CSS link, it might not be working for pages that a deeper into your site structure).
Alternatively, I sometimes find that the  needs to be the very first thing on the page or you force some browsers into compatibility mode and all hell breaks loose when that happens.


text:
Q: Immediate/Force Azure File Sync So I've been looking for a solution to Immediately syncing files uploaded to Azure in Azure File Sync and hadn't found any solutions.
I found this round-a-bout way of doing it, so I thought I would share it so other people who want to use this service have a word around while Microsoft implements it properly
Method

*

*Create a duplicate of the item you want to pull from Azure (e.g. Foo.exe). Make sure its larger than 64KiB

*Azure File Sync will upload it to the Cloud and also pull down the duplicate item (the one you wanted) but it will append a "- Cloud" to the duplicate file. (So now you have Foo.exe and Foo - Cloud.exe)

*Delete the file you created (Foo.exe)

*Remove "- Cloud" from the file that was pulled from the cloud (Foo - Cloud.exe -> Foo.exe)

*Your done

I've also made the comment here https://feedback.azure.com/forums/217298-storage/suggestions/33072151-enable-immediate-sync-after-changes-on-the-azure-f (but messed up the file size requirement)

A: Method

*

*Create a duplicate of the item you want to pull from Azure (e.g. Foo.exe). Make sure its larger than 64KiB

*Azure File Sync will upload it to the Cloud and also pull down the duplicate item (the one you wanted) but it will append a "- Cloud" to the duplicate file. (So now you have Foo.exe and Foo - Cloud.exe)

*Delete the file you created (Foo.exe)

*Remove "- Cloud" from the file that was pulled from the cloud (Foo - Cloud.exe -> Foo.exe)

*Your done


text:
Q: Is this an appropriate use of an AngularJS Service? I have an app with many views that are varied and numerous enough to justify dynamically loading CSS files, based on which view is active at the time.
I looked into various ways of dynamically 'loading' CSS files with angular, and even found a plugin that worked, though it was kind of clunky in its implementation.
I did some research on a native JS way to do this and decided to implement it in a more 'angular way'. I inject the service below into the routes' controller.
Is my method of implementation (using a service) correct? If not, what is the correct venue for logic of this kind?
HTML:
<head>
...
    <link id="library-css" href="~/Styles/libraryCSS" rel="stylesheet" type="text/css" disabled />
    <link id="results-css" href="~/Styles/resultsCSS" rel="stylesheet" type="text/css" disabled />
...
</head>

The AngularJS Service:
myServices.service("CSSLoader", [function () {

    var cssLinks = {},
        linkToActivate = {};

    (function init() {
        //loading the <link> elements into the cssLinks object for later retrieval
        cssLinks = {
            library: document.getElementById("library-css"),
            results: document.getElementById("results-css")
        };
    })();

    this.loadCSS = function (cssReference, retainPreviouslyLoadedCSS) {
        if (!cssReference) { throw "CSS Link must be provided.";}

        if (!retainPreviouslyLoadedCSS) {
            //first disables any links that are active
            for (var cnt in cssLinks) {
                cssLinks[cnt].disabled = true;
            }
        }

        linkToActivate = cssLinks[cssReference];
        if (!linkToActivate) { throw "CSS Link, (" + cssReference + "), that was provided cannot be found."; }

        linkToActivate.disabled = false;
    };

}]);

Thanks!

A: please find a plunker I created for you.
It is based on a directive that watches a scope variable that corresponds to its own id.
app.directive('disablecss', function() {
  return {
    link: function(scope, element, attrs) {
      scope.$watch('cssToSet.'+attrs.id, function(value,oldvalue) {

where the attrs.id corresponds to the link id where the directive is set
   <link href="resultCSS.css" id="resultCSS" rel="stylesheet" disablecss />
    <link href="libraryCSS.css" id="libraryCSS" rel="stylesheet" disablecss />

The scope attribute is automaticaly modified by the controller associated to the partial views
app.config(function($routeProvider) {
  $routeProvider.
    when('/view1', {
        controller:'View1Ctrl',
        templateUrl:'partial1.html'
    }).
    when('/view2', {
        controller:'View2Ctrl',
        templateUrl:'partial2.html'
    }).
    otherwise({redirectTo:'/'});
});

app.controller('View1Ctrl',['$scope',function($scope,$rootscope){
  $scope.cssToSet.resultCSS=true;
  $scope.cssToSet.libraryCSS=false;
}]);

idem for View2Ctrl

Do not hesitate if something is not clear.Bye


text:
Q: Change Imageview's image outside recyclerview on a clickevent of recyclerview item I want to update Imageview's image on the click of a recyclerview item. Below I have posted my layout screenshot:

Small images are in recycler view and the big green image is outside of recycler view.
//my recycler view adapter code

Context mContext;
List<imgModel> mImgModelList;
String imgUrl;

public imageListAdapter(Context context, List<imgModel> imgModelList) {
    mContext = context;
    mImgModelList = imgModelList;
}

@NonNull
@Override
public imgListHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

    LayoutInflater inflater = LayoutInflater.from(mContext);
    View view = inflater.inflate(R.layout.img_card,viewGroup,false);
    imgListHolder imgListHolder = new imgListHolder(view);

    return imgListHolder;
}

@Override
public void onBindViewHolder(@NonNull imgListHolder imgListHolder, int i) {
    final imgModel current = mImgModelList.get(i);
    imgUrl = mImgModelList.get(0).getImgUrl();
    Picasso.get().load(current.getImgUrl()).into(imgListHolder.mImageView);

    imgListHolder.mImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           imgUrl = current.getImgUrl();
        }
    });
}

@Override
public int getItemCount() {
    return mImgModelList.size();
}

class imgListHolder extends RecyclerView.ViewHolder{
    ImageView mImageView;
    public imgListHolder(@NonNull View itemView) {
        super(itemView);
        mImageView = (ImageView)itemView.findViewById(R.id.singleimg);
    }
}

}
// it is the activity class
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image_list_);

    final Intent myIntent = getIntent();
    final String cateGory = myIntent.getStringExtra("Category");
    String subCategory = myIntent.getStringExtra("subCategory");
    mRelativeLayout = (RelativeLayout)findViewById(R.id.imgListLayout);
    selectedImage =(ImageView)findViewById(R.id.selectedImg);

    //mToolbar =(Toolbar)findViewById(R.id.toolbar);
   mRecyclerView = (RecyclerView)findViewById(R.id.imglistRecycler);
   //mToolbar.inflateMenu(R.menu.menu);
    data = new ArrayList<>();
   myRef.child(cateGory).child(subCategory).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
          for (DataSnapshot category : dataSnapshot.getChildren()) {
                if (category.child("like").exists()) {
                    imgModel temp = new imgModel(category.child("imgUrl").getValue().toString(), category.child("views").getValue().toString(),
                            category.child("like").getValue().toString(), category.child("share").getValue().toString());
                    data.add(temp);
                }

                mImageListAdapter = new imageListAdapter(imageList_Activity.this,data);
                mRecyclerView.setAdapter(mImageListAdapter);
                mRecyclerView.setLayoutManager(new GridLayoutManager(imageList_Activity.this,3));

            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

}
I want, when user will click any recycler view image means the small images, it will show in big imageview which is outside of recycler view.

A: You can use an interface to update the selected image. create an interface in your adapter eg :
 interface UpdateImage{
    void updateImageUrl(String imageurl);
}

Now implement this interface in your activity. While setting your adapter just add
 new imageListAdapter(imageList_Activity.this,data,this);
Now on onClick of the item just call
imgListHolder.mImageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       imgUrl = current.getImgUrl();
       updateImage.updateImageUrl(current.getImgUrl())
    }
});

In your activity, when you implement the above interface you will get an override method updateImageUrl. You can update your image view with this URL.
@Override
public void updateImageUrl(String imageurl) {
    Glide.with(this).load(imageUrl).into(imageView)
}

A: As Raghavendra said, make an interface class then pass it in inside adapter.
Have your activity implements that interface and pass in your activity inside the adapter.
Interface OnClick{
   public void clickAction()
}

//your adapter class
Adapter {
   //your interface
   public OnClick onclick;
   //set your imageview click activity
   imageView.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
      onClick.click;
   }});

//now pass your interface from activity
ImageListActivity implements OnClick {
   //pass to your adapter
   adapter.onClick = this
}


text:
Q: How to configure pxelinux.cfg/default properly in order to install Ubuntu from network? I'm trying to set up PXE in order to install Ubuntu 13.10 Server x64 through local network. So far, I can boot through PXE and, when using pxelinux.cfg/default provided by default, be able to install Ubuntu by downloading it from a mirror.
I want to be able to install Ubuntu from NFS. I edited pxelinux.cfg/default like this:
1  # D-I config version 2.0
2  default ubuntu-installer/amd64/boot-screens/vesamenu.c32
3  menu title Ubuntu setup
4  label ubuntu-13.10-server-amd64
5          menu label ubuntu-13.10-server-amd64
6          kernel 3.11.0.18-generic
7          append netboot=nfs initrd=install/initrd.gz nfsroot=192.168.1.75:/↵
   exports/ubuntu-13.10-server-amd64 ip=dhcp rw

*

*192.168.1.75 is the IP of the server I use for DHCP, DNS and NFS,

*I got the kernel 3.11.0.18-generic by running uname -r,

*showmount -e 192.168.1.75 gives:

Export list for 192.168.1.75:
/exports/ubuntu-13.10-server-amd64 192.168.1.0/24

The directory contains the contents of the original ubuntu-13.10-server-amd64 image.
When booting from PXE, I get the original screen (see screenshots below), then another one. Pressing Tab shows the command:

3.11.0.18-generic netboot=nfs initrd=install/initrd.gz nfsroot=192.168.1.↵
75:/exports/ubuntu-13.10-server-amd64 ip=dhcp rw

Pressing Enter does nothing.
I imagine there is something wrong with my changes of pxelinux.cfg/default.
What's wrong with it?
Is there a comprehensive documentation of the options to set?
Are there logs which can help understanding what is wrong?

A: It sounds like your kernel and init are not loading (hence the hang). Are you sure your paths are correct? Also, check your filenames -- I'm not sure where you got 3.11.0.18-generic, my 14.04 server DVD netboot kernel is a file called "linux".
This line:
6          kernel 3.11.0.18-generic

Implies that a file called 3.11.0.18-generic exists in the root of your TFTP server, e.g. something like \tftpboot\3.11.0.18-generic or \var\lib\tftp\3.11.0.18-generic. Let's call this TFTPROOT. Similarly for install/initrd.gz - is there a file TFTPROOT/install/initrd.gz?
Your path on line 2 (default ubuntu-installer/amd64/boot-screens/vesamenu.c32) implies that you've copied the contents of DVDISO/install/netboot into your TFTP server root. E.g. you've likely got a folder called TFTPROOT/ubuntu-installer. However, the proper kernel and init file for netboot are(for me) contained in DVDISO/install/netboot/ubuntu-installer/amd64. So your paths should be kernel ubuntu-installer/amd64/linux and append initrd=ubuntu-installer/amd64/initrd.gz ...

A: I had that problem, and could hit enter after changing file permission for kernel and inird.
Try with setting chmod 777 3.11.0.18-generic


text:
Q: Is the following generalization of Jensen's inequality known? I believe the following statement is true, but I can't find a proof anywhere. Does someone know if there is a reference or if it has a name?

Let $f : \mathbb{R} \to \mathbb{R}$ be convex. Let $X$ be a random variable so that $f(X)$ is defined.  Let $\gamma \in [0,1]$. If $\mathbb{E}[X]=0$, then $\mathbb{E}[f(\gamma X)] \leq \mathbb{E}[f(X)]$.

Setting $\gamma=0$ is simply Jensen's inequality.

A: The result is a corollary of Jensen's inequality. If $\gamma\in[0,1]$ then by convexity
$$f(\gamma X)=f(\gamma X + (1-\gamma)0)\le
\gamma f(X)+(1-\gamma)f(0).$$
Taking expectations,
$$
{\mathbb E}[f(\gamma X)]\le \gamma {\mathbb E}[f(X)]+(1-\gamma) f(0).
$$
But $f(0)=f({\mathbb E}[X])$, and by Jensen this last is at most ${\mathbb E}[f(X)]$. Finally $1-\gamma\ge0$, so $$(1-\gamma)f(0)\le(1-\gamma){\mathbb E}[f(X)],$$
and the result is proved. (So the result is both a generalization and a corollary of Jensen...)


text:
Q: Regex that returns hashtags with hash sign but excludes @ mentions I have a regex that returns the words (excludes @mentions includes hashtags but removes the hash sign #)
import re
pattern=r'(?u)(?<![@])\b\w\w+\b'
pattern=re.compile(pattern)
pattern.findall('this is a tweet #hashtag @mention')

This returns
['this', 'is', 'tweet', 'hashtag']

What I need is a modification to this regex that returns the hash sign with hashtag so it should return:
['this', 'is', 'tweet', '#hashtag']

Note that my question is different from returning just @mentions and #hashtags I want both regular words and hashtags but I don't want @mentions.

A: Adding '#?' to the pattern will let it match words that start with 0 or 1 hash symbols.
import re
pattern=r'(?u)(?<![@])#?\b\w\w+\b'
pattern=re.compile(pattern)
results = pattern.findall('this is a tweet #hashtag @mention')
print(results)

Resulting in:
['this', 'is', 'tweet', '#hashtag']