Q: This is a number guessing game the num_check function works just fine the first time but won't run any second attempts. Does anyone know why? import random

# Define function - Number Generator
def num_gen():

    num = random.randrange(1, 101)
    return num

# Define function - Number Check
def num_check(x, y):

    result = ''
    if x > y:
        result = 'high'
    elif x < y:
        result = 'low'
    else:
        result = 'correct'
    return result

# Call - Number Generator
num = num_gen()

# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))

att = 1

# Process - Guess and Display Result
result = num_check(guess, num)

if result == 'high':

    guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
    att += 1
    result = num_check(guess, num)

elif result == 'low':

    guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
    att += 1
    result = num_check(guess, num)

else:

    print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')

A: After getting input from console, you should create a loop which breaks when guessed number equal to input. For example:
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))

att = 1

# Process - Guess and Display Result
result = num_check(guess, num)

while result != guess:

    if result == 'high':

        guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
        att += 1
        result = num_check(guess, num)

    elif result == 'low':

        guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
        att += 1
        result = num_check(guess, num)

    else:
        break

print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')

After revision, code seems like:
import random

# Define function - Number Generator
def num_gen():

    num = random.randrange(1, 101)
    return num

# Define function - Number Check
def num_check(x, y):

    result = ''
    if x > y:
        result = 'high'
    elif x < y:
        result = 'low'
    else:
        result = 'correct'
    return result

# Call - Number Generator
num = num_gen()

# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))

att = 1

# Process - Guess and Display Result
result = num_check(guess, num)

while result != guess:

    if result == 'high':

        guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
        att += 1
        result = num_check(guess, num)

    elif result == 'low':

        guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
        att += 1
        result = num_check(guess, num)

    else:
        break

print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')

A: You should use while True:, because your guessing code runs only once without it
import random

# Define function - Number Generator
def num_gen():

    num = random.randrange(1, 10)
    return num

# Define function - Number Check
def num_check(x, y):

    result = ''
    if x > y:
        result = 'high'
    elif x < y:
        result = 'low'
    else:
        result = 'correct'
    return result

# Call - Number Generator
att = 1
num = num_gen()
while True:
    # Input - Guess
    guess = int(input('Please guess a number between 1 and 100: '))
    # Process - Guess and Display Result
    result = num_check(guess, num)

    if result == 'high':
        print('Your guess was HIGH! Please guess another number between 1 and 100: ')
        att += 1

    elif result == 'low':
        print('Your guess was LOW! Please guess another number between 1 and 100: ')
        att += 1

    else:
        print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
        break

A: It's because python programs runs from top to bottom, and when it reaches the bottom it's done and stops running. To stop this order we have multiple different ways:
We can call a function, as you do in you're program.
Selection Control Structures: As if statements
Iteration Control Structures: As loops
The last one is the one you need in this solution. Wrap code in a while loop, with the correct condition, in you're example, this would be
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))

att = 1

# Process - Guess and Display Result
result = num_check(guess, num)

if result == 'high':

    guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
    att += 1
    result = num_check(guess, num)

elif result == 'low':

    guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
    att += 1
    result = num_check(guess, num)

else:

    print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')

The best way woul be to use a will loop as follow:
while guess != num:

A: how can you expect it to run more than 1 time if you have not used any loop in the program. For example in this case you should use a while loop, then only it will prompt the user again and again and will check for the conditions, set a game variable to be True. When the number is matched then simply set the game variable to be False and it will end the loop.
import random

# Set the game variable initially to be True
game = True

# Define function - Number Generator
def num_gen():

    num = random.randrange(1, 101)
    return num

# Define function - Number Check
def num_check(x, y):

    result = ''
    if x > y:
        result = 'high'
    elif x < y:
        result = 'low'
    else:
        result = 'correct'
    return result

# Call - Number Generator
num = num_gen()

# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))

att = 1

# Process - Guess and Display Result
result = num_check(guess, num)

while game:

    if result == 'high':

        guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
        att += 1
        result = num_check(guess, num)

    elif result == 'low':

        guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
        att += 1
        result = num_check(guess, num)

    else:

        print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
        game = False


Q: Colorbox inside Multicols So I am using the multicols environment and I want to have the background of some portions of the column colored.
However, I see that multicols does not play well with xcolor and colored sentences overflow in the next column.
Why is that happening? Would tcolorbox work better in this case?
Example:
\documentclass[10pt,landscape, fleqn]{article}
\usepackage{multicol}
\usepackage{calc}
\usepackage{ifthen}
\usepackage[landscape]{geometry}
\usepackage{amsmath,amsthm,amsfonts,amssymb}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{graphicx,overpic}
\usepackage{hyperref}
\usepackage{listings}

%problem statement
\newcommand{\problem}[1] {
  \rule{1\linewidth}{0.25pt}\\
   \colorbox{yellow}{#1}
}

% -----------------------------------------------------------------------

\begin{document}
\raggedright
\footnotesize
\begin{multicols*}{3}

\setlength{\premulticols}{1pt}
\setlength{\postmulticols}{1pt}
\setlength{\multicolsep}{1pt}
\setlength{\columnsep}{2pt}

\problem{This is a long sentence that will unfortunately cross the multicols boundaries.}

This is a long sentence that will not cross the multicols boundaries.

\end{multicols*}
\end{document}

A: The problem is not with a bad interaction; as David mentioned in his comment, \colorbox is unbreakable; you can use a \parbox (of the appropriate width) inside the \colorbox to allow wrapping or you can use the mdframed package to define an environment with the colored background and the top rule; the following example shows both approaches:
\documentclass[10pt,landscape, fleqn]{article}
\usepackage{multicol}
\usepackage{calc}
\usepackage{ifthen}
\usepackage[landscape]{geometry}
\usepackage{amsmath,amsthm,amsfonts,amssymb}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{graphicx,overpic}
\usepackage{mdframed}
\usepackage{listings}
\usepackage{hyperref}

%problem statement
\newcommand{\problem}[1]{%
  \rule{1\columnwidth}{0.25pt}\\
   \colorbox{yellow}{\parbox{\dimexpr\columnwidth-2\fboxsep-2\fboxrule\relax}{#1}}
}

\newmdenv[
  backgroundcolor=yellow,
  skipabove=\topsep,
  skipbelow=\topsep,
  linewidth=0.25pt,
  topline=true,
  bottomline=false,
  leftline=false,
  rightline=false,
]{problemi}

% -----------------------------------------------------------------------

\begin{document}
\raggedright
\footnotesize
\begin{multicols*}{3}
\setlength{\premulticols}{1pt}
\setlength{\postmulticols}{1pt}
\setlength{\multicolsep}{1pt}
\setlength{\columnsep}{2pt}

\problem{This is a long sentence that will not cross the multicols boundaries.}

This is a long sentence that will not cross the multicols boundaries.

\begin{problemi}
This is a long sentence that will not cross the multicols boundaries built using the \texttt{mdframed} package.
\end{problemi}
\end{multicols*}

\end{document}

Notice that there's some white space between the rule and the yellow background in the first case, using your current definition; if you want to get rid of this space, you'll need something like:
\newcommand{\problem}[1]{%
  \rule{1\columnwidth}{0.25pt}\\[0.25pt]\nointerlineskip
   \colorbox{yellow}{\parbox{\dimexpr\columnwidth-2\fboxsep-2\fboxrule\relax}{#1}}
}


Q: How to use query string to find requesting page in ASP.NET? I have a page signup.aspx where user can register, how this page will find from which page request came from and how it will redirect user after registration to the requesting page. I want to do this using query string but don't know how

A: On any links to the register page put
<a href="Signup.aspx?ReturnUrl=<%=Request.Url.AbsolutePath%>">Register Here

then on your register form when they have registered add:
if (!String.IsNullOrEmpty(Request["ReturnUrl"]))
     Response.Redirect(Request["ReturnUrl"]);
else
     Response.Redirect("~/Default.aspx");

A: if(Request.QueryString["foo"] == "bar"){
    Response.Redirect("page.php", true);
}

This would get the information from http://www.example.com/registered.aspx?foo=bar
So Request.QueryString["QueryString"] is the value of anything after the ? and each variable after the &. so if you had http://www.example.com/registered.aspx?foo=bar&abc=def
Then you would have 2 querystrings, foo and abc.


Q: How Can I Implement Realtime Notification On My Php Page This Is My Home.Php ,I Need To Display Realtime Notification From Database
<html>
<body>
<label>Notifications <?php echo "(".$notification.")"; ?>)</label>
//$notification Contain no. of Notifications From Database
</body>
</html>

A: You need to use web socket for real time notification. You can try Ratchet or socket.io.


Q: How to sum the values of all the textboxes with same class which are generated using ajax? I want to sum of all the values of textboxes generated using ajax. I have the textboxes with classname adminhoursand these textboxes are generated using ajax. The sum should be displayed in another textbox on the change event of the textbox with class adminhours. The sum should be multiplied with the admin rate textbox. Please help me. Thanks in advance.
HTML
<form action="" method="post">

                Name
                Email2(payment)
                Class Rate
                Admin Rate
                Week
                Status
                Comment

                    <select name="txtuser" id="txtuser">
                    <option>--select--</option>
                                        <option value="2">nitinjohnson2000</option>

                    </select>

                <input type="text" name="txtemail2" style="width:100%;" readonly="">
                <input type="text" name="txtclassrate" style="width:80px;" readonly="">
                <input type="text" name="txtadminrate" style="width:80px;" readonly="">

                    <select name="txtweek" id="txtweek">
                        <option>--select--</option>
                                                <option>08-31-2015</option>
                                                <option>09-07-2015</option>
                                                <option>09-14-2015</option>
                                                <option>09-21-2015</option>
                                                <option>09-28-2015</option>
                                                <option>10-05-2015</option>
                                                <option>10-12-2015</option>
                                                <option>10-19-2015</option>
                                            </select>

                Not Saved
                <textarea name="txtcomment"></textarea>

                    Session
                    Day of week
                    Date
                    Pre-Assigned
                    Start Date
                    End Date
                    Present
                    Late Arrival
                    Expense
                    Admin Hours
                    Comments

                    Fall 2015 - Bethany Elementary Chess Program - Plano ISD
                    Wed
                    09-02-2015
                    Y
                    2015-09-09
                    2015-12-12
                    <input type="checkbox" name="presentdays[]">
                    <input type="checkbox" name="latedays[]">
                    5
                    <input type="text" name="admin_hours[]" class="adminhours" value="0" style="width:50px;">
                    <input type="text" name="item_comment" style="width:80px;">

                        Fall 2015 - Ashley Elementary Chess Program - Frisco ISD
                        Mon
                        08-31-2015
                        Y
                        2015-09-14
                        2015-12-12
                        <input type="checkbox" name="presentdays[]">
                        <input type="checkbox" name="latedays[]">
                        15	<input type="text" name="admin_hours[]" class="adminhours" value="0" style="width:50px;">
                        <input type="text" name="item_comment" style="width:80px;">

                        Fall 2015 - Bledsoe Elementary Chess Program - Frisco ISD
                        Wed
                        09-02-2015
                        Y
                        2015-09-16
                        2015-12-12
                        <input type="checkbox" name="presentdays[]">
                        <input type="checkbox" name="latedays[]">
                        15
                        <input type="text" name="admin_hours[]" class="adminhours" value="0" style="width:50px;">
                        <input type="text" name="item_comment" style="width:80px;">

                        Fall 2015 - Anderson Elementary Chess Program - Frisco ISD
                        Mon
                        08-31-2015
                        Y
                        2015-09-21
                        2015-12-12
                        <input type="checkbox" name="presentdays[]">
                        <input type="checkbox" name="latedays[]">
                        5
                        <input type="text" name="admin_hours[]" class="adminhours" value="0" style="width:50px;">
                        <input type="text" name="item_comment" style="width:80px;">

                    Day
                    Classes $
                    Late $
                    Expense
                    Admin
                    Approved Adjustment
                    Approved Comment

                    <input type="text" name="number_of_classes" value="4" style="width:50px;" readonly="">
                    <input type="text" name="totalclasses" value="40" readonly="">
                    <input type="text" value="" id="latecharges" readonly="">
                    <input type="text" name="totalexpense" value="40" readonly="">
                    <input type="text" name="totaladminrate" value="0" readonly="">
                    <input type="text" name="approved_adjustment" id="approved_adjustment" style="width:50px;">
                    <textarea name="approver_comment"></textarea>

                Total
                <input type="text" name="finaltotal" id="finaltotal" readonly="">
                Approved Total
                <input type="text" name="approvedtotal" id="approvedtotal" readonly="">

    <input type="hidden" name="alldata" id="alldata" value="16,15,17,14">

                <input type="submit" name="addtimecard" value="Save" class="button button-primary button-large">

</form>

Javascript

A: The logic to get all elements with class .adminhours should not check with val in selector if(jQuery(".adminhours").val().length > 0). I have updated your code below :
var totalAdminhours = 0;
if(jQuery(".adminhours").length > 0){
        jQuery(".adminhours").each(function () {
            totalAdminhours += totalAdminhours + jQuery(this).val();
        });
    } else {
        totalAdminhours = 0;
    }


Q: Overloading == operator A derives directly from Object class and neither A or Object overload == operator, so why doesn't next code cause an error:
class Program
{
    static void Main(string[] args)
    {
        A a1 = new A();
        A a2 = new A();

        if (a1 == a2) ... ;
    }
}

class A { }

thanx

A:
A derives directly from Object class and neither A or Object overload == operator, so why doesn't next code cause an error?

As with your other question, you seem to have some strange belief that whether an overloaded operator exists has any bearing on whether an operator can be meaningfully chosen. It does not.
Again, to resolve this situation overload resolution first attempts to determine if there is a user-defined operator defined on either of the operands. As you note, there is not.
Overload resolution then falls back on the built-in operators. As I mentioned in your other question, the built-in operators are the equality operators on int, uint, long, ulong, bool, char, float, double, decimal, object, string, all delegate types and all enum types, plus the lifted-to-nullable versions of all the value types.
Given those operators we must now determine the applicable ones. There is no implicit conversion from "A" to any of the value types, to any of the nullable value types, to string, or to any delegate type.
The only remaining applicable candidate is object.
If overload resolution chooses the equality operator that compares two objects, additional constraints must be met. In particular, both operands must either be null or a reference type, or a type parameter not constrained to be a value type.  That constraint is met.  Also, if the two sides have types then the operand types must have some sort of compatibility relationship; you can't do "myString == myException" because there is no relationship between string and Exception. There is a relationship between "A" and "A", namely, they are identical.
Therefore the reference equality operator is chosen, and the == means "compare these two object expressions by reference".
I am mystified as to why you believe having a user-defined == operator has anything to do with this, either in this question or your other question. The absence of such a method does not prevent the compiler from generating whatever code it likes for this expression. Can you explain?

A: Because by default, the == operator compares the references (memory locations) of the objects a1 and a2. And because they're different instances of class A, the expression a1 == a2 always evaluates to false in your example.

A: Objects have a default implementation of the == operator that checks if they refer to the same object (reference comparison). So there's no reason for it to be an error. The operator does have a meaning.

A: Because Object has a default implementation comparing references.

A: The base's == operator is called that why its not giving any error.

A:
By default, the operator == tests for
  reference equality by determining if
  two references indicate the same
  object, so reference types do not need
  to implement operator == in order to
  gain this functionality.

From: http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
The important bit concerning your question being:

reference types do not need to
  implement operator == in order to gain
  this functionality


Q: Are the UTC datetime formats acknowledged by W3C identical to those of ISO 8601? The W3C Date and Time note suggests that date and time 'official' formats are identical to, or a subset of ISO 8601. The note says "This document defines a profile of ISO 8601", and also "To reduce the scope for error and the complexity of software, it is useful to restrict the supported formats to a small number."
Is it safe to assume, that all W3C datetimes (such as those used in server logs) are therefore compatible with ISO 8601?


Q: How can I change the Universal Login logo on auth0 dashboard? I'm currently stuck on the auth0 Universal Login page.
I want to change the logo by given an url but it keep telling me that the url is not valid.
I don't know what to do anymore because the exact same url is valid for the Application logo.
Screenshot of the error

A: it seems that you might get that error if you have an whitespace before or after the link too. Can you check whether or not you have that white space in there? maybe that's it


Q: Positive lookahead assertion and .* sign in python I have the following regular expression:
passw = re.compile(r'^(?=.*\d)(?=.*[A-Z])(?=.*[\$|\?\!])[A-Za-z\d$!&]{8}$')

which I can interpret as string of length 8, which must contain at least one number, one big letter and one of characters($?!). And also consists only of numbers, letters and $?!.
?= - this symbol is known as lookahead assertion:  For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.
But how can we interpret .* sign? What does it mean in regex?
Can we avoid it in this situation?

A: In fact .* means zero or more occurrences of any character, and when it follows with a special pattern in a lookahead it means that the regex engine will assert that the regex can be matched. And when you use .* before your pattern you are telling the regex engine to match my pattern that precede by zero or more characters this means you want to be sure that your pattern is present in your string (from leading to trailing).
Here is an example with diagram:
(?=.*\d)[a-z]+

Debuggex Demo


Q: How can I simplify calcul of gradient? Goal: Given $f(\alpha) :=\dfrac{1}{2} \|y-X\alpha\|_2^2$ I want to show that $\nabla f(\alpha)=0\iff X^T X\alpha = X^T y$ where: $X\in\mathbb{R}^{n\times p},\alpha\in\mathbb{R}^p,y\in\mathbb{R}^n$.
If I compute the gradient according to definition I have no problem showing this. But in the lecture the professor is using some gradient/vector propreties as shortcuts and I want to be able to recognise and use them as well. But when using shortcut my solution is wrong by a transposition and I want to know why it fails. Here are the steps:
$$ \nabla f(\alpha) = \frac{1}{2}\frac{d}{d\alpha}\Big(\|y\|_2^2-2y^T X\alpha+\alpha^TX^TX\alpha\Big) $$
I know that $\dfrac{d}{dx} x^TAx = (A+A^T)x$ so $\dfrac{d}{d\alpha} \alpha^TX^TX\alpha = 2X^TX\alpha$ since $X^TX$ is symmetric. Also $\dfrac{d}{d\alpha} \|y\|_2^2= 0$ goes by itself. The error lies in the last gradient calcul I have to do. Here's what I've done:
Since for $x\in\mathbb{R}^p$ $\dfrac{d}{dx} (x) = E\in\mathbb{R}^{p\times p}$ the identity matrix, then:  $\dfrac{d}{d\alpha} 2y^TX\alpha = 2y^TX\cdot E = 2y^TX$. It leads to the result:
$$ \nabla f(\alpha)=0\iff X^T X\alpha = y^T X$$
Which is false by a transposition, the dimensions are not matching so it doesn't really make sense. So question is: Why doesn't my shortcut work in this case, and in what other easy way can I make this work ?
Note: The same problem arise when I consider $f:\mathbb{R}^n\to \mathbb{R}$, $f(x) = (1,\dots,1)\cdot \begin{pmatrix}x_1\\ \vdots\\ x_n\end{pmatrix}= x_1+\cdots +x_n$. Obviously $\nabla f(x) = \begin{pmatrix} 1\\ \vdots \\ 1\end{pmatrix}\in\mathbb{R}^n$. But using the same shortcut as above we have:
$$ \frac{d}{dx} \big(\;(1,\dots,1)\cdot \begin{pmatrix}x_1\\ \vdots\\ x_n\end{pmatrix}\;\big)=(1,\dots,1)\cdot E_{n\times n} = (1,\dots,1)\in\mathbb{R}^{1\times n} $$
Same, nearly the right answer but not quite.

A: $\def\p#1#2{\frac{\partial #1}{\partial #2}}$
Explicit use of the inner (dot) product is one way to avoid the transposition error.
Define the vector $w=(X\cdot a-y),\,$ then write the function in terms of this vector and calculate its gradient.
$$\eqalign{
 f &= \tfrac 12w\cdot w \\
df &= w\cdot dw \;=\; w\cdot(X\cdot da) \;=\; (X^T\!\cdot w)\cdot da \\
\p{f}{a} &= X^T\!\cdot w \;=\; X^T(X\cdot a-y) \\
}$$
Taking the transpose of a matrix is never an issue, but anytime you find yourself taking the transpose of a vector, proceed with caution. Rewriting the equation using dot products is one fool-proof method. It forces you to arrange the expression on each side of a dot product into dimensionally compatible forms.
Another fool-proof method is to use dyadic products, while very complicated expressions often require index notation for a solution.


Q: Google Maps kml files If I use an embeded google map in my website, will the data contained in an kml displayed be publicly viewable?
Will it be possible for the user to access just the data displayed (i.e., not the user interface) or would I have to provide that separately?

A: If you load your KML through the API, with GGeoXml(), (V2), or KmlLayer(), (V3), then your data needs to be in a public server because it is parsed by Google's servers and they need to be able to get to it. If you load it with a third party extension then you can keep it private.
Third party extensions that can load and parse KML data are EGeoXml() by Mike Williams
http://econym.org.uk/gmap/extensions.htm#EGeoXml
and GeoXml() by Lance Dyas
http://www.dyasdesigns.com/geoxml/
but I believe that both of those are only available for the API V2 for now.

A: I just upgraded my Google Maps JavaScript API Application from v2 to v3, following these instructions.
My v2 application was using the EGeoXml extension referred to by @Marcelo in the accepted answer to locally parse KML data.
A substitution of geoxml3 in its place, as suggested by @geocodezip (a contributor to the project) in a comment, functioned immediately in my v3 application.

A: No, the data will not be public. I'm not sure about your other question though.


Q: remove duplicate rows where one column equals a different column I have a df like this:
d = {'label':['A','B','G','O']
    ,'label2':['C','D','O','Z']}
df = pd.DataFrame(d)
print(df)

  label label2
0   A    C
1   B    D
2   G    O
3   O    Z

What i want to do is to get rid of the duplicate rows that have label = label2 (keep only the first)
So i want to get something like this from the above df:
  label label2
0   A    C
1   B    D
2   G    O

I do this below, but it doesn't do the trick
df[~df[['label', 'label2']].apply(frozenset, axis=1).duplicated()]

Any idea on how to tackle this?

A: Try this, using .isin method for Seires:
mask = ~df['label'].isin(df['label2'])
df_output = df[mask]
print(df_output)

Output:
  label label2
0   A    C
1   B    D
2   G    O

A: You can use drop to remove duplicate label between 2 columns:
df.drop(df[df['label'].isin(df['label2'])].index, inplace=True)
print(df)

# Output:
  label label2
0     A      C
1     B      D
2     G      O


Q: .Net Garbage Collection on LoH When the memory dump is being analyzed, it shows that this particular string variable which is holding the xml content is causing memory leak. I read on some of the articles that LoH goes to Gen 2. So,

*

*Will garbage collector gets invoked if Gen 0 and Gen 1 is not under pressure and Gen 2 is under pressure due to LoH ?

*Will it go to Gen 2 when it has released Gen 0 or Gen 1 memory ?

*If so what’s the better way to handle this ?

A: *

*No, it will not

*Only if there's enough memory pressure

However, if your application is doing allocations, it's pretty unlikely the string will survive for too long. And if there's not enough memory pressure, the GC has little reason to release the memory.
Do make sure the string is not referenced anymore, though. Count the references, check that it's not interned.
You can force a garbage collection, but it's great way to damage GC performance. It might be the best solution for your case if your application does the odd "allocate a huge string and then forget it" operation, and you care about memory available to the rest of the system (there's no benefit to your application). There's no point in trying that if you're doing a lot of allocations anyway, though - in that case, look for memory leaks on your side. WinDbg can help.

A: 1. Will garbage collector gets invoked if Gen 0 and Gen 1 is not under pressure ?
If there is enough space in Generation0 and Generation2, then Garbage Collector will not be invoked.
If there is enough space in Generation0 and Generation2, then it means that that there is enough space to create new objects and there is no reason to run Garabage Collection.
2. Will it go to Gen 2 when it has released Gen 0 or Gen 1 memory ?
If the object is survived after Garbage Collection in Generation1 and in the Generation1, then the object will be moved to Generation2.
3. If so what’s the better way to handle this ?

*

*To destroy an object from heap, you should just delete references of this string. Your string variable which has xml values should not be static to be garbage collected.(read more about roots)

*Try to use compact GCSettings.LargeObjectHeapCompactionMode:
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
This will compact the Large Object Heap when the next Full Garbage Collection is executed. With GC.Collect() call after the settings been applied, the GC gets compacted immediately.

*

*Try to use WeakReference:
WeakReference w = new WeakReference(MyLargeObject);
 MyLargeObject = w.Target as MyLargeClass;
MyLargeClass MyLargeObject;
if ( (w == null) || ( (MyLargeObject=w.Target as MyLargeClass) == null) )
{
    MyLargeObject = new MyLargeClass();
    w = new WeakReference(MyLargeObject);
}
This article gives is very useful to you about Garbage Collection and the article is written in plain English.


Q: How to Drawable Rotating around its Top Android I am getting strange results with the following code:
  Animation a = new RotateAnimation(0.0f, 360.0f,
                Animation.ZORDER_TOP, 0.5f, Animation.ZORDER_TOP,
                0.5f);
        a.setRepeatCount(-1);
        a.setDuration(1000);
        img.startAnimation(a);

Whats the right way to specify the axis point (top of the drawable)?

A: Try this one it will work "rotationY" means it will rotate Y Direction, "rotationX" means it will rotate X Direction
    ObjectAnimator animation = ObjectAnimator.ofFloat(view, "rotationY", 0.0f, 360f);
    animation.setDuration(600);
    animation.setRepeatCount(ObjectAnimator.INFINITE);
    animation.setInterpolator(new AccelerateDecelerateInterpolator());
    animation.start();


Q: ^M characters when using Tramp (on Windows) to connect to Ubuntu Server I've set up Tramp on Emacs on my Windows 7 box (64 bit). For this test, this is the only thing in my emacs-config:
(setq tramp-default-method "plink")
Then I connect to my Ubuntu Server 9.10 running in a VM on my local network.
Connection goes fine, i can use dired to browse folders and open files. Yay!
However, git status shows up as:
Git:master^M
An when i open speedbar all folders and files ends with ^M, ie:
<+> conf/^M
Does anyone know how to prevent this line-ending collision from occurring?

A: don't know if this is it but I had a similar issue that I fixed with this.
(setq default-buffer-file-coding-system 'utf-8-unix)

there's a few people who have asked how to get tramp working on windows(I actually gave up) so if you felt like documenting how you did it, there would likely be legions of thankful windows users out there.

A: (prefer-coding-system 'utf-8) did the trick!
Thanks Tom for the clue... Getting Tramp to work on my windows machine was no trouble at all. I'm using this version of Emacs:
GNU Emacs 23.1.50.1 (i386-mingw-nt6.1.7600)
of 2009-10-15 on LENNART-69DE564

With this in my init.el:
(setq tramp-default-method "plink")
(prefer-coding-system 'utf-8)

Putty directory with plink-app is in my system path.
Then: C-X C-F /username@192.168.0.2: and Tab brings up password prompt then autocompletion on servers-files.


Q: HiDPI Mode not respected by iOS Simulator I turned on HiDPI mode in my OS X El Capitan and now facing the issue: iOS Simulator screen shows only part of its contents. Please see the picture below.
If I turn HiDPI mode off then everything gets back to normal.
What can I do to have both HiDPI mode on and proper iOS Simulator screen?
I am using Xcode 7.3.1 and iOS 9.3 simulator.

A: The issue is gone after installing Xcode 8.


Q: Hiding filter input box instead of disabling + tablesorter 2 I need a little assistance.  I am using a fork of JQuery TableSorter 2 (http://mottie.github.com/tablesorter/) to work and filter my tables.  If i dont want certain columns to be used as filter, I simply need to add "filter-false" as a class to the selected column header.
My main question is whether there is a way I can actually hide the filter boxes on the selected columns instead of just disabling them...
Thanks
Emmanuel

A: Here is the default css:
/* optional disabled input styling */
table.tablesorter thead tr.tablesorter-filter-row input.disabled {
    opacity: 0.5;
    filter: alpha(opacity=50);
}

As seen, a disabled class is applied to those disabled filters, so you can use css to either apply display:none or visibility:hidden to it:
tr.tablesorter-filter-row input.disabled {
    display: none;
}

A: I recommend simply sticking with:
/* optional disabled input styling */
table.tablesorter thead tr.tablesorter-filter-row input.disabled {
   opacity: 0.0;
    filter: alpha(opacity=0);
}

As having that one hidden, removes also the table's inner border thus creating unpleasant visual effect.


Q: AlertDialog not showing when not onCreate I have an Activity that have to show an AlertDialog with a ListView for the user to choose one of the options. When I put the code of the AlertDialog in the onCreate method, it works. But when somewhere else, it doesn't. There are no errors on the console.
Here is where it's called (in the Activity):
@Override
public void onStateChanged(IntegratorState state) {
    switch (state.getState()) {
    case AWAITING_MENU_OPTION:
        IntegratorHelper.showOptionsMenu(state, SitefMenuActivity.this).show();
        break;
    default:
        Toast.makeText(getApplicationContext(), state.getState().name(),
                Toast.LENGTH_LONG).show();
    }
}

And here is where I create the Dialog (in another class):
public static AlertDialog showOptionsMenu(IntegratorState state, Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(state.getGatewayMessageExtra());
    String[] strings;
    strings = state.getGatewayMessage().split(";");

    final List<String> options = Arrays.asList(strings);

    builder.setAdapter(new MenuSaleAdapter(context,
            android.R.layout.simple_list_item_1, options),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == options.size()-1) {
                        // Do a thing
                    } else {
                        // Do other thing
                    }
                }
            });
    return builder.create();
}

private static class MenuSaleAdapter extends ArrayAdapter<String> {

    public MenuSaleAdapter(Context context, int textViewResourceId,
            List<String> objects) {
        super(context, textViewResourceId, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView view = (TextView) super.getView(position, convertView,
                parent);
        view.setTextColor(Color.BLACK);
        return view;
    }
}

I tried to put all the code in the same Activity, but it still doesn't work. The application doesn't freeze or anything, it just don't show the Dialog. Any ideas? Thanks

A: Try changing first part to:
    @Override
    public void onStateChanged(IntegratorState state) {
    switch (state.getState()) {
    case AWAITING_MENU_OPTION:
        IntegratorHelper.showOptionsMenu(state, SitefMenuActivity.this);
        break;
    default:
        Toast.makeText(getApplicationContext(), state.getState().name(),
                Toast.LENGTH_LONG).show();
    }
}

and second part:
public static void showOptionsMenu(IntegratorState state, Activity activity) {
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setTitle(state.getGatewayMessageExtra());
    String[] strings;
    strings = state.getGatewayMessage().split(";");

    final List<String> options = Arrays.asList(strings);

    builder.setAdapter(new MenuSaleAdapter(activity,
            android.R.layout.simple_list_item_1, options),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == options.size()-1) {
                        // Do a thing
                    } else {
                        // Do other thing
                    }
                }
            });
    builder.create().show();
}


Q: SharePoint Designer Workflow copy data from one list field to another I have attempted to do this workflows and tried publishing a few but they cant seem to execute. I am not sure what the reason could be. I am trying to forward all values from one field in a list to another another field from another list?
Should I use lookup field to perform this workflow?

The workflow which I have published the list to displays the following below. Is this correct when you publish a workflow on the list?

A: Alright, so you didn't provide much to go off (like whether this is a 2010 or 2013 WF and what you were trying to copy) but I've drafted up a 2013 WF that does what you want (you were on the right track)...
Workflow Overview:

Create Item Details:

Update List Item Details:

Not sure if this is what you were looking for but I hope it helps!


Q: How to use cronjobs to run a python script on a webserver thats on the cloud? I am currently trying to create a Discord bot (with Discord.py) that is able to search through Reddit every few hours to see if there is anything new that has been posted in a specific subreddit. Currently, I have a way to scrape Reddit for this information but it is activated through a Discord command. Ideally, I would like for the script to run automatically after a certain time interval instead of being activated through a command.
I am using asyncpraw and discord.py for my code, so it is all in Python.
Additionally, I am using Flask to create a webserver for the bot, and then using Repl.it to host the server for free. I also use cron-job.org to submit a request every five minutes to the webserver in order to keep it running.
I have my files set up as main.py, which contains all information for the Discord bot, commands, and code that activates when the command is entered into the chat, and then a keep_alive.py file that contains the starting of the web server and the thread (I'm not super knowledgeable about Flask so I'm not super clear on what everything does). At the end of main.py, before I enter the discord bot's token, I call a function from keep_alive.py.
So far, I have tried to use cron-job.org to set up a cronjob, but it hasn't worked thus far as I am not super clear on how to go about it. I have also tried using schedule.py or sched.py, but neither has worked.
To my understanding, I need to use a cronjob for the functionality that I want, but I would love some guidance on actually implementing it, especially as far as the organization of files goes and where to call functions for them to activate. Additionally, I would like to find out if there is a way to use cronjobs within Repl.it, because I don't think you can use them from within their console.
Please let me know if you need any more information or code or anything else!
I appreciate any and all help! Thanks!

A: I don't know if this helps you but the way I was able to automate python scripts on my web server was by using a windows 2016 server.
Then creating a .bat file that would run the script like this. Just make sure your file location is set correctly.
python C:\inetpub\wwwroot\top_10_week.py %*

Then use windows task scheduler to schedule the script to run after a certain time, I set mine to 3 hours but I'm sure you can do it every 5 minutes.
https://www.windowscentral.com/how-create-automated-task-using-task-scheduler-windows-10


Q: Ошибка: "Приложение не установлено" после неудачной установки GridTab После неудачной установки GridTab (проблемы с электросетью) на Android Studio я теперь не могу установить ни одну программу на смартфон. Они компилируются без ошибок, всё вроде бы хорошо, но установка программы на смартфон всё время прерывается сообщением "Приложение не установлено". В чём может быть дело?

A: Установите любой эмулятор андроида, например:

*

*NOX

*MEMU

и попробуйте в него устанавливать, этим вы исключите проблему со смартом.
Если не поможет, то вам делать сброс настроек на дефолт (можете предварительно забекапить свои), и последнее , переустановка самой IDE и повторная установка компонентов и плагинов.


Q: Postgres Function/Trigger Avg I am trying to create a function that calculates the moving average for an item. What I have is a table of "item" and then each user can "vote" which produces one vote, with a score, user_id and item_id.
I want to calculate an AVG, which is stored in item_id after every insert and is calculated based on number of vote's (selected by vote.item_id) and averages the score using vote.score.
this is the idea of the query.. this works, but stores the moving average int he last column of vote and is not usable, but I am close!!
select vote.score as single_vote_score, vote.user_id, vote.item_id, items.score as item_score,
    AVG(vote.score)
        OVER(ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM vote
    LEFT JOIN items on vote.item_id = items.id
WHERE vote.item_id = 10;

This is the function
CREATE FUNCTION calculate_item_score() RETURNS TRIGGER AS $calculates_items_score_by_average$
    BEGIN UPDATE "item"
        SET "score" = AVG("vote"."score")
        FROM "vote"
        WHERE "item"."id"="vote"."item_id";
        RETURN NEW;
    END;
$calculates_items_score_by_average$
LANGUAGE plpgsql;

This trigger should run every time a vote is inserted!
CREATE TRIGGER "update_item_score"
AFTER INSERT ON "vote"
FOR EACH ROW EXECUTE
PROCEDURE calculate_item_score();

-- this errors out
INSERT INTO vote (user_id, photo_id, score) VALUES ('129','10','50.0');

This is my error
ERROR:  aggregate functions are not allowed in UPDATE
LINE 1: UPDATE "photo" SET "score" = AVG("vote"."score") FROM "vote"...
                                 ^
QUERY:  UPDATE "item" SET "score" = AVG("vote"."score") FROM "vote" WHERE
"item"."id"="vote"."item_id"
CONTEXT:  PL/pgSQL function calculate_item_score() line 1 at SQL statement

A: BEGIN UPDATE "item"
    SET "score" = (select AVG("vote"."score") FROM "vote")

Use it as follows:
create or replace function test (id int) returns void as
$$
begin
update employees
set commission_pct=(select min(commission_pct) from employees)
where employee_id= $1;
end
$$ LANGUAGE plpgsql VOLATILE;

select test(198); --call function

The process of aggregate functions is calculated after getting data set from data in table, we cannot use any calculating without selecting data from table first. In the above function is update column score* to AVG(score) but there is not data-set to calculate the AVG(score).

A:
ERROR:  aggregate functions are not allowed in UPDATE

How much clearer can you get than that? First, a few things: this is a bad idea. You're essentially forcing at the very least an index scan, and at the very most a full table seq scan. That's a lot for an update.
Some other ideas:

*

*Window functions.

*[MATERIALIZED] VIEWS.

this is the idea of the query.. this works, but stores the moving average int he last column of vote and is not usable, but I am close!!

I'm not sure what "the last column of vote" means, but if that's you're only problem, then simply move it to a different position in the SELECT list?
SELECT
  AVG(vote.score) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW),
  vote.score as single_vote_score,
  vote.user_id,
  vote.item_id,
  items.score AS item_score
FROM vote
LEFT JOIN items
  ON vote.item_id = items.id
WHERE vote.item_id = 10;

I'm not sure why the position of it matters though?


Q: Incorrect prettier file pattern I'm using prettier to format an angular project but I'm having a little trouble figuring out the correct file pattern.
Using prettier --check src/**/* includes *.pdf files which causes errors.

Using prettier --check src/**/*.ts ignores *.component.ts files.
I could use prettier --check src/**/*(.component.ts|.service.ts|...) an so on but this pattern would be gigantic. I also have to do this for .html en .scss


Q: Missing Method when include require 'test_helper' i'm trying to test using minitest but when running this file with

bin/rails test test/controllers/api/v1/blogs_api_controller_test.rb

But it gives this error

.rvm/gems/ruby-2.3.1/gems/railties-5.1.1/lib/rails/railtie/configuration.rb:95:in
  method_missing': undefined methodweb_console' for
 (NoMethodError) Did you mean?  console

require 'test_helper'

class BlogsApiControllerTest < ActiveSupport::TestCase
  test 'Get all Blogs' do
    assert false
  end
end

Rails version 5.1.1 Ruby 2.3.1
Gem File
source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.1.1'
# Use Puma as the app server
gem 'puma', '~> 3.8.2'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 3.2.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails', '~> 4.1.1'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.6'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'

gem 'kaminari', '~> 0.17.0'
gem 'bootsy', '~> 2.4'
gem 'searchkick', '~> 3.0.2'
gem 'devise', '~> 4.3.0'
gem 'omniauth-facebook', '~> 3.0.0'
gem 'omniauth-google-oauth2', '~> 0.4.1'

gem 'cancancan', '~> 1.15.0'
gem 'paperclip', '~> 5.0.0'
gem 'sitemap_generator', '~> 5.1.0'
gem 'jwt'
gem 'simple_command'

gem 'rack-cors', require: 'rack/cors'

# For admin panel ----------------
gem 'activeadmin', '~> 1.0.0'
# Below are for rails 5
# gem 'inherited_resources', github: 'activeadmin/inherited_resources'
# gem 'ransack',             github: 'activerecord-hackery/ransack'
gem 'draper',              '~> 3.0.1'
# ---------------------

group :development, :test do
  gem 'pry'

  # Use mysql as the database for Active Record
  gem 'mysql2', '~> 0.4.6'
end

group :development do
  gem 'wdm', '>= 0.1.0' if Gem.win_platform?
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console'
  gem 'listen', '~> 3.0.8'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.1'
end

group :production do
  gem 'pg', '~> 0.18.4'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

A: Please put gem 'web-console' into your Gemfile's test section. You can change the following lines
group :development, :test do
  gem 'pry'

  # Use mysql as the database for Active Record
  gem 'mysql2', '~> 0.4.6'
end

with following
group :development, :test do
  gem 'pry'
  gem 'web-console'
  # Use mysql as the database for Active Record
  gem 'mysql2', '~> 0.4.6'
end

And remove web-console from following lines
group :development do
  gem 'wdm', '>= 0.1.0' if Gem.win_platform?
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console' # remove this

Now run following command to update bundles
bundle install


Q: Set color of alertdialog I display an alertdialog in my app but the left and right side of the title shows a different color. I have set my own background color in thems.xml
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="ACCAppTheme" parent="android:Theme.Holo">
    <!-- Change default text colour from dark grey to black -->
    <!-- <item name="android:windowBackground">@drawable/ic_logo</item> -->
    <item name="android:background">#140051</item>
    <item name="android:textColor">#ffffff</item>
    <item name="android:textColorHint">#c0c0c0</item>
    <item name="android:actionBarStyle">@style/AppTheme.ActionBar</item>
</style>

<!-- <style name="OverFlow" parent="@android:style/Widget.Holo.ActionButton.Overflow">
    <item name="android:textSize">18sp</item>
</style> -->

<style name="AppTheme.ActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:background">#140051</item>
    <item name="android:height">50dp</item>
    <item name="android:titleTextStyle">@style/AppTheme.ActionBar.Text</item>
    <item name="android:textColor">@android:color/white</item>
    <item name="android:showDividers">beginning</item>
</style>

<style name="AppTheme.ActionBar.Text" parent="@android:style/TextAppearance">
    <item name="android:textAllCaps">false</item>
    <item name="android:textColor">@android:color/white</item>
</style>
</resources>

but what appears is like this

here's the code that creates the alert dialog
public class AppMessages {
public static final int MESSAGE_INFO = 1;
public static final int MESSAGE_CRITICAL = 2;

public interface AlertButtonClickListener {

    public abstract void onButtonClicked(boolean value);

}

public static void showMessage(Context context,
                                String message,
                                String title,
                                int messageType,
                                final AlertButtonClickListener target) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(message)
            .setTitle(title)
            .setIcon(R.drawable.ic_dialog_information)
            .setCancelable(false)
            .setPositiveButton("Ok", new AlertDialog.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (target != null) {
                        target.onButtonClicked(true);
                    }
                }
            });

    switch (messageType) {
    case AppMessages.MESSAGE_CRITICAL:
        builder.setIcon(R.drawable.ic_dialog_exclamation);
        break;
    case AppMessages.MESSAGE_INFO:
        builder.setIcon(R.drawable.ic_dialog_information);
        break;
    }

    builder.show();
}

public static void yesNo(final Context mContext,
                        final String title,
                        final String msg,
                        final String positiveBtnCaption,
                        final String negativeBtnCaption,
                        final boolean isCancelable,
                        final AlertButtonClickListener target) {

        ((Activity) mContext).runOnUiThread(new Runnable() {

        @Override
        public void run() {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

            builder.setTitle(title)
                    .setMessage(msg)
                    .setIcon(R.drawable.ic_dialog_question)
                    .setCancelable(false)
                    .setPositiveButton(positiveBtnCaption,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    target.onButtonClicked(true);
                                }
                            })
                    .setNegativeButton(negativeBtnCaption,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    target.onButtonClicked(false);
                                }
                            });

            AlertDialog alert = builder.create();
            alert.setCancelable(isCancelable);
            alert.show();
            if (isCancelable) {
                alert.setOnCancelListener(new OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface arg0) {
                        target.onButtonClicked(false);
                    }
                });
            }
        }
    });

}
}

here's how I call the it
AppMessages.showMessage(thisActivity,
                                    "New update found. Click Ok to download it now.",
                                    "New Update Found",
                                    1,
                                    new AppMessages.AlertButtonClickListener() {
                                        @Override
                                        public void onButtonClicked(boolean value) {
                                            APKDownloader.downloadAPK(thisActivity);
                                        }
                                    });

A: Try this,
Customize AlertDialog Theme
Create a new Android XML resource file under res/values/
You'll want to create a new style that inherits from the default alertdialog theme:
<style name="CustomDialogTheme" parent="@android:style/Theme.Dialog">
    <item name="android:bottomBright">@color/white</item>
    <item name="android:bottomDark">@color/white</item>
    <item name="android:bottomMedium">@color/white</item>
    <item name="android:centerBright">@color/white</item>
    <item name="android:centerDark">@color/white</item>
    <item name="android:centerMedium">@color/white</item>
    <item name="android:fullBright">@color/orange</item>
    <item name="android:fullDark">@color/orange</item>
    <item name="android:topBright">@color/blue</item>
    <item name="android:topDark">@color/blue</item>
</style>

You can specify either colors or drawable for each section of the AlertDialog.
An AlertDialog will build it's display by combining 3 drawables/colors (top, center, bottom) or a single drawable/color (full).
In a theme of your own override the android:alertDialogStyle style (you can do this within the same XML file):

    @style/CustomDialogTheme

Override your application's theme in the AndroidManifest within the application tag:
<application
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/MyTheme">

Now that you've defined your application's theme, any attributes overridden in your theme will resonate throughout your app.
For example if you also wanted to change the color of your application's title bar:
You would first define a  new style that inherits from the default attribute

    @color/blue

and just add the new overridden item to your theme:
<style name="MyTheme">
    <item name="android:windowTitleBackgroundStyle">@style/MyBackground</item>
    <item name="android:alertDialogStyle">@style/CustomDialogTheme</item>
</style>


Q: Embedding tab bar to top of screen iphone I want to design a page with tab bar on top of it.In some articles of this site.(i missed urls) i found that this is not a common way and the question gets some down rate.
The question is this: whethere having a design like this may cause that apple not approve the application on his store?

A: Even if it doesn't make Apple reject your app, think of the users not being used to the tab bar being at the top and how that is going to affect how well the app does in the Store.
Every platform has its own design patterns and there is a reason for that. If you stick to them there is a higher chance that the first-time users have an easier time using your app, which results in a higher chance that they keep using it. If they don't know how to use it or find it hard, they will move to another one.
Take a look at the Human Interface Guidelines and apply them. It will do good.


Q: Terraform: aws_lb_listener with multiple ports I am building an ALB on AWS using Terraform. The ALB should forward multiple ports to the instances, but the documentation specifies:

port - (Required) The port on which the load balancer is listening.

Do I have to add a separate ALB listener for each port, or is there a way to specify multiple ports per listener?

A: An ALB listener can only listen on a single port. You must define a listener for each port you want the load balancer to listen on. This isn't a limitation of Terraform, it's the way AWS load balancers are designed.
Additionally, since an ALB can only handle HTTP and HTTPS requests you usually don't setup more than two listeners on an ALB (ports 80 and 443), and the listener configuration would of necessity be different since one would have an SSL certificate configuration and one would not.


Q: Use multiple checkbox selection while parsing JSON I'm trying to select multiple checkboxes in a custom listview while parsing JSON. Now I am able select a single checkbox. How can I select multiple checkbox values?


Q: Determine whether $S=\{(x,\sin(\frac{1}{x})):x \in \mathbb{R}^+\} \bigcup \{(0,0)\}$ is an open set, closed set or neither. $$S:=\{(x,\sin(\frac{1}{x})):x \in \mathbb{R}^+\} \cup \{(0,0)\}$$
For proving that this is not an open set, I took $x=(0,0)$, and said, if this is infact an open set, then $\exists r>0 \text{ s.t. } B(x,r) \subseteq S$. Now, clearly, $(-r/2,0) \in B(x,r)$, but $ (-r/2,0) \notin S$. Thus, $S$ isn't an open set.
But how do I prove that this is a closed set/neither ?
 For $S$ to be a closed set, all its limit points will have to be inside $S$, which seems intuitively true, but I am not able to show it explicitly. Could someone help ?

A: You're right about not being an open set. And it is not a closed set because, for each $n\in\Bbb N$, $\left(\frac1{\pi/2+2n\pi},1\right)\in S$, but$$\lim_{n\to\infty}\left(\frac1{\pi/2+2n\pi},1\right)=(0,1)\notin S.$$


Q: python - regex putting repeating patterns in a single group I'm trying to parse a string in regex and am 99% there.
my test string is
 1
  1234 1111 5555 88945
    172.255.255.255 from 172.255.255.255 (1.1.1.1)
      Origin IGP, localpref 300, valid, external, best
      rx pathid: 0, tx pathid: 0x0

my current regex pattern is:
(?P<as_path>(\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}).*\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+.*localpref\s(?P<local_pref>\d+),\s(?P<attribs>\S+,\s{0,4})

im using regex101 to test and have a link to the test here https://regex101.com/r/iGM8ye/1
So currently i have a group2 I don't want this group, could someone tell me why im getting this group and how to remove it?
and the second is, in the attributes I want to match the words, "valid, external, best" currently my pattern only matches "valid," I thought adding the repeat of within the group would of matched all three of those but it hasn't.
How would I achieve matching the repeat of "string, string, string," (string comma space) into one group?
Thanks
EDIT
Desired output
as_path : 1234 1111 5555 88945
peer_addr : 172.255.255.255
peer_rid : 1.1.1.1
local_pref : 300
attribs : valid, external, best

attiribs may also just be valid, external, or just external, or another entry in the format (stringcommaspace)

A: Try Regex: (?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}).*\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+.*localpref\s(?P<local_pref>\d+),\s(?P<attribs>[\S]+,(?: [\S]+,?)*){0,4}
Demo
Regex in the question had a capturing group (Group 2) for (\d{4,10}\s). it is changed to a non capturing group now (?:\d{4,10}\s)

A: See regex in use here.
(?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}(?:\.\d{0,3}){3}).*\((?P<peer_rid>\d{0,3}(?:\.\d{0,3}){3})\)\s+.*localpref\s(?P<local_pref>\d+),\s+(?P<attribs>\S+(?:,\s+\S+){2})

*

*You were getting group 2 because your as_path group contained a group. I changed that to a non-capturing group.

*I changed attribs to \S+(?:,\s+\S+){2}

*

*This will match any non-space character one or more times \S+, followed by the following exactly twice:

*

*,\s+\S+ the comma character, followed by the space character one or more times, followed by any non-space character one or more times

*I changed peer_addr and peer_rid to \d{0,3}(?:\.\d{0,3}){3} instead of \d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}. This is a preference, but shortens the expression.

Without that last modification, you can use the following regex (it performs slightly better anyway (as seen here):
(?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}).*\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+.*localpref\s(?P<local_pref>\d+),\s+(?P<attribs>\S+(?:,\s+\S+){2})

You can also improve the performance by using more specific tokens as the following suggests (notice I also added the x modifier to make it more legible) and as seen here:
(?P<as_path>\d{4,10}(?:\s\d{4,10}){0,19})\s+
(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})[^)]*
\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+
.*localpref\s(?P<local_pref>\d+),\s+
(?P<attribs>\w+(?:,\s+\w+){2})

A: You get that separate group because your are repeating a capturing group were the last iteration will be the capturing group, in this case 88945 You could make it non capturing instead (?:
For the second part you could use an alternation to exactly match one of the options (?:valid|external|best)
Your pattern might look like:
(?P<as_path>(?:\d{4,10}\s){1,20})\s+(?P<peer_addr>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}).*\((?P<peer_rid>\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})\)\s+.*localpref\s(?P<local_pref>\d+),\s(?P<attribs>(?:valid|external|best)(?:,\s{0,4}(?:valid|external|best))+)

regex101 demo


Q: Why json_encode create new line after password_verify php and create error in android studio I'm new in php, now i want to create json_encode and use it as API to my android apps, but after i try it on android, the log say that

Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

and the postman shows one line after the json response. how to eliminate the new line (line two) which is not contain anything.
This is my response in postman:
1 {"kode":1,"pesan":"Login Berhasil"}
2

picture spoiler :
https://imgur.com/a/fKi0a72
thank you for all your response afterwards
i have tried to change code in php to fetch the password row several time but always produce second line.
 $konek = new Mysqli($HostName, $HostUser, $HostPass, $DatabaseName) or die(Mysqli_errno());

 if($_SERVER['REQUEST_METHOD'] == 'POST')
 {
    $email = $_POST['email'];
    $password = $_POST['password'];
    $role = $_POST['role'];

    $sql = "SELECT * FROM user WHERE email= '$email'";
    $result = $konek->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
                if(password_verify($password, $row['password'])){
                echo json_encode(array('kode' =>1, 'pesan' => 'Login Berhasil'));
                } else {
                    echo json_encode(array('kode' =>2, 'pesan' => 'Login Gagal. Periksa Email atau password'));
                }
        }
     }
 }
else{
    echo json_encode(array('kode' =>101, 'pesan' => 'Login Error '));
}

This is my response in postman:
1 {"kode":1,"pesan":"Login Berhasil"}
2

A: try to see output in json instead of html because in my Postman it is displayed correctly.
you should set Content type of Response of API to json to avoid any issues like this.
If doesn't help please comment with output as json in postman.


Q: Rails ActiveRecord query using multiple joins involving polymorphic association I'm trying to figure out how I can replicate the following SQL query using AR given the model definitions below. The cast is necessary to perform the average. The result set should group foo by bar (which comes from the polymorphic association). Any help is appreciated.
SQL:
SELECT AVG(CAST(r.foo AS decimal)) "Average", s.bar
FROM rotation r INNER JOIN cogs c ON r.cog_id = c.id
           INNER JOIN sprockets s ON s.id = c.crankable_id
           INNER JOIN machinists m ON r.machinist_id = m.id
WHERE c.crankable_type = 'Sprocket' AND
      r.machine_id = 123 AND
      m.shop_id = 1
GROUP BY s.bar

ActiveRecord Models:
class Rotation < ActiveRecord::Base
    belongs_to :cog
    belongs_to :machinist
    belongs_to :machine
end

class Cog < ActiveRecord::Base
    belongs_to :crankable, :polymorphic => true
    has_many :rotation
end

class Sprocket < ActiveRecord::Base
    has_many :cogs, :as => :crankable
end

class Machinist < ActiveRecord::Base
    belongs_to :shop
end

UPDATE
I've figured out a way to make it work, but it feels like cheating. Is there are a better way than this?
Sprocket.joins('INNER JOIN cogs c ON c.crankable_id = sprockets.id',
               'INNER JOIN rotations r ON r.cog_id = c.id',
               'INNER JOIN machinists m ON r.machinist_id = m.id')
    .select('sprockets.bar', 'r.foo')
    .where(:r => {:machine_id => 123}, :m => {:shop_id => 1})
    .group('sprockets.bar')
    .average('CAST(r.foo AS decimal)')

SOLUTION
Albin's answer didn't work as-is, but did lead me to a working solution. First, I had a typo in Cog and had to change the relation from:
has_many :rotation

to the plural form:
has_many :rotations

With that in place, I am able to use the following query
Sprocket.joins(cogs: {rotations: :machinist})
    .where({ machinists: { shop_id: 1 }, rotations: { machine_id: 123}})
    .group(:bar)
    .average('CAST(rotations.foo AS decimal)')

The only real difference is that I had to separate the where clause since a machine does not belong to a machinist. Thanks Albin!

A: I think this code is a little simpler and taking more help from AR
Sprocket
.joins(cogs: {rotations: :machinist})
.where({ machinists: { machine_id: 123, shop_id: 1 } } )
.group(:bar)
.average('CAST(rotations.foo AS decimal)')

The select clause was unnecessary, you don't have to select values since you only need them internally in the query, AR helps you decide what you need afterwards.
I tested this out using a similar structure in one of my own projects but it is not the exact same models so there might be a typo or something in there if it does not run straight up. I ran:
Activity
.joins(locations: {participants: :stuff})
.where({ stuffs: { my_field: 1 } })
.group(:title)
.average('CAST(participants.date_of_birth as decimal)')

producing this query
SELECT AVG(CAST(participants.date_of_birth as decimal)) AS average_cast_participants_date_of_birth_as_decimal, title AS title
FROM `activities`
INNER JOIN `locations` ON `locations`.`activity_id` = `activities`.`id`
INNER JOIN `participants` ON `participants`.`location_id` = `locations`.`id`
INNER JOIN `stuffs` ON `stuffs`.`id` = `participants`.`stuff_id`
WHERE `stuffs`.`my_field` = 1
GROUP BY title

which AR makes in to a hash looking like this:
{"dummy title"=>#<BigDecimal:7fe9fe44d3c0,'0.19652273E4',18(18)>, "stats test"=>nil}


Q: I am unable to get show different devices both audio and video available during stream I was just going through https://github.com/ScaleDrone/webrtc/blob/master/script.js but there is no way i could select from the devices and stream
navigator.mediaDevices.getUserMedia({
    audio: true,
    video: true,
  }).then(stream => {
    // Display your local video in #localVideo element
    localVideo.srcObject = stream;
    // Add your stream to be sent to the conneting peer
    stream.getTracks().forEach(track => pc.addTrack(track, stream));
  }, onError);

how do i get all the device id shown for both video as well as audio source . please helpp me anyone
i just want that all device id should be shown and i can select any one from them.
I actually mean to say that when i use this on my phone it only selects my front camera . but what command should i insert here so that i can move to my rear camera or any other camera device attached and same is the case of audio, there are no audio devices to select from

A: I think you are looking for enumerateMediaDevices it seems to be implemented on all recent browsers (Not IE).


Q: How to show NEW post content in post editor? In my functions.php I have:
 global $wpdb;
 $wpdb->update(
   $wpdb->posts,
   array('post_content' => $newcontent),
   array('ID' => $post_id)
 );

this code updates the post_content in the WP DB with my $newcontent when I publish a post.
In fact I can see the modified content inside the DB and of course I can see it with:
 echo get_post_field('post_content', $post_id);

The issue is that (after publish and update) the post editor continues to show the old content!
In a few words... I need a way to force the editor to show the $newcontent, the one stored into the DB (after publish).
Any ideas?

A: try wp update post function:
// Update post 37 for example
  $my_post = array(
  'ID'           => 37,
  'post_title'   => 'This is the post title.',
  'post_content' => 'This is the updated content.',
  );

// Update the post into the database
  wp_update_post( $my_post );

https://codex.wordpress.org/Function_Reference/wp_update_post

A: I am not quite sure what is your scenario, but I think you need to refresh the WordPress editor. If you did that try to update the post since it is cached.
https://codex.wordpress.org/Function_Reference/wp_update_post


Q: Can you mix string and object outputs in SQL JSON? I'm trying to construct a JSON-serialized list of key/value pair items from my SQL database (compat level 140).  The trick is that the values can be anything: numbers, strings, null, or other JSON objects.
It should be able to look something like this:
[{"key":"key1","value":"A String"},{"key":"key2","value":{"InnerKey":"InnerValue"}}]

However, SQL seems to be forcing me to select either a string or an object.
SELECT
       [key] = kvp.[key],
       [value] = CASE
              WHEN ISJSON(kvp.[value]) = 1 THEN JSON_QUERY(kvp.[value])
              ELSE '"' + kvp.[value] + '"'  -- See note below
              END
FROM (VALUES
        ('key1', 'This value is a string')
       ,('key2', '{"description":"This value is an object"}')
       ,('key3', '["This","value","is","an","array","of","strings"]')
       ,('key4', NULL)

       -- Without these lines, the above 4 work fine; with either of them, even those 4 are broken
       --,('key5', (SELECT [description] = 'This value is a dynamic object' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER))
       --,('key6', JSON_QUERY((SELECT [description] = 'This value is a dynamic object' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)))
) AS kvp([key], [value])
FOR JSON PATH

Am I trying to do something that SQL can't support, or am I just missing the proper syntax for making this work?
*Note that the addition of the double-quotes seems like it shouldn't be necessary.  But without those, SQL fails to wrap the string and generates bad JSON:
[{"key":"key1","value":This value is a string},...

A: If your query is modified to this, it works:
SELECT
   [key] = kvp.[key],
   [value] = ISNULL(
          JSON_QUERY(CASE WHEN ISJSON(kvp.[value]) = 1 THEN kvp.[value] END),
          '"' + STRING_ESCAPE(kvp.[value], 'json') + '"'
   )
FROM (VALUES
   ('key1', 'This value is a "string"')
   ,('key2', '{"description":"This value is an object"}')
   ,('key3', '["This","value","is","an","array","of","strings"]')
   ,('key4', NULL)

   -- These now work
   ,('key5', (SELECT [description] = 'This value is a dynamic object' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER))
   ,('key6', JSON_QUERY((SELECT [description] = 'This value is a dynamic object' FOR JSON PATH, WITHOUT_ARRAY_WRAPPER)))
) AS kvp([key], [value])
FOR JSON PATH, INCLUDE_NULL_VALUES

Of course, this wouldn't be sufficient if value was an int. Also, I can't really explain why yours doesn't work.


Q: function that moves capitals to the front of a string and capitalizes lowercase letters? I'm trying to make a function that takes in a string as an input. It then moves the capital letters in the string to the front, and capitalizes lower-case letters. Lower-case letters and spaces should be kept in the same position relative to their location in the original string.
For example:
unravel_message(' neHAw moPPnthY')

should return 'HAPPY NEW MONTH' as the output.
and unravel_message('ALL CAPITALS')
should return 'ALLCAPITALS ' as the output.
(the space remains in the same location; only the capitals are moved back)
My Attempt:
def unravel_message(word):
    return ''.join([i for i in word if i == i.upper()]) + ''.join([i.upper() for i in word if i == i.lower()])

for my function, unravel_message(' neHAw moPPnthY') outputs ' HA PPY NEW MONTH'. Which isn't quite right. I think this may be because of the ''.join(). I would like to revise this function to use a single list comprehension wihtout imports if possible. If the inputs are all lowercase, I would also like to include an assertion statement addressing an error but I'm not sure how to do this.

A: Timsort is stable, which means that you can get what you want with something like
>>> assert not message.islower()
>>> ''.join(sorted(message, key=lambda c: not c.isupper())).upper()
'HAPPY NEW MONTH'

The trick is that booleans are a subclass of integers in python. The key returns False == 0 for elements you want to move to the beginning, and True == 1 for elements that stay. You need to use lambda c: not c.isupper() because spaces and other characters will move back if you use str.islower as the key.
If you want the assertion to be more detailed, like checking if all the letter characters are lowercase, you can do it with something like
>>> assert any(c != c.lower() for c in message)

For more complex unicode code points, use c.casefold() instead of c.lower().

A: Here is a solution that uses a single list comprehension without imports. It is also linear in time with the length of the string unlike sorting solutions with have higher time complexity of O(n log n). It also has an assertion statement flagging strings with no uppercase letters (i.e., all alpha characters are lowercase).
def unravel_message(s):
    assert any('A' <= c <= 'Z' for c in s)
    return (duo := list(map(lambda x: ''.join(x).replace(chr(0), ''), zip(*[(c, chr(0)) if c.isupper() else (chr(0), c.upper()) for c in s]))))[0] + duo[1]

x = unravel_message(' neHAw moPPnthY')
print(x)
x = unravel_message(' no uppercase letters')

Output:
HAPPY NEW MONTH
Traceback (most recent call last):
  File "C:\python\test.py", line 7, in <module>
    x = unravel_message(' no uppercase letters')
  File "C:\python\test.py", line 2, in unravel_message
    assert any('A' <= c <= 'Z' for c in s)
AssertionError

Note that the solution uses the walrus operator := to make it a one-liner. If you are using Python earlier than version 3.8, you can do this instead:
def unravel_message(s):
    assert any('A' <= c <= 'Z' for c in s)
    duo = list(map(lambda x: ''.join(x).replace(chr(0), ''), zip(*[(c, chr(0)) if c.isupper() else (chr(0), c.upper()) for c in s])))
    return duo[0] + duo[1]


Q: добавить данные в бд из 4 textbox по нажатию кнопки ERROR: validation failed for one or more entities. See "EntityValidationErrors" property for more details.
 public PageAddTest()
        {
            InitializeComponent();
            cmbxQuestion.SelectedValuePath = "id_question";
            cmbxQuestion.DisplayMemberPath = "nameQuestion";
            cmbxQuestion.ItemsSource = AppConnect.modelOdb.Question.ToList();

        }

        private void BtnSubmit_Click(object sender, RoutedEventArgs e)
        {
            if (Rbtn1.IsChecked == false &&
                Rbtn2.IsChecked == false &&
                Rbtn3.IsChecked == false &&
                Rbtn4.IsChecked == false
                )
            {
                MessageBox.Show("error", "error",
                    MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            try
            {
                Answers userObj = new Answers()
                {
                    Question = cmbxQuestion.SelectedItem as Question,
                    isCorrect = false,

                };

                AppConnect.modelOdb.Answers.Add(new Answers() { nameAnswer = TxbAnswer1.Text });
                AppConnect.modelOdb.Answers.Add(new Answers() { nameAnswer = TxbAnswer2.Text });
                AppConnect.modelOdb.Answers.Add(new Answers() { nameAnswer = TxbAnswer3.Text });
                AppConnect.modelOdb.Answers.Add(new Answers() { nameAnswer = TxbAnswer4.Text });
                AppConnect.modelOdb.Answers.Add(userObj);
                AppConnect.modelOdb.SaveChanges();

                MessageBox.Show("Данные добавлены", "",
                MessageBoxButton.OK, MessageBoxImage.Exclamation);

            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка добавления данных " + ex.Message, "",
                   MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }


Q: Which one is better in terms of Speed and memory usage or simply best practice I have a function with a lot of constant variables inside. Would it be better to store these variables in a Hash-map (it would be a complicated one) (it would have hash-maps inside the Hash-map. Or several if, else if clauses. In terms of readability they're about the same. But What I'm worried about is the memory taken and the speed of the app. This is a extremely simplified version of the problem :
function myFunction(data) {
    var a = 0, b = 0, c = 0, d = 0;
    if(data == value1) {
        a += 3;
        if(value1Fetched) {
           b += 6;
           c +=2;
           d +=1;
        }
    } else if (data == value2) {
        a += 1;
        if(value2Fetched) {
           b += 4;
           c +=9;
        }
    }
return a+b+c+d;
}

Obviously there are way more flags and values (and Data is a Hash-map too)
version 2 :
function myFunction(data) {
    var a = 0, b = 0, c = 0, d = 0;
    var myHash = {
        value1: {
            a: 3,
            b: 6,
            c: 2,
            d: 1
        },
        value2: {
            a: 1,
            b: 4,
            c: 9,
            d: 0
        }
    };
    a += myHash[data][a];
    if(isFetched(data)){
        b += myHash[data][b];
        c += myHash[data][c];
        d += myHash[data][d];
    }
return a+b+c+d;
}

Sorry for the messy (pseudo)code, i tried to make it as readable as possible.
This has been haunting me for days and everyone at work has a different opinion.

A: I would say the extensibility of the second question far outweighs any possible (and unlikely) performance issues. You can even change that structure on the fly if needed, or have multiple instances for two environments where the mapping turns out different.
It might be slower for examples as small as the one you posted, but it sounds like the actual might have a great many entries, in which case using a map lookup has O(log(n)) complexity rather than O(n) (hope I have those terms correct! Been a while since college). Large JSON objects (string-maps) are not uncommon in JavaScript, in fact you often work with them for the libraries and browser features in common code.


Q: Apache httpd.conf file: How to add condition to check url is HTTPS or HTTP I want to set "SameSite" and "Secure" as follows in httpd.conf file, only if url is https only.
How can add condition to check if url is https or http
Header always edit Set-Cookie (.*) "$1; SameSite=None; Secure"
Header onsuccess edit Set-Cookie (.*) "$1; SameSite=None; Secure
I have tried following solutions but didn't help:
<If "reqenv('HTTPS') == 'on'">
SetEnvIf HTTPS "on" HAS_HTTPS
SetEnvIfExpr "tolower(req('HTTPS')) =='on'" HAS_HTTPS


Q: Failed to call a dynamic method in a static context? These are created using Android Studio similar to How to modify dummy content in android master/detail activity?. I changed the static method under dummyContent into below:
public void fetchData() {
    // Add some sample items.
    for (int i = 1; i <= COUNT; i++) {
        addItem(createDummyItem(i));
    }

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(
                    DummyContent.UNAME, DummyContent.PASSWORD.toCharArray());
        }
    });

    try {
        DummyContentRegistry registry = new XMLDummyContentParser(DummyContent.url).parse();
        for (DummyContent.DummyItem t: registry.getTeachers()) {
            DummyContent.addItem(t);
        }
    } catch (Exception e) {
        fail("Exception should not have been thrown");
    }
}

while above passed the test:
public class DummyContentRegistryTest {
    @Before
    public void buildRegistry() {}

    @Test
    public void testFetchData() {
        Assert.assertEquals(0,DummyContent.ITEMS.size());
        new DummyContent().fetchData();
        Assert.assertEquals(27,DummyContent.ITEMS.size());// two more items are added through parsing xml on a website
    }

}

However when I call the method under MainActivity.onCreate it failed "Exception should not have been thrown". Why? Here's an example of failing call
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (DummyContent.ITEMS.isEmpty()) {
        new DummyContent().fetchData();
    }
......
}

I don't know if the problem is similar to calling non-static method in static method in Java but I've obviously tried the way most of them agreed.
    [ 07-25 04:04:56.442 23983:24025 D/         ]
                                                                                HostConnection::get() New Host Connection established 0x7f1b57910500, tid 24025
07-25 04:04:56.460 23983-24025/*****private*****.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
07-25 04:04:56.873 23983-23983/*****private*****.myapplication I/Choreographer: Skipped 32 frames!  The application may be doing too much work on its main thread.
07-25 04:05:07.474 23983-23983/*****private*****.myapplication W/System.err: java.io.IOException: Couldn't open *****private*****
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:755)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:292)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at javax.xml.parsers.SAXParser.parse(SAXParser.java:390)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at javax.xml.parsers.SAXParser.parse(SAXParser.java:266)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at *****private*****.myapplication.dummy.XMLDummyContentParser.parse(XMLDummyContentParser.java:33)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at *****private*****.myapplication.dummy.DummyContent.fetchData(DummyContent.java:53)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at *****private*****.myapplication.MainActivity.onCreate(MainActivity.java:52)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.Activity.performCreate(Activity.java:6237)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.ActivityThread.-wrap11(ActivityThread.java)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.os.Looper.loop(Looper.java:148)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err: Caused by: android.os.NetworkOnMainThreadException
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:215)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
07-25 04:05:07.475 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:384)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:231)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:     at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:753)
07-25 04:05:07.476 23983-23983/*****private*****.myapplication W/System.err:    ... 18 more
07-25 04:05:07.483 23983-23983/*****private*****.myapplication D/AndroidRuntime: Shutting down VM

07-25 04:05:07.484 23983-23983/*****private*****.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: ******private*******, PID: 23983
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{******private*******.myapplication.MainActivity}: java.lang.IllegalStateException: Already attached
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                                at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                                Caused by: java.lang.IllegalStateException: Already attached
                                                                                at android.support.v4.app.FragmentManagerImpl.attachController(FragmentManager.java:2126)
                                                                                at android.support.v4.app.FragmentController.attachHost(FragmentController.java:104)
                                                                                at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:313)
                                                                                at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
                                                                                at *****private*****.myapplication.MainActivity.onCreate(MainActivity.java:55)
                                                                                at android.app.Activity.performCreate(Activity.java:6237)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                                at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

A: The Exception e, which you catch may contain useful information on what exactly went wrong. Do e.printStackTrace(); inside your catch-block to print all available information to the standard output.
If that does not help you solve the problem post the stacktrace here.

A: You cannot manipulate UI thread from background thread thats why you are getting this error.
ClassName.this.runOnUiThread(new Runnable() {
                public void run() {
                //Do something on UiThread

                // enclose your UI manipulated code here in these braces.
            }
        });


Q: How can I get the number of pages in a PDF file inside a Google Apps Script? The PDF files are in my Google Drive. I just got that I can get the number of pages of a PDF sending it as a job to Cloud Print, because Cloud Print will return a JSON object with "numberOfPages" attribute.
Is there any faster and easier way? Thanks in advance.

A: Well, I actually did like I said.
I take my file, then send it to CloudPrint via its JSON Api. I need to send it to a dummy printer, a printer I registered in CloudPrint but actually is never connected to Internet. Then, I get the number of pages of the PDF file in the value of response's "numberOfPages" attribute. Save this number in some var. Finally, I send a delete petition to JSON Api for my file in the dummy printer, indeed isn't necessary at all.
Thanks!


Q: Bash script in raspbian runs manually, won't run in cron Trying to turn a small TV into a photo frame so to speak, so I have a Raspberry Pi and I have a bash script at /home/pi/scripts/script.sh:
#!/bin/sh
sudo /usr/bin/gpicview /home/pi/Downloads/test_5_25.png >> /home/pi/Downloads/test.log

My cron tab looks like this:
    # m h  dom mon dow   command
* * * * * sh /home/pi/scripts/script.sh
My syslog shows that its running:
May 27 04:32:01 raspberrypi /USR/SBIN/CRON[2999]: (pi) CMD (sh /home/pi/scripts/script.sh

But gpicview is not opening like when I run the script manually, and in my error log it shows...

option parsing failed: Cannot open display:

I thought maybe permissions or something, but I've double checked those to the best of my ability and cannot figure it out. Any clues would be greatly appreciated!!

A: You probably need to set the display manually, i.e.:
* * * * * export DISPLAY=:0 && sh /home/pi/scripts/script.sh

As outlined in this article.