text:
Q: Expandable listview - Highlight I have used a customised expandable listview in my application.
I have used individual xml for parent and child rows. I have set the color of both these xml's as white. Now, the issue i have is, the expandable listview is not getting highlighted in orange color on clicking a parent or child row.
How can  I accomplish this?
Any help in this regard would be well appreciated.
Best Regards,
Rony

A: You might have to use a state list drawable to specify an alternate color for pressed views (assuming that when you changed the views to white, you did so by giving them a white drawable for the background).  Without seeing the XML/code, though, I can't say for sure.
Alternatively, you may actually be able to use a color state list.


text:
Q: Why does comparing an environment variable value with a string result in an error message? I tried to compare current date on being equal to a specific date using this code:
@echo on
if %date%=="Sun 10/15/2017" ( echo "Today is Sunday" ) else ( echo "Today is Unknown" )
pause

But on execution of the batch file I get just output the error message:

10/15/2017=="Sun 10/15/2017" was unexpected at this time.

What is the reason for this error?

A: The date environment variable reference %date% is replaced by Windows command interpreter during the preprocessing state by the region (country) dependent string before the IF command is executed at all.
On running the batch file from within a command prompt window it can be seen that the IF command line is after preprocessing:
if Sun 10/15/2017=="Sun 10/15/2017" ( echo "Today is Sunday" ) else ( echo "Today is Unknown" )

So the syntax of IF command is not correct after environment variable expansion because there is Sun as first argument, a space and Sun 10/15/2017=="Sun 10/15/2017" being interpreted as unexpected operator.
Whenever comparing strings it is recommended to use double quotes as only within a double quoted string the space character is not interpreted as argument separator. And the characters &()[]{}^=;!'+,`~|<> are also interpreted as literal characters within a double quoted string.
The double quotes are also compared by IF on running the string comparison. So it is needed that both compared strings are enclosed in double quotes.
@echo off
if "%DATE%"=="Sun 10/15/2017" ( echo "Today is Sunday." ) else ( echo "Today is unknown." )
pause

Another solution if region dependent date really contains the abbreviated weekday too.
@echo off
if not "%DATE:Sun=%"=="%DATE%" ( echo "Today is Sunday." ) else ( echo "Today is unknown." )
pause

This batch file compares the current date string with all case-insensitive occurrences of Sun being replaced by nothing with unmodified current date string. The string substitution is successful only on date string containing weekday abbreviation Sun and in this case the two compared strings are not equal.
On my computer the IF condition is never true as %DATE% expands to a date string not containing weekday according to configuration in Windows Region and Language settings.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

*

*echo /?

*if /?

*set /?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Centering two tables in landscape modus The posts seems very similar to the one's already posted two tables side by side in landscape mode but I have difficulties centering my first tables in the middle of a landscape page. This is only a script of my thesis which spans a lot of pages. As it is my whole thesis, I excuse the long preamble. I would like to fit in these two landscape tables below into my thesis. The tables are too big by nature, therefore I scaled them. How can I set the tables to be in the middle of the page. I have tried \centering in both, the \table and \minipage modus. I also tried it without \table,  but I wish one caption above both minipage tables. Any help is highly appreciated. Thanks
\documentclass[a4paper, 11pt, oneside]{report}
%========= PACKAGES
\usepackage[english]{babel}
\usepackage[T1]{fontenc}
\usepackage[latin1]{inputenc}
%========= LAYOUT
\usepackage{fullpage}
\usepackage{pdflscape}
\usepackage{afterpage}
%========= MATH
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{siunitx}
%========= TABLES
\usepackage{longtable}
\usepackage{wrapfig}
\usepackage{booktabs}
\usepackage{multirow}
\sisetup{input-symbols = {()},  % do not treat "(" and ")" in any special way
         group-digits  = false} % no grouping of digits
%========= GRAPHICS
\usepackage{caption}
\usepackage{subcaption}
%========= DOKUMENT =================
\begin{document}
\clearpage % begin landscape tables
\begin{landscape}
\begin{table}[htp]
\centering
\caption[]{GARCH-VaR - out-of-sample estimates} \label{tab:VaRresultsgarch}
\begin{minipage}{0.48\columnwidth}
\resizebox{\columnwidth}{!}{%
\begin{tabular}{@{}
    S[table-number-alignment = right,
    table-figures-integer = 1,
    table-figures-decimal = 3]
    S
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = right,
    table-figures-integer = 1,
    table-figures-decimal = 3]
    S
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 4,
    table-space-text-post = \textsuperscript{*}]
    @{}}
\toprule
 & & \multicolumn{3}{c}{GARCH} & & &  \multicolumn{3}{c}{GARCH}\\
\cmidrule(rl){3-5} \cmidrule(l){8-10}
{\textbf{CHF}} & {Test} & {Normal} & {Std-$t$} & {GED} & {\textbf{EUR}} & {Test} & {Normal} & {Std-$t$} & {GED} \\
\cmidrule(r){1-5} \cmidrule(l){6-10}
\SI{5.0}{\percent} & {VR} & 5.213 & 5.611 & 5.054 & \SI{5.0}{\percent} & {VR} & 4.584 & 4.895 & 4.429 \\
\end{tabular}%
}
\end{minipage}\quad
%=========== new tabular =============
\begin{minipage}{0.48\columnwidth}
\resizebox{\columnwidth}{!}{%
\begin{tabular}{@{}
    S[table-number-alignment = right,
    table-figures-integer = 1,
    table-figures-decimal = 3]
    S
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = right,
    table-figures-integer = 1,
    table-figures-decimal = 3]
    S
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 4,
    table-space-text-post = \textsuperscript{*}]
    @{}}
\toprule
 & & \multicolumn{3}{c}{GARCH} & & &  \multicolumn{3}{c}{GARCH}\\
\cmidrule(rl){3-5} \cmidrule(l){8-10}
{\textbf{CHF}} & {Test} & {Normal} & {Std-$t$} & {GED} & {\textbf{EUR}} & {Test} & {Normal} & {Std-$t$} & {GED} \\
\cmidrule(r){1-5} \cmidrule(l){6-10}
\SI{1.0}{\percent} & {VR} & 1.512 & 1.114 & 1.114 & \SI{1.0}{\percent} & {VR} & 1.243 & 0.932 & 0.932 \\
\end{tabular}%
}
\end{minipage}
\end{table}
\clearpage
%=========== new page and tabular =============
\begin{table}[htp]
\centering
\begin{minipage}{0.48\columnwidth}
%\caption{GARCH-VaR - out-of-sample estimates $p = 0.005$}
\resizebox{\columnwidth}{!}{%
\begin{tabular}{@{}
    S[table-number-alignment = right,
    table-figures-integer = 1,
    table-figures-decimal = 3]
    S
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = right,
    table-figures-integer = 1,
    table-figures-decimal = 3]
    S
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 4,
    table-space-text-post = \textsuperscript{*}]
    @{}}
\toprule
 & & \multicolumn{3}{c}{GARCH} & & &  \multicolumn{3}{c}{GARCH}\\
\cmidrule(rl){3-5} \cmidrule(l){8-10}
{\textbf{CHF}} & {Test} & {Normal} & {Std-$t$} & {GED} & {\textbf{EUR}} & {Test} & {Normal} & {Std-$t$} & {GED} \\
\cmidrule(r){1-5} \cmidrule(l){6-10}
\SI{0.5}{\percent} & {VR} & 0.836 & 0.358 & 0.398 & \SI{0.5}{\percent} & {VR} & 0.777 & 0.622 & 0.622 \\
\end{tabular}%
}
\end{minipage}\quad
%=========== new tabular =============
\begin{minipage}{0.48\columnwidth}
\resizebox{\columnwidth}{!}{%
\begin{tabular}{@{}
    S[table-number-alignment = right,
    table-figures-integer = 1,
    table-figures-decimal = 3]
    S
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = right,
    table-figures-integer = 1,
    table-figures-decimal = 3]
    S
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 3,
    table-space-text-post = \textsuperscript{**}]
    S[table-number-alignment = center,
    table-figures-integer = 2,
    table-figures-decimal = 4,
    table-space-text-post = \textsuperscript{*}]
    @{}}
\toprule
 & & \multicolumn{3}{c}{GARCH} & & &  \multicolumn{3}{c}{GARCH}\\
\cmidrule(rl){3-5} \cmidrule(l){8-10}
{\textbf{CHF}} & {Test} & {Normal} & {Std-$t$} & {GED} & {\textbf{EUR}} & {Test} & {Normal} & {Std-$t$} & {GED} \\
\cmidrule(r){1-5} \cmidrule(l){6-10}
\SI{0.1}{\percent} & {VR} & 0.239 & 0.08 & 0.159 & \SI{0.1}{\percent} & {VR} & 0.233 & 0.078 & 0.078 \\
\end{tabular}%
}
\end{minipage}
\end{table}
\end{landscape}
\end{document}

A: I ment to center the tables vertically. After several attempts I found the solution. When setting the table on an empty page the \table environment may not contain a positioning defined by [htbp].
By removing [htbp] the tables centered properly.
\clearpage

\begin{table}% ... [htp] <- remove
\centering
\begin{minipage}{0.48\columnwidth}
%\caption{GARCH-VaR - out-of-sample estimates $p = 0.005$}
\resizebox{\columnwidth}{!}{%
\begin{tabular}{@{}
% ...content
\end{tabular}%
}
\end{minipage}
\end{table}

Sorry for the post and hopefully this helps others.


text:
Q: Object's address, passed from Lua to C++, is returning me the wrong value in a member variable I'm currently trying some experiences with the SWIG tool for wrapping generation of C++ and Lua code.
After some fighting with SWIG (trying to set it up, learn how it works, etc...), I finally got a working example.
However, I've come up with an awkward result in one of my experiments.
I was trying to recover a Lua's userdata back to C++ and change some of it's values.
Here is what i got in my console results:
Console

C++: index.cpp
Lua: Foo.lua

C++: Constructor of 0xb2d9f0
Lua: Adress of lFoo = userdata: 0xb35048

C++: Set - Old = 12 New = 4
Lua: Foo->Value = 4

Lua: Bye World

C++: Lua's lFoo To C++
C++: Adress of lFoo = 0xb35048
C++: Foo->Value = 1
C++: Set - Old = 1 New = 44
C++: Popping Foo from Lua
C++: Closing lLuaState
C++: Destructor of 0xb2d9f0
C++: Bye World

Before I state where things are getting confused to me, let me paste some of the other codes is this examples, so that the console output gets lesser abstract:
Foo.h

#ifndef FOO_H_
#define FOO_H_

#include <iostream>

class Foo
{
    public:
        Foo( int a_value );
        virtual ~Foo();

        int getValue(){ return m_value; }
        void setValue( int a_value )
        {
            std::cout << "C++: Set - Old = " << m_value << " New = " << a_value << "\n";
            m_value = a_value;
        }
    private:
        int m_value;
};

#endif /* FOO_H_ */

Foo.cpp

#include "Foo.h"

Foo::Foo( int a_value ) : m_value( a_value )
{
    std::cout << "C++: Constructor of " << this << "\n";
    //setValue( a_value );
}

Foo::~Foo()
{
    std::cout << "C++: Destructor of " << this << "\n";
}

index.cpp

#include <string>
#include <iostream>
#include <lua.hpp>

#include "Foo.h"

extern "C" int luaopen_Foo(lua_State* L); // declare the wrapped module

const std::string ctLuaFooFile = "Foo.lua";

int main( int argc, char * args[] )
{
    std::string lLuaFile = ctLuaFooFile;

    std::cout << "C++: index.cpp\n";

    lua_State *lLuaState;

    lLuaState = lua_open();

    luaL_openlibs( lLuaState );

    luaopen_Foo( lLuaState );

    Foo * lFoo;

    if ( luaL_loadfile( lLuaState, lLuaFile.c_str() ) == 0 ) // load and run the file
        {
        int lError = lua_pcall( lLuaState, 0, 0, 0 );

        if ( lError )
        {
            std::cout << "Lua Error: " << lua_tostring( lLuaState, -1 );
            lua_pop( lLuaState, 1 );  /* pop error message from the stack */
        }

        std::cout << "C++: Lua's lFoo To C++\n";

        lua_getglobal( lLuaState, "lFoo");

        lFoo = static_cast<Foo *>( lua_touserdata( lLuaState, -1 ) );

        std::cout << "C++: Adress of lFoo = " << lFoo << "\n";

        std::cout << "C++: Foo->Value = " << lFoo->getValue() << "\n";

        lFoo->setValue( 44 );

        std::cout << "C++: Popping Foo from Lua\n";
        //Is Foo's destructor invoked here? --No
        lua_pop( lLuaState, -1 );
    }
    else
    {
        std::cout << "unable to load" << lLuaFile << "\n";
    }

    std::cout << "C++: Closing lLuaState \n";
    //Foo's destructor getting invoked here!
    lua_close( lLuaState );

    std::cout << "C++: Bye World\n";

    if( lFoo )
    {
        delete lFoo;
    }

    return 0;
}

Now that things are a little clearer on how I got those console outputs, let me tell you where my questions lie:
1º - Why, when I got the reference from lFoo back to C++, in line lFoo = static_cast<Foo *>( lua_touserdata( lLuaState, -1 ) ); its address was 0xb35048 (which seems to be a specific Lua pointer) instead of 0xb2d9f0 (which appeared in the C++ side of the code)?
2º - Even if those pointers are on different addresses, they both appear to be pointing to the same Foo object (or at least, to "a" Foo object), except that when I check C++ lFoo->getValue() I get 1 instead of 4. Why is that?
I consided that i could be getting an second Foo object, but his constructor was never called.
3º - Also, am I doing something wrong when I get my Foo's reference back to C++? Is there a better way of doing it?
4º - And finally, when I call lua_close( lLuaState );, Foo's Destructor is getting called. Is there a way for me to change the responsability of destroying this object in the C++ side? I think i read something about it in the SWIG docs but I can't seen to remember where.

For those willing to try my experiment, I will leave here the Foo.i interface file, used by the SWIG tool to create Foo_wrap.cxx, as well as the console commands used by my Eclipse, SWIG and g++ compiler:
Foo.i

/* File : example.i */
%module Foo

%{
#include "Foo.h"
%}

/* Let's just grab the original header file here */
%include "Foo.h"

Console commands

**** Build of configuration Debug for project SwigDemo ****

make pre-build main-build
Criando wrappers para lua
swig -c++ -lua ../Foo.i

Building file: ../Foo.cpp
Invoking: GCC C++ Compiler
g++ -I/usr/include/lua5.1 -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"Foo.d" -MT"Foo.d" -o"Foo.o" "../Foo.cpp"
Finished building: ../Foo.cpp

Building file: ../Foo_wrap.cxx
Invoking: GCC C++ Compiler
g++ -I/usr/include/lua5.1 -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"Foo_wrap.d" -MT"Foo_wrap.d" -o"Foo_wrap.o" "../Foo_wrap.cxx"
Finished building: ../Foo_wrap.cxx

Building file: ../index.cpp
Invoking: GCC C++ Compiler
g++ -I/usr/include/lua5.1 -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"index.d" -MT"index.d" -o"index.o" "../index.cpp"
Finished building: ../index.cpp

Building target: SwigDemo
Invoking: GCC C++ Linker
g++ -L/usr/lib -L"/home/bruno/Programas/eclipse/workspace/SwigDemo/Debug" -o"SwigDemo"  ./Foo.o ./Foo_wrap.o ./index.o   -llua5.1
Finished building target: SwigDemo

Ps: I'm sorry for the long post. If there is a ways to improve it, I'd be more than happy to listen about it.

A: 1) Since the pointer value lFoo that you print out on the C++ side is different from any Foo that has been constructed, we can conclude that lFoo does not point to a Foo object.
2) lFoo->getValue() does not return the 4 that was stored in the Foo object, because the data at lFoo is not a Foo, but a wrapper.
3) Here is one way: in index.cpp read in the contents of the Foo module (and don't link to it anymore):
#include "foo_wrap.cxx"

Replace
lFoo = static_cast<Foo*>(lua_touserdata(lLuaState, -1));

with
void* ptr;
SWIG_ConvertPtr(
    lLuaState, -1, &ptr, SWIGTYPE_p_Foo, SWIG_POINTER_DISOWN);
lFoo = static_cast<Foo*>(ptr);

4) Pass 0 instead of SWIG_POINTER_DISOWN, if you don't want to take ownership of the Foo value.


text:
Q: How can I do to add the condition AND using exlude? I have this query :
MyTable.objects.filter(date=date).exclude(starthour__range=(start, end), endhour__range=(start, end))

But I want exclude the queries that starthour__range=(start, end) AND endhour__range=(start, end) not OR. I think in this case the OR is used.
Could you help me please ?
Thank you very much !

A: This is consequence of De Morgan's law [wiki], this specifies that ¬ (x ∧ y) is ¬ x ∨ ¬ y. This thus means that the negation of x and y, is not x or not y. Indeed, if we take a look at the truth table:
 x | y | x ∧ y | ¬x | ¬y | ¬(x ∧ y) | ¬x ∨ ¬y
---+---+-------+----+----+----------+---------
 0 | 0 |   0   | 1  | 1  |    1     |    1
 0 | 1 |   0   | 1  | 0  |    1     |    1
 1 | 0 |   0   | 0  | 1  |    1     |    1
 1 | 1 |   1   | 0  | 0  |    0     |    0
So excluding items where both the starthour is in the(start, end) range and endhour is in the (start, end) range, is logically equivalent to allowing items where the starthour is not in the range, or where the endhour is not in the range.
Using and logic
You can thus make a disjunction in the .exclude(…) call to filter out items that satisfy one of the two conditions, or thus retain objects that do not satisfy any of the two conditions:
MyTable.objects.filter(date=date).exclude(
    Q(starthour__range=(start, end)) | Q(endhour__range=(start, end))
)
Overlap logic
Based on your query however, you are looking for overlap, not for such range checks. It will not be sufficient to validate the starthour and endhour. If you want to check if two things overlap. Indeed, imagine that an event starts at 08:00 and ends at 18:00, and you filter for a range with 09:00 and 17:00, then both the starthour and endhour are not in the range, but still the events overlap.
Two ranges [s1, e1] and [s2, e2] do not overlap if s1≥ e2, or s2≥ e1. The negation, the condition when the two overlap is thus: s1< e2 and s2< e1. We thus can exclude the items that overlap with:
# records that do not overlap

MyTable.objects.filter(date=date).exclude(
    starthour__lt=end, endhour__lt=start
)


text:
Q: Why must the accessor be more restrictive than the property? I have this code:
public string foo { get; set; }

Now, I interpret this as my object has a public property called foo, and both it's accessor's are public. If I write this:
private string foo { get; set; }

I interpret that as my object has a private property called foo, and both it's accessor's are private. I understand making the property itself private. What I don't understand is why the accessor's must be more restrictive?  If I write:
private string foo { public get; public set; }

I interpret that my object has a private property called foo, and both's it's accessor's are public, which is the behavior that I want. I'd like the private property with public accessors. I mean, if I have to write a Get/Set method, I will. But I'm just confused as to why this is.

A: A property is actually (under water) nothing more than two methods:
public string foo { get; set; }

will translate into:
public string get_foo() { ... }
public void set_foo(string value) { ... }

These methods can only have ONE access modifier, not a combination of two.
If I remember correcly, C#v1 did not support access modifiers for the getters and setters. There was one access modifers for the property which was used for both functions.
In v2 it was possible to "override" one of getter/setter-pair, this way overrwriting the "other" function. There was no use to override both getters/setters, because in that would render the property-access modifier useless.
Why the access modifier for the getter/setter is more restrictive has, in my opinion, something to do with easier implementing interfaces which always have (implicitly public) properties.
For more info, read: http://msdn.microsoft.com/en-us/library/75e8y5dd(v=vs.80).aspx

A: Why you need such a property
private string foo { public get; public set; }

If you want to have you get set public, then make the property public.
The compiler will first check the access of the property and then its method. If the property is public then its method can have either public or private or any accessor


text:
Q: How do I reference id's of children within a canvas in Kivy? I get the error Invalid data after declaration when I try to assign an id to canvas, but I don't see any other way of referencing the id's further below (for example e1). How do I reference e1 in my Python code?
<MyClockWidget>:
    face: face
    ticks: ticks
    el1: el1
    FloatLayout:
        id: face
        size_hint: None, None
        pos_hint: {"center_x":0.5, "center_y":0.5}
        size: 0.9*min(root.size), 0.9*min(root.size)
        canvas:
            id: cand
            Color:
                rgb: 0.5, 0.5, 0.5
            Ellipse:
                size: self.size
                pos: self.pos
        canvas:
            Color:
                rgb: 0.1, 0.1, 0.1
            Ellipse:
                id: el1
                size: self.size
                pos: self.pos
                angle_start: 0
                angle_end: 90
            Ellipse:
                id: el2
                size: self.size
                pos: self.pos
                angle_start: 110
                angle_end: 130

A: I don't think the use of instruction groups in kv lang is well documented, but here is an example for how to use them to later access Canvas elements. This example also show how to use properties to control aspects of a Canvas instruction:
from kivy.app import App
from kivy.uix.slider import Slider
from kivy.lang import Builder
from kivy.graphics import Color

kv = """
#:kivy 1.9.1
BoxLayout:
    orientation: 'vertical'
    Widget:
        id: w_canvas
        my_color: (0, 1, 1)
        canvas:
            Color:
                rgb: self.my_color
            Rectangle:
                pos: self.pos
                size: (self.width/2, self.height/2)
            Color:
                group: 'b'
                rgb: (0, .8, 0)
            Ellipse:
                group: 'a'
                pos: (self.pos[0], self.pos[1] + self.height/2)
                size: (self.width/4, self.height/4)
            Ellipse:
                group: 'b'
                pos: (self.pos[0]+ self.width/2, self.pos[1] + self.height/2)
                size: (self.width/4, self.height/4)
    Button:
        text: 'Click me'
        on_release: app.handle_button()
"""
class Test(App):
    def build(self):
        return Builder.load_string(kv)
    def handle_button(self):
        # binding Canvas instruction property to Widget property
        self.root.ids.w_canvas.my_color = (.5, .2, 0)
        # Access single item of canvas instruction group
        an_ellipse = self.root.ids.w_canvas.canvas.get_group('a')[0]
        an_ellipse.pos = (an_ellipse.pos[0] + 10, an_ellipse.pos[1])
        # loop through all elements of canvas instruction group
        for gitem in self.root.ids.w_canvas.canvas.get_group('b'):
            if isinstance(gitem, Color):
                gitem.rgb = (0, .5, 1)
            try:
                gitem.size = (gitem.size[0] / 2.0, gitem.size[1])
            except:
                pass

Test().run()


text:
Q: MOD 11 Gun doesn't show up I have various guns for recon.  When I go to my soldier it shows up.  When I go use recon most of the time it doesn't show up to be able to use along with the other guns.
Anyone help? Greatly Appreciated.

A: Make sure you are on the USA side, because it is a US specific gun. Or, it could be a rare glitch that happens to me with the MP-443, where the gun disappears from the selection. If that's the case then just reboot the game and see if it appears.

A: There is a recent glitch that is sometimes keeping exp from being saved and weapons from appearing even after you unlock them.This glitch is getting patched soon
this is what the developers have on this glitch
http://www.computerandvideogames.com/350208/battlefield-3-stat-freeze-glitch-blamed-on-famas/


text:
Q: C++ regex, parsing I'm pretty new with regexp and I can't get my function doing what I would like.
I have a long string, and I want to extract from it, 3 variables.
My string looks :
 Infoname/info :
 Input_Device_Name GTape  Buffer_Size 16384 Acquisition_Event_Rate 163691.000000
 Acquisition_Buffer_Rate 14873.333008 Acquisition_Succes_Rate 100.000000

And my goal is to store 163691.000000, 14873.333008 and 100.000000 in three differents variables.
What is the fastest and nicest way to do it please ?
Thank you,
eo

A: You could use the following regex to look for it:
"Input_Device_Name\s+GTape\s+Buffer_Size\s+[0-9.]+\s+Acquisition_Event_Rate\s+([0-9.]+)\s+Acquisition_Buffer_Rate\s+([0-9.]+)\s+Acquisition_Succes_Rate\s+([0-9.]+)"

This should catch the three values assuming that your text stays the same and that your numbers always take this form (i.e. are positive and not in exponential form.) Note that only the last three numbers are captured by putting brackets round them.
If you use boost regex, you could do something like this:
#include <boost/regex.hpp>

...
boost::smatch what;
static const boost::regex pp("Input_Device_Name\\s+GTape\s+Buffer_Size\\s+[0-9.]+\\s+Acquisition_Event_Rate\\s+([0-9.]+)\\s+Acquisition_Buffer_Rate\\s+([0-9.]+)\\s+Acquisition_Succes_Rate\\s+([0-9.]+)");
if ( boost::regex_match(inputTextString, what, pp) )
{
    if ( what.size() == 4 )
    {
         double d1 = strtod(static_cast<const string&>( what[1] ).c_str(), NULL, 0);
         double d2 = strtod(static_cast<const string&>( what[2] ).c_str(), NULL, 0);
         double d3 = strtod(static_cast<const string&>( what[3] ).c_str(), NULL, 0);

         // These are your doubles, do some stuff with them.
    }
}

Where inputTextString contains the line of text you want to parse, so if this is coming from a file say, you would want to place this code in a loop. The what variable is a vector of all the matching text though what[0] contains the whole line and so can be ignored unless you need it. Last but not least, remember to double escape the 'space' character class otherwise it will already be processed (or generate an error or warning) by the compiler prior to being presented to the regex processor. Also, please note that I've not had time to compile this, though it is based on working code
Watch out for trailing, leading space on your input file and use ^ and $ to mark the beginning or end of the line respectively if it helps.

A: Just search for [0-9\.]+ as long as it returns any results. And, for example, if you would like to refuse 16384 as a variable you don't need, test every search result for having a dot in it.


text:
Q: Sql query that outputs last minute data Good day everyone, I solve this problem. We need to display data on statuses 200 and 500 for the last minute from clickhouse to our grafana monitor.
I expect this request to work and output last minute data, but as soon as I enter it into the monitor on Grafana, it throws a "request error"
"100 - (sum(StatusRes != '200'[1m]) * 100),
 100 - (sum(StatusRes == '200'[1m]) * 100),"

Also tried like this:
SELECT
    $ timeSeries as t,
    StatusRes,
    sum (StatusRes == '200') * 100 / (StatusRes == '500'),
    Provider
FROM $ table

WHERE $ timeFilter

GROUP BY
    t,
    StatusRes,
    Provider
ORDER BY
    t,
    StatusRes,
    Provider


text:
Q: IIS 8.5 Serving Old Files I have a clickonce application on Windows Server 2012 IIS 8.5. I recently updated it to a new version and it works fine, except for one url used by a second web page to link to it. It links directly to the .application file and when I use that link I get version 2.1.0.10 of that file instead of the one that is one the server version 3.1.0.1.
It's only when using the that link, other url's server the correct file. I've even stopped the website on both servers (load balanced) and the link still somehow downloads the old file.
I have cache and kernel cache turned off under Output Cache Settings in IIS, I have Common HTTP Response Headers set to Expire Web Content immediately, but it's still serving up and old file even though it doesn't exist anymore. I have a url rewrite rule for that specific url to redirect to one that works and still I download an old file.
I've restarted IIS and the servers themselves and nothing has changed. I then tried copying the files to a new folder and creating a new site in IIS. I copied over the bindings and stopped the old site and app pool. Still get served the old file.
Can anyone help me figure out what's going on with the IIS? How is it serving up a file that doesn't exist, even when the website is stopped? How can I get it to update?

A: I had the same issue and tried everything mentioned here (and elsewhere!), and finally found out that the reason was the IIS Compression cache!
On the IIS console, click on the website and then on the Compression, and uncheck the Enable static content compression.
This should solve the problem.

A: If the web server has been stopped, it is possible that this file may be 'served' from your browser's cache.
Have you tried clearing your browser's cache? If this doesn't work, it might be worth restarting the IIS service completely, or, failing that, moving the website's wwwroot directory elsewhere, and redeploying the latest version of your site, or simply renaming the .application file and re-deploying?
This would be akin to cleaning and re-building a project in Visual Studio.

A: This was eventually found to be caused by a setting on the load balancer caching results. We turned off this setting and now no longer have the issue.


text:
Q: Proof that a degree $4$ polynomial has a minimum
Let $$f(x) = x^4+a_3x^3+a_2x^2+a_1x+a_0.$$ Prove that $f(x)$ has a minimum point in $\Bbb{R}$.

The Extreme Value Theorem implies that the minimum exists in some $[a,b]$, but how do I find the right $a$ and $b$?

A: Hint Since $\lim_{x \to \infty} f(x) = +\infty$, for any $M \in \Bbb R$ one can find $b \in \Bbb R$ such that $x > b$ implies $f(x) > M$. Similarly, $\lim_{x \to -\infty} f(x) = +\infty$...

A: If $x>|a_3|+\sqrt{|a_2|}+\sqrt[3]{|a_1|}+\sqrt[4]{|a_0|}$ then $f(x)>0$.


text:
Q: Eigen values and vectors $$ X'(t)= \begin{bmatrix}x'(t)\\ y'(t) \end{bmatrix} = \begin{bmatrix}-5 & -2\\-1 & -4\end{bmatrix}\begin{bmatrix}x(t)\\ y(t) \end{bmatrix}$$
Sketch the directions field for the system, plot the straight line solutions
for each Eigenvalue, specify the corresponding straight line solution and its x(t) and y(t).
I found the Eigenvalues which are $-6, -3$ and the vectors $v_1 = (2,1) , v_2 = (-1,1)$
I need help to plot the lines

A: Hints:

*

*You found the eigenvalues and eigenvectors correctly.

*The solution is given as:

$$x(t) =  \dfrac{1}{3} c_1 e^{-6 t} (e^{3 t}+2)- \dfrac{2}{3} c_2 e^{-6 t} (e^{3 t}-1)$$
$$y(t) =  \dfrac{1}{3} c_2 e^{-6 t} (2 e^{3 t}+1)-\dfrac{1}{3} c_1 e^{-6 t} (e^{3 t}-1)$$

*

*Now, using all of the information below, direction fields, solutions, eigenvalues, eigenvectors, generate the phase portrait:

A: Your eigenvectors are missing from your plot. Note that you already have them there in your solution. No need to scratch around for equations. Plot (2,1) and a constant multiple of, it say (-2,-1) and draw the line through the points. (Actually only the first point is needed since the eigenvector passes through (0,0)). Do the same for eigenvector represented by (-1,1). Throw on some arrow heads and you are done.  Greg L.


text:
Q: Header of the table is devided into two pages in print window in chrome I am trying to print the page using window.print(). but when the row entry is multiplies and it is being shown in the other page, the header of the other page's table is devided between both of the pages. Here is the screenshot of what i am getting.

Here is my all code:
    <!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>atop</title>
  <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assests/css/bootstrap.css">
  <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assests/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assests/css/bootstrap-theme.css">
  <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assests/css/bootstrap-theme.min.css">

  <img src="<?php echo base_url();?>assests/images/atop logo.png">

    To ,
    <address>
      <?php echo $customer_name;?>

<?php echo $address;?>

Phone: <?php echo $mobile;?>

Tin No.:<?php echo $tin;?>
    </address>

    Invoice : <?php echo $bil_no;?>

    Date : <?php echo date('d-m-Y', strtotime($date));?>

            Date
            DC. No.
            Description
            Size
            Set
            Color
            Plate
            Rate
            Amount

          <?php foreach($total as $object)
          { ?>

            <?php echo date('d-m-Y', strtotime($object['adate']));?>
            <?php echo $object['id'];?>
            <?php echo $object['details'];?>
            <?php echo $object['plate_size'];?>
            <?php echo $object['plate_set'];?>
            <?php echo $object['color'];?>
            <?php echo $object['quantity'];?>
            <?php echo $object['rate'];?>
            <?php echo $object['amount'];?>

          <?php } ?>

                Grass Total
                <?php echo $total[0]['sum'];?>

                Vat (4%)
                <?php echo $total[0]['vat'];?>

                Tax (1%)
                <?php echo $total[0]['tax'];?>

                Total:
                <?php echo $total[0]['total_amount'];?>

Rules

1. Payment should be made with in 30 days otherwise.

2. 18% interest will be chenged extra.

3. All taxes will be collected as abd when levide.

4. Subject to Ahmedabad Jurisdiction.

E.&O.E.

For, ATOP

Autho.  Signature

I have tried this code in mozilla and its working properly but not in chrome.

A: I have used page-break-inside: avoid; successfully in the past. I would recommend you trying it.

A: In @media print block add few next rules
tr, th, td{
    page-break-inside:avoid !important;
    page-break-after:auto;
}


text:
Q: SBT imports empty JavaFX-base jar I have switched to OpenJDK 11 and for some reason it doesn't include JavaFX, so I have to use it as a dependency now. However, SBT imports an empty jar.

Just curios why it may happen and how to fix?

A: In order to get proper jar you need to add OS classifier. For instance: "org.openjfx" % "javafx-base" % "12-ea+4" classifier "linux". Or you can follow the example: https://www.reddit.com/r/scala/comments/9fbzbk/build_file_snippet_for_using_javafx_with_java_11/


text:
Q: Can you put i3 on an alternate GUI terminal? Is there a way to put another GUI type, such as i3, on one of the other GUI terminals (i.e. Ctrl + Alt F7-F12)?

A: Yes, but you have to run another x server.
As I recall, you can't do this with the standard login managers (lightdm, gdm), because they're designed on the assumption that only once instance of them will be running. However, I've done it with wdm, although it's a bit clunky.
You probably want to look into running your second server manually via startx.


text:
Q: How can I melt multiple columns in R I have this data called my.data. I want to melt all columns together and get the result in three columns. The final data should have three columns-
1. key.related column
2. IBS values from all three columns (IBS_2_samples IBS_4_samples IBS_8_samples)
3. Column indicating IBS columns types (i.e, column values should be IBS_2_samples IBS_4_samples IBS_8_samples accordingly).

Please teach me how to melt this data so I can make line plot with it (as shown here:Plot multiple lines (data series) each with unique color in R). Thanks
my.data<- structure(list(key.related = c("G11F:G11F", "G11M:G11M", "G29P:G29P",
"G29P:G29S"), IBS_2_samples = c(0.533, 0.629, NA, NA), IBS_4_samples = c(1.01,
1.04, 0.83, 0.349), IBS_8_samples = c(1.11, 1.11, 0.956, 0.42
)), .Names = c("key.related", "IBS_2_samples", "IBS_4_samples",
"IBS_8_samples"), row.names = c(NA, 4L), class = "data.frame")

A: You can convert your data in long format using data.table::melt as:
library(data.table)

melt(setDT(my.data),id.vars = "key.related")

#    key.related      variable value
# 1:   G11F:G11F IBS_2_samples 0.533
# 2:   G11M:G11M IBS_2_samples 0.629
# 3:   G29P:G29P IBS_2_samples    NA
# 4:   G29P:G29S IBS_2_samples    NA
# 5:   G11F:G11F IBS_4_samples 1.010
# 6:   G11M:G11M IBS_4_samples 1.040
# 7:   G29P:G29P IBS_4_samples 0.830
# 8:   G29P:G29S IBS_4_samples 0.349
# 9:   G11F:G11F IBS_8_samples 1.110
# 10:   G11M:G11M IBS_8_samples 1.110
# 11:   G29P:G29P IBS_8_samples 0.956
# 12:   G29P:G29S IBS_8_samples 0.420


text:
Q: TensorFlow 2.0 Keras: How to write image summaries for TensorBoard I'm trying to setup an image recognition CNN with TensorFlow 2.0. To be able to analyze my image augmentation I'd like to see the images I feed into the network in tensorboard.
Unfortunately, I cannot figure out, how to do this with TensorFlow 2.0 and Keras. I also didn't really find documentation on this.
For simplicity, I'm showing the code of an MNIST example. How would I add the image summary here?
import tensorflow as tf
(x_train, y_train), _ = tf.keras.datasets.mnist.load_data()

def scale(image, label):
    return tf.cast(image, tf.float32) / 255.0, label

def augment(image, label):
    return image, label  # do nothing atm

dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
dataset = dataset.map(scale).map(augment).batch(32)

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(dataset, epochs=5, callbacks=[tf.keras.callbacks.TensorBoard(log_dir='D:\\tmp\\test')])

A: Except providing an answer to your question
I will make the code more TF2.0-like. If you have any questions/need clarification, please post a comment down below.
1. Loading data
I would advise to use Tensorflow Datasets library. There is absolutely no need to load data in numpy and transform it to tf.data.Dataset if one can do it in a single line:
import tensorflow_datasets as tfds

dataset = tfds.load("mnist", as_supervised=True, split=tfds.Split.TRAIN)

Line above will only return TRAIN split (read more about those here).
2. Define Augmentations and Summaries
In order to save images, one has to keep tf.summary.SummaryWriter object throughout each pass.
I have created a convenient wrapping class with __call__ method for easy usage with tf.data.Dataset's map capabilities:
import tensorflow as tf

class ExampleAugmentation:
    def __init__(self, logdir: str, max_images: int, name: str):
        self.file_writer = tf.summary.create_file_writer(logdir)
        self.max_images: int = max_images
        self.name: str = name
        self._counter: int = 0

    def __call__(self, image, label):
        augmented_image = tf.image.random_flip_left_right(
            tf.image.random_flip_up_down(image)
        )
        with self.file_writer.as_default():
            tf.summary.image(
                self.name,
                augmented_image,
                step=self._counter,
                max_outputs=self.max_images,
            )

        self._counter += 1
        return augmented_image, label

name will be the name under which each part of images will be saved. Which part you may ask - the part defined by max_outputs.
Say image in __call__ will have shape (32, 28, 28, 1), where the first dimension is batch, second width, third height and last channels (in case of MNIST only onel but this dimension is needed in tf.image augmentations). Furthermore, let's say max_outputs is specified as 4. In this case, only 4 first images from batch will be saved. Default value is 3, so you may set it as BATCH_SIZE to save every image.
In Tensorboard, each image will be a separate sample over which you can iterate at the end.
_counter is needed so the images will not be overwritten (I think, not really sure, clarification from someone else would be nice).
Important: You may want to rename this class to something like ImageSaver when doing more serious buisness and move augmentation to separate functors/lambda functions. It suffices for presentation purposes I guess.
3. Setup global variables
Please do not mix function declaration, global variables, data loading and others (like loading data and creating function afterwards). I know TF1.0 encouraged this type of programming but they are trying to get away from it and you might want to follow the trend.
Below I have defined some global variables which will be used throughout next parts, pretty self-explanatory I guess:
BATCH_SIZE = 32
DATASET_SIZE = 60000
EPOCHS = 5

LOG_DIR = "/logs/images"
AUGMENTATION = ExampleAugmentation(LOG_DIR, max_images=4, name="Images")

4. Dataset augmentation
Similar to yours but with a little twist:
dataset = (
    dataset.map(
        lambda image, label: (
            tf.image.convert_image_dtype(image, dtype=tf.float32),
            label,
        )
    )
    .batch(BATCH_SIZE)
    .map(AUGMENTATION)
    .repeat(EPOCHS)
)

*

*repeat is needed as the loaded dataset is a generator

*tf.image.convert_image_dtype - better and more readable option than explicit tf.cast mixed with division by 255 (and ensures proper image format)

*batching done before augmentation just for the sake of presentation

5. Define model, compile, train
Almost as you did in your example, but I have provided additional steps_per_epoch, so fit knows how many batches constitute an epoch:
model = tf.keras.models.Sequential(
    [
        tf.keras.layers.Flatten(input_shape=(28, 28, 1)),
        tf.keras.layers.Dense(128, activation="relu"),
        tf.keras.layers.Dropout(0.2),
        tf.keras.layers.Dense(10, activation="softmax"),
    ]
)

model.compile(
    optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]
)
model.fit(
    dataset,
    epochs=EPOCHS,
    steps_per_epoch=DATASET_SIZE // BATCH_SIZE,
    callbacks=[tf.keras.callbacks.TensorBoard(log_dir=LOG_DIR)],
)

Not much to explain other than that I think.
6. Run Tensorboard
Since TF2.0 one can do it inside colab using %tensorboard --logdir /logs/images, just wanted to add this for others who may visit this issue. Do it however you like, anyways you know how to do it for sure.
Images should be inside IMAGES and each sample named by name provided to AUGMENTATION object.
7. Whole code (to make everyone's life easier)
import tensorflow as tf
import tensorflow_datasets as tfds

class ExampleAugmentation:
    def __init__(self, logdir: str, max_images: int, name: str):
        self.file_writer = tf.summary.create_file_writer(logdir)
        self.max_images: int = max_images
        self.name: str = name
        self._counter: int = 0

    def __call__(self, image, label):
        augmented_image = tf.image.random_flip_left_right(
            tf.image.random_flip_up_down(image)
        )
        with self.file_writer.as_default():
            tf.summary.image(
                self.name,
                augmented_image,
                step=self._counter,
                max_outputs=self.max_images,
            )

        self._counter += 1
        return augmented_image, label

if __name__ == "__main__":

    # Global settings

    BATCH_SIZE = 32
    DATASET_SIZE = 60000
    EPOCHS = 5

    LOG_DIR = "/logs/images"
    AUGMENTATION = ExampleAugmentation(LOG_DIR, max_images=4, name="Images")

    # Dataset

    dataset = tfds.load("mnist", as_supervised=True, split=tfds.Split.TRAIN)

    dataset = (
        dataset.map(
            lambda image, label: (
                tf.image.convert_image_dtype(image, dtype=tf.float32),
                label,
            )
        )
        .batch(BATCH_SIZE)
        .map(AUGMENTATION)
        .repeat(EPOCHS)
    )

    # Model and training

    model = tf.keras.models.Sequential(
        [
            tf.keras.layers.Flatten(input_shape=(28, 28, 1)),
            tf.keras.layers.Dense(128, activation="relu"),
            tf.keras.layers.Dropout(0.2),
            tf.keras.layers.Dense(10, activation="softmax"),
        ]
    )

    model.compile(
        optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]
    )
    model.fit(
        dataset,
        epochs=EPOCHS,
        steps_per_epoch=DATASET_SIZE // BATCH_SIZE,
        callbacks=[tf.keras.callbacks.TensorBoard(log_dir=LOG_DIR)],
    )

A: You could do something like this to add input image to tensorboard
def scale(image, label):
    return tf.cast(image, tf.float32) / 255.0, label

def augment(image, label):
    return image, label  # do nothing atm

file_writer = tf.summary.create_file_writer(logdir + "/images")

def plot_to_image(figure):
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    plt.close(figure)
    buf.seek(0)
    image = tf.image.decode_png(buf.getvalue(), channels=4)
    image = tf.expand_dims(image, 0)
    return image

def image_grid():
    """Return a 5x5 grid of the MNIST images as a matplotlib figure."""
    # Create a figure to contain the plot.
    figure = plt.figure(figsize=(10, 10))
    for i in range(25):
        # Start next subplot.
        plt.subplot(5, 5, i + 1, title=str(y_train[i]))
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
        image, _ = scale(x_train[i], y_train[i])
        plt.imshow(x_train[i], cmap=plt.cm.binary)

    return figure

# Prepare the plot
figure = image_grid()
# Convert to image and log
with file_writer.as_default():
    tf.summary.image("Training data", plot_to_image(figure), step=0)

dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
dataset = dataset.map(scale).map(augment).batch(32)

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

model.fit(dataset, epochs=5, callbacks=[tf.keras.callbacks.TensorBoard(log_dir=logdir)])


text:
Q: Disable stylesheet based on referrer I don't want to allow the stylesheet (hosted with me) to be loaded on a couple of domains.
This is what I'm trying, but doesn't work:
RewriteEngine on

RewriteCond %{HTTP_REFERER} ^http://example1.com/ [NC]
RewriteRule \.css$ http://www.mywebsite.com/dummy.css [R,L]

RewriteCond %{HTTP_REFERER} ^http://example2.com/ [NC]
RewriteRule \.css$ http://www.mywebsite.com/dummy.css [R,L]

How can I make it work?

A: css/.htaccess
Options +FollowSymLinks
RewriteEngine On

# Redirect requests to load.php
RewriteCond %{REQUEST_URI} .*\.css$ [NC]
RewriteRule .* load.php

css/load.php
$referrer = $_SERVER['HTTP_REFERER'];

if (strpos($referrer, 'allowedwebsite1.com') !== false or
    strpos($referrer, 'allowedwebsite2.com') !== false ) {

    header("Content-type: text/css", true);
    $css = file_get_contents("style.css");
    echo $css;
}
else {
    header("Content-type: text/css", true);
    echo ''; // empty stylesheet
}


text:
Q: Changing obj code section I am trying to change the code section after compiling but before linking (after obj is created but before it is linked to an exe).
I am able to locate the code section and add any number of NOPs to its end and the exe works fine; however, if I add a NOP to the beginning or middle of the section, the exe crashes.
I did update all the sections headers (pointer to data & pointer to relocations) according to the change size (delta), but I'm probably missing something else I need to fix. Since it works when I append to the end, it feels like an in-section-offset problem.


text:
Q: find entries to the left and right of a certain entry in a mysql table in a single query Let's say I have a table in a database like this table. Let's say that I want to get the entries on the left and right of the entry whose the primary key is equal to 5 (or any other primary key). So in our case, I want to get the entries whose primary key is equal to 4 and 6 respectively. What is the SQL query that will give me such result? Can you guys translate the SQL query into a find('all') CakePHP query?
Thank you
NOTE: The ids are not necessarily contiguous, meaning, they do not necessarily follow the 1, 2, 3, 4, 5, 6, 7, 8 sequence. I can have something like 1, 5, 13, 44, 66, 123, etc

A: Try Union like this
 (SELECT * FROM employee WHERE id < 5 order by id DESC LIMIT 1)
 UNION
 (SELECT * FROM employee WHERE id >5  LIMIT 1)

A: PHP
$id = 5;
SELECT * FROM Employee where id = $id-1 OR id = $id+1;

MySQL
SET @id = 5;
SELECT * FROM Employee where id = @id-1 OR id = @id+1;

A: Checkout find('neighbors'). It returns the records before and after the one you specify and your ids can have "holes" in the sequence.


text:
Q: How to show tooltip after copying using zero-clipboard? I am trying to emulate the behavior seen on github and the bootstrap site, where the the tooltip on the zero-clipboard button changes after copying from something like "Copy to Clipboard" to "Copied".  Both sites seem to use an element called data-copied-hint to do this, but it does not work for me.  I have also tried modifying the title element after copying using jquery, but that only changes the tooltip the next time you hover over - the tooltip is still not shown right after the click.  Any ideas what I need to do?
Here is my code (also on Plunker at http://plnkr.co/edit/HTXl8Yjz3Wp9iOL5LKr7)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/zeroclipboard/2.1.6/ZeroClipboard.js"></script>

    <button id="myclippy" data-clipboard-text="hello world" title="click to copy" data-copied-hint="you copied the text">hello</button>
    <input type="text" />

    <script type="text/javascript">
        var button = document.getElementById("myclippy");
        var client = new ZeroClipboard(button);
    </script>
</body>
</html>

A: Unfortunately Samuel's method didn't quite work as I wanted.  After a bit more searching I found this gist: https://gist.github.com/subchen/4d07dda61f88dcd9320a
Using the global-zeroclipboard-html-bridge worked for me
eg./
//...
var $bridge = $("#global-zeroclipboard-html-bridge");

client.on("ready", function(e) {
  $bridge.data("placement", "left").attr("title", "Copy to clipboard").tooltip();
  });

client.on("aftercopy", function(e) {
  $bridge.attr("title", "Copied!").tooltip("fixTitle").tooltip("show").attr("title", "Copy to clipboard").tooltip("fixTitle");
    });
//...

A: the simplest solution is to change the 'generated' tooltip text into something else during the aftercopy event.
//...
client.on('aftercopy', function(event) {
      $('.tooltip .tooltip-inner').text('Copied!');
    });
//...

see the updated Plunk (bootstrap CSS and JS is included to work with their simple tooltips) and get inspired
note: if the tooltip text (before and after click) length differs, the bottom/top tooltip in this example gets shifted a bit. either use left/right tooltip positions or displaying a new tooltip might work


text:
Q: Do my web pages need to be in HTML5 to use the Data Highlighter or Schema.org Microdata? Do my web pages need to be written in HTML5 to use the Data Highlighter?  Do my web pages need to be written in HTML5 to use the Schema.org Microdata?

A: Not sure about the Data Highlighter, but yes, in order to use Microdata (whether with schema.org or any other vocabulary) you need to use HTML5. Microdata was originally part of HTML5 (it was removed from the spec some time ago, and now exists separately, but is still only valid in HTML5).
However you can still use schema.org in non-HTML5 web pages by embedding it using RDFa or JSON-LD instead of Microdata. And obviously you can also use RDFa and JSON-LD in HTML5 web pages as well.


text:
Q: Function pointer IAR ( typedef void ) I am working on STM8S with IAR Workbench.
My code
typedef     void    (*MyFunction)();

and I got these errors:

Error[Pe513]: a value of type "void (*)(u8)" cannot be assigned to an
  entity of type "MyFunction"

I search on the web and I find a sample for AVR that I show below:
typedef void (*MyFunction)(void);

It also doesn't work.
Any idea for fix it.

A: For pointers to be assignable they need to point to compatible types (and the type pointed to by the left-hand side needs to have all the qualifiers of the type pointed to by the right-hand side). See 6.5.16.1p1.
Assuming u8 is uint8_t AKA unsigned char, void () is NOT compatible with void (u8).
6.7.6.3p15 (with emphasis):

For two function types to be compatible, both shall specify compatible
  return types.146) Moreover, the parameter type lists, if both are
  present, shall agree in the number of parameters and in use of the
  ellipsis terminator; corresponding parameters shall have compatible
  types. If one type has a parameter type list and the other type is
  specified by a function declarator that is not part of a function
  definition and that contains an empty identifier list, the parameter
  list shall not have an ellipsis terminator and the type of each
  parameter shall be compatible with the type that results from the
  application of the default argument promotions. If one type has a
  parameter type list and the other type is specified by a function
  definition that contains a (possibly empty) identifier list, both
  shall agree in the number of parameters, and the type of each
  prototype parameter shall be compatible with the type that results
  from the application of the default argument promotions to the type of
  the corresponding identifier. (In the determination of type
  compatibility and of a composite type, each parameter declared with
  function or array type is taken as having the adjusted type and each
  parameter declared with qualified type is taken as having the
  unqualified version of its declared type.)

The incompatibility is because of the promotions part. Character types get promoted to int so while you could do:
(void(*)()){0}=(void(*)(int)){0};
(void(*)(int)){0}=(void(*)()){0};

doing the same with u8 / unsigned char is not permissible:
(void(*)()){0}=(void(*)(unsigned char)){0}; //error
(void(*)(unsigned char)){0}=(void(*)()){0}; //error

You need to make the typedef be exactly to void (*)(u8) or you need to change the target function's signature to void (int)  (or void (unsigned)) or you need to cast the function pointer. (Note that function pointers are freely inter-castable but you need to cast to the proper type before calling the function).


text:
Q: Criar colunas de checkboxes dinamicamente com angular Estou tentando criar dinamicamente colunas de checkboxes em um dropdown, usando angular. Utilizo bootstrap. Cada item do checkbox pode ou não ter filhos relacionados.
A solução que encontrei foi colocar tudo dentro de uma div (.col-sm-4, pelo sistema de grids do bootstrap, mas os itens não ficaram bem alinahdos).
Segue o código e o resultado que dessa ação: (coloquei a borda em vermelho para facilitar a orientação)

    Tipo peca

                <input type="checkbox" ng-click="vm.selectAll($event)" />

                    {{result.nome}}
                    {{result.total}}

                        <input type="checkbox" ng-click="vm.selectAll($event)" />

                            {{peca.nome}}
                            {{peca.total}}

Resultado:

Como poderia contornar esse problema?


text:
Q: Getting a managed metada field to use in sharepoint 2013 workflow condition I'm working on a SharePoint 2013 publishing approval workflow that needs to compare if a managed metadata field in a newly created item is set to a specific value. This in order to assign a task to a sharepoint group if the condition is true. I'm having difficulties in finding the value of the MMD field. I've tried to do it in the Term|GUID-way(Term|xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx). But I don't get any values at all.
If anyone has some pointers or advice on this issue, it would be great!
Thanks, Joakim

A: Here is a snippet that I have used to set the values in a TaxonomyField in SharePoint 2010.
However the object model hasn't changed too much in this area:-
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.taxonomyfieldvalue_members.aspx
This code is expecting an SPListItem object to be passed through.
string labelValue = String.Empty;
TaxonomyField field = item.Fields.GetField(fieldName) as TaxonomyField;
string fieldValue = item[field.Id].ToString();

TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(field);
string fieldValue = item[field.Id].ToString();
if (fieldValue.Contains("|"))
{
  taxonomyFieldValue.PopulateFromLabelGuidPair(fieldValue);
}

labelValue = taxonomyFieldValue.Label;

You can now compare the value inside labelValue with the value you need to check.


text:
Q: ORACLE SQL: add time to a timestamp with timezone I need to add seconds and substract variables with type TIMESTAMP WITH TIMEZONE, however, to my understanding, adding numbers to such data causes the information about the timezone to be lost, perhaps because it's converted to a DATE type
That is:
  SELECT FROM_TZ(
           TO_TIMESTAMP(
             TO_DATE('03/09/2012 2:30:30','DD/MM/YYYY HH:MI:SS')
           )
         , 'America/Chicago')
      FROM DUAL;

Gives:
 03/09/2012 00:00:00, -05:00

Then
  SELECT FROM_TZ(
           TO_TIMESTAMP(
             TO_DATE('03/09/2012 2:30:30','DD/MM/YYYY HH:MI:SS')
           )
         , 'America/Chicago')  + 1/24 -- add 1 hour
      FROM DUAL;

Gives
 03/09/2012 01:00:00

and loses the timezone information.
But
 SELECT FROM_TZ(
     TO_TIMESTAMP(
       TO_DATE('03/09/2012 2:30:30','DD/MM/YYYY HH:MI:SS'))
      , 'America/Chicago') +  INTERVAL '1' hour

  FROM DUAL;

Correctly gives
 03/09/2012 01:00:00,000000000 -05:00

However the INTERVAL.. syntax expect a char constant, so I can't use that with variables.
How can I perform that kind of arithmetic with TIMESTAMP WITH TIME ZONE datatype while retaining timezone information?
TIA

A: You can use the NUMTODSINTERVAL function to convert a number to an interval.
SELECT FROM_TZ( TIMESTAMP '2012-10-08 00:00:00','-5:00')
  + NUMTODSINTERVAL(1,'HOUR')
FROM dual;


text:
Q: Handling Password Authentication over a Network I'm writing a game which requires users to log in to their accounts in order to be able to play. What's the best way of transmitting passwords from client to server and storing them?
I'm using Python and Twisted, if that's of any relevance.

A: The best way is to authenticate via SSL/TLS. The best way of storing passwords is to store them hashed with some complex hash like sha1(sha1(password)+salt) with salt.

A: If you want plug'n'play solution, use py-bcrypt for storing passwords (http://www.mindrot.org/projects/py-bcrypt/) and SSL/TLS to protect them in transit.


text:
Q: An asynchronous operation exceeded the page timeout (trying to use HttpRequestMessage with ASP.NET WebForms page) I have created a web API in AWS that I am trying to get some JSON back from using a web page built in ASP.NET Webforms (most up-to-date version). I can't get the asynchronous part to work. Either the GET method hangs seemingly forever, or - following the best practice approach from the Microsoft documentation - I get this error after a little while:

[TimeoutException: An asynchronous operation exceeded the page
  timeout.]    System.Web.UI.d__554.MoveNext() +984

I know this is something to do with the wait/async portion of the code and being in ASP.NET because of the following.

*

*If I use very similar code in a console application it works fine.

*If i call the web API using POSTMAN it works fine.

I have made async = true in the page directive. Here is my page load
protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        RegisterAsyncTask(new PageAsyncTask(GetStuffAsync));
    }
    catch (Exception ex)
    {
        renderStoreCards.Text = ex.Message;
    }
}

Here is my method
    private async Task GetStuffAsync()
    {
        string testHtml = string.Empty;

        try
        {
            var signer = new AWS4RequestSigner("AccessKey", "SecretKey");
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri("https://some-aws-address-changed-for-stack-overflow.execute-api.ap-southeast-2.amazonaws.com/Prod/tables/InSiteStoreInformation/ServerName")
            };

            request = await signer.Sign(request, "execute-api", "ap-southeast-2");
            var client = new HttpClient();
            var response = await client.SendAsync(request).ConfigureAwait(false);
            string responseString = await response.Content.ReadAsStringAsync();
        }
        catch (Exception ex)
        {
            renderStoreCards.Text = ex.Message;
        }
    }

The above example produces a TimeoutException. Previous to the above, I was trying the following code. This works fine in a console app, but not in the ASP.NET page.
  class Program
    {
        static void Main(string[] args)
        {
            try
            {
                MainAsync().Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception occured {ex.Message}");
                Console.ReadKey();
            }
        }

        static async Task MainAsync()
        {
            try
            {
                var signer = new AWS4RequestSigner("AccessKey", "SecretKey");
                var request = new HttpRequestMessage
                {
                    Method = HttpMethod.Get,
                    RequestUri = new Uri("https://<Hiddenforstackoverflowpost>.execute-api.ap-southeast-2.amazonaws.com/Prod/tables/InSiteStoreInformation/ServerName")
                };

                request = await signer.Sign(request, "execute-api", "ap-southeast-2");

                var client = new HttpClient();
                var response = await client.SendAsync(request);

                var responseStr = await response.Content.ReadAsStringAsync();
                dynamic sales = Newtonsoft.Json.JsonConvert.DeserializeObject(responseStr);
                Console.WriteLine($"Server = {sales[0].ServerName}");
                Console.ReadKey();
                Console.Write(responseStr);
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
    }

I am by no means an expert in async/wait combinations, but it appears that the HttpClient I'm using has no synchronous alternative, so I have to figure this out.

A: I know this is an old question, but I just came across.
The timeouts are most likely caused by ReadAsStringAsync as you neglected to use '.ConfigureAwait(false)' on it. Running async tasks inside ASP.net can be very finicky especially around execution contexts. It most likely is some kind of dead-lock on the async method when it tries to restore the execution context on its return. This usually fails due to the nature of IIS hosting. I am not sure if it actually is a dead-lock or some other issue under the hood. Just make sure to always use .ConfigureAwait(false).
I know this is old, but maybe it helps someone else coming across this issue.


text:
Q: History API & URL for single long page I'm working on a NON-API Wordpress site. One of the pages is a long page segmented into several sections. At the top of the page is a menu for most of the sections on the page.
When a user lands on the page, the URL will read mysite.com/about
As the user scrolls down the page, the URL updates to show the current section: mysite.com/about -> mysite.com/about/team -> mysite.com/about/awards
Inbound traffic to the page will parse the URL and scroll to the appropriate section. mysite.com/about/team will scroll to the "team" section.
All the content on the site is visible and available when the page loads, the menu only scrolls to the appropriate section. In other frameworks, this can be trivial with the History API. In WP, I've tried using the following but still get a 404
function wpd_foo_rewrite_rule() {
    add_rewrite_rule(
        '^/about/([^/]*)/?',
        'index.php?pagename=about',
        'top'
    );
}
add_action( 'init', 'wpd_foo_rewrite_rule' );


text:
Q: UserControl binding from WPF User Control Library doesn't work with ContentControl Why is binding for a Caliburn.Micro UserControl enclosed to WPF User Control Library not working with ContentControl?

Initial
Create new Wpf App v4.6.2

*

*Install Nuget Caliburn.Micro v3.1.0

*Install Nuget Caliburn.Micro.Start v3.1.0

*Do adaptions like explained http://caliburnmicro.com/documentation/nuget

*

*adapt app.xaml

*delete StartupUri

*add ResourceDictionary

*check   AppBootstrapper

*delete MainWindow.xaml

*Add Button x:Name="DoIt" to ShellView.xaml

*Add public void DoIt() with MessageBox.Show() to ShellViewModel.cs

*Test this initial version

✓ Check! This runs and binding works...

UserControl View

*

*Add UserControl and name it e.g. TestUcView

*Add a Textbox and give a name e.g. UcValue

<UserControl x:Class="WpfApp1.Test2UcView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:WpfApp1"
             mc:Ignorable="d"
             d:DesignHeight="50" d:DesignWidth="200" Visibility="{Binding UcVisibility}">
    <Grid >
        <TextBox x:Name="UcValue" HorizontalAlignment="Left" Height="23" Margin="10,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="100"/>
        <Button x:Name="UcAction" Content="Do specific" HorizontalAlignment="Left" Margin="120,10,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>
</UserControl>

UserControl ViewModel

*

*Add class with corresponding name TestUcViewModel

*Change class to public and derive from screen and add using Caliburn.Micro

*Add property with corresponding name to TextBox e.g. UcValue

public class Test1UcViewModel : Screen
{
    private string _UcValue;
    public string UcValue { get => _UcValue; set { _UcValue = value; NotifyOfPropertyChange(() => UcValue); } }

    public void TestBut2() {
        MessageBox.Show("TestBut2");
    }
}

UserControl Integration

*

*In ShellViewModel create public property for the ViewModel and create an instance in the constructor

*Create control in View to be bound

*

*Possibility: Place ContentControl in the ShellView.xaml with the same Name as the ViewModel property (ViewModel first)

*Possibility: Compile and place the UserControl into the ShellView.xaml and add cal:Bind.Model="{Binding <ViewModel-Property-Name>}" for this the namespace

✓ Check! This runs and binding of UserControl works...

BUT,
...now with integrating the third UserControl that belongs to a WPF User Control Library (dll), the Caliburn binding doesn't work for the UserControl from the dll when using the syntax for ContentControl.
public class ShellViewModel : Caliburn.Micro.PropertyChangedBase, IShell
{
    private Test1UcViewModel _Test1UserControlModel;
    private Test2UcViewModel _Test2UserControlModel;
    private Test3UcViewModel _Test3UserControlModel;

    public Test1UcViewModel Test1 { get => _Test1UserControlModel; set { _Test1UserControlModel = value; NotifyOfPropertyChange(() => Test1); } }
    public Test2UcViewModel Test2 { get => _Test2UserControlModel; set { _Test2UserControlModel = value; NotifyOfPropertyChange(() => Test2); } }
    public Test3UcViewModel Test3 { get => _Test3UserControlModel; set { _Test3UserControlModel = value;NotifyOfPropertyChange(() => Test3); } }

    public ShellViewModel()
    {
        _Test1UserControlModel = new Test1UcViewModel();
        Test1.UcValue = "Bubble";
        _Test2UserControlModel = new Test2UcViewModel();
        Test2.UcValue = "Simmer";
        _Test3UserControlModel = new Test3UcViewModel();
        Test3.Uc3Value = "Knocking on heavens door";
        Test1.UcVisibility = Visibility.Visible;
        Test2.UcVisibility = Visibility.Hidden;
        Test3.UcVisibility = Visibility.Hidden;
    }

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:cal="http://www.caliburnproject.org"
        xmlns:local="clr-namespace:WpfApp1"
        xmlns:TestUcLib="clr-namespace:TestUcLib;assembly=TestUcLib"
        x:Class="WpfApp1.ShellView" Width="500" Height="300">

    <Grid Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <TextBlock Text="Input"
                   TextWrapping="Wrap"
                   VerticalAlignment="Bottom"
                   HorizontalAlignment="Center"
                   FontSize="20" />
        <StackPanel>
            <Button x:Name="DoIt1" Content="Do it 1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="5"/>
            <Button x:Name="DoIt2" Content="Do it 2" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="5"/>
            <Button x:Name="DoIt3" Content="Do it 3" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="5"/>
        </StackPanel>

        <ContentControl x:Name="Test1" Grid.Column="1"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
        <ContentControl x:Name="Test2" Grid.Column="1"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
        <ContentControl x:Name="Test3" Grid.Column="1"  HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
        <!--This one works-->
        <!--<TestUcLib:Test3UcView cal:Bind.Model="{Binding Test3}" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>-->
    </Grid>

</Window>

Is it mandatory to use <TestUcLib:Test3UcView cal:Bind.Model="{Binding Test3}" instead of using ContentControl when the UserControl is inside dll?

A: Caliburn.Micro uses a simple naming pattern to find the UserControl that it should bind to the view model and display and it only searches any assembly you have exposed as searchable via AssemblySource.Instance: http://caliburnmicro.com/documentation/conventions.
You could override this logic by setting the ViewLocator.LocateForModelType property and implement your own. The following basic example should give you the idea:
public class HelloBootstrapper : BootstrapperBase
{
    public HelloBootstrapper()
    {
        Initialize();
    }

    ...

    static Func<Type, DependencyObject, object, UIElement> _func;
    protected override void Configure()
    {
        var assembly = System.Reflection.Assembly.Load("WpfCustomControlLibrary1"); //<-- this is your assembly
        AssemblySource.Instance.Add(assembly);

        _func = ViewLocator.LocateForModelType;
        ViewLocator.LocateForModelType = LocateForModelType;
        ...
    }

    private static Func<Type, DependencyObject, object, UIElement> LocateForModelType = (modelType, displayLocation, context) => {

        //use the default method first:
        UIElement view = _func(modelType, displayLocation, context);
        if (!(view is TextBlock))
            return view;

        var viewTypeName = modelType.Name.Replace("Model", string.Empty);
        var viewType = (from assmebly in AssemblySource.Instance
                        from type in assmebly.GetExportedTypes()
                        where type.Name == viewTypeName
                        select type).FirstOrDefault();

        return viewType == null ? new TextBlock { Text = string.Format("{0} not found.", viewTypeName) }
            : Activator.CreateInstance(viewType) as UIElement;
    };
}


text:
Q: How I can check whether a page is loaded completely or not in web driver? I am writing some Java Webdriver code to automate my application. How can I correctly check whether the page has been loaded or not? The application has some Ajax calls, too.
I have declared an implicit wait for WebDriver.

A: Simple ready2use snippet, working perfectly for me
static void waitForPageLoad(WebDriver wdriver) {
    WebDriverWait wait = new WebDriverWait(wdriver, 60);

    Predicate<WebDriver> pageLoaded = new Predicate<WebDriver>() {

        @Override
        public boolean apply(WebDriver input) {
            return ((JavascriptExecutor) input).executeScript("return document.readyState").equals("complete");
        }

    };
    wait.until(pageLoaded);
}

A: Selenium does it for you. Or at least it tries its best. Sometimes it falls short, and you must help it a little bit. The usual solution is Implicit Wait which solves most of the problems.
If you really know what you're doing, and why you're doing it, you could try to write a generic method which would check whether the page is completely loaded. However, it can't be done for every web and for every situation.

Related question: Selenium WebDriver : Wait for complex page with JavaScript(JS) to load, see my answer there.
Shorter version: You'll never be sure.
The "normal" load is easy - document.readyState. This one is implemented by Selenium, of course. The problematic thing are asynchronous requests, AJAX, because you can never tell whether it's done for good or not. Most of today's webpages have scripts that run forever and poll the server all the time.
The various things you could do are under the link above. Or, like 95% of other people, use Implicit Wait implicity and Explicit Wait + ExpectedConditions where needed.
E.g. after a click, some element on the page should become visible and you need to wait for it:
WebDriverWait wait = new WebDriverWait(driver, 10);  // you can reuse this one

WebElement elem = driver.findElement(By.id("myInvisibleElement"));
elem.click();
wait.until(ExpectedConditions.visibilityOf(elem));

A: You can set a JavaScript variable in your WepPage that gets set once it's been loaded. You could put it anywhere, but if you're using jQuery, $(document).onReady isn't a bad place to start. If not, then you can put it in a

And in your test (C# example):
// The timespan determines how long to wait for any 'condition' to return a value
// If it is exceeded an exception is thrown.
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5.0));

// Set the 'condition' as an anonymous function returning a boolean
wait.Until<Boolean>(delegate(IWebDriver d)
{
    // Check if our global variable is initialized by running a little JS
    return (Boolean)((IJavaScriptExecutor)d).ExecuteScript("return typeof(window.TestReady) !== 'undefined' && window.TestReady === true");
});

A: I know this post is old. But after gathering all code from above I made a nice method (solution) to handle ajax running and regular pages. The code is made for C# only (since Selenium is definitely a best fit for C# Visual Studio after a year of messing around).
The method is used as an extension method, which means to put it simple; that you can add more functionality (methods) in this case, to the object IWebDriver. Important is that you have to define: 'this' in the parameters to make use of it.
The timeout variable is the amount of seconds for the webdriver to wait, if the page is not responding. Using 'Selenium' and 'Selenium.Support.UI' namespaces it is possible to execute a piece of javascript that returns a boolean, whether the document is ready (complete) and if jQuery is loaded. If the page does not have jQuery then the method will throw an exception. This exception is 'catched' by error handling. In the catch state the document will only be checked for it's ready state, without checking for jQuery.
public static void WaitUntilDocumentIsReady(this IWebDriver driver, int timeoutInSeconds) {
    var javaScriptExecutor = driver as IJavaScriptExecutor;
    var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));

    try {
        Func<IWebDriver, bool> readyCondition = webDriver => (bool)javaScriptExecutor.ExecuteScript("return (document.readyState == 'complete' && jQuery.active == 0)");
        wait.Until(readyCondition);
    } catch(InvalidOperationException) {
        wait.Until(wd => javaScriptExecutor.ExecuteScript("return document.readyState").ToString() == "complete");
    }
}

A: Recently, when I was dealing with an AJAX application/RIA, I was having the same issue! And I used implicit wait, with a time of around 90 seconds. It waits, till the element is available...So, what we can do to make sure, that page gets loaded completely is,
add a boolean statement, checking for whether the condition(a particular part of the element), is present and assign it to a variable, check for the condition and only when it is true, " do the necessary actions!"...In this way, I figured out, both waits could be used...
Ex:
@Before

{ implicit wait statement}

@Test

{

boolean tr1=Driver.findElement(By.xpath("xx")).isEnabled/isDisplayed;

if (tr1==true && ____)//as many conditions, to make sure, the page is loaded

{

//do the necessary set of actions...
driver.findElement(By.xpath("yy")).click();

}

}

Hope this helps!! It is in implementation stage, for me too...

A: Here is how I would fix it, using a code snippet to give you a basic idea:
public class IFrame1 extends LoadableComponent<IFrame1> {

    private RemoteWebDriver driver;

    @FindBy(id = "iFrame1TextFieldTestInputControlID" ) public WebElement iFrame1TextFieldInput;
    @FindBy(id = "iFrame1TextFieldTestProcessButtonID" ) public WebElement copyButton;

    public IFrame1( RemoteWebDriver drv ) {
        super();
        this.driver = drv;
        this.driver.switchTo().defaultContent();
        waitTimer(1, 1000);
        this.driver.switchTo().frame("BodyFrame1");
        LOGGER.info("IFrame1 constructor...");
    }

    @Override
    protected void isLoaded() throws Error {
        LOGGER.info("IFrame1.isLoaded()...");
        PageFactory.initElements( driver, this );
        try {
            assertTrue( "Page visible title is not yet available.",
                    driver.findElementByCssSelector("body form#webDriverUnitiFrame1TestFormID h1")
                    .getText().equals("iFrame1 Test") );
        } catch ( NoSuchElementException e) {
            LOGGER.info("No such element." );
            assertTrue("No such element.", false);
        }
    }

    /**
     * Method: load
     * Overidden method from the LoadableComponent class.
     * @return  void
     * @throws  null
     */
    @Override
    protected void load() {
        LOGGER.info("IFrame1.load()...");
        Wait<WebDriver> wait = new FluentWait<WebDriver>( driver )
                .withTimeout(30, TimeUnit.SECONDS)
                .pollingEvery(5, TimeUnit.SECONDS)
                .ignoring( NoSuchElementException.class )
                .ignoring( StaleElementReferenceException.class ) ;
        wait.until( ExpectedConditions.presenceOfElementLocated(
                By.cssSelector("body form#webDriverUnitiFrame1TestFormID h1") ) );
    }
....

A: Below is some code from my BasePageObject class for waits:
public void waitForPageLoadAndTitleContains(int timeout, String pageTitle) {
    WebDriverWait wait = new WebDriverWait(driver, timeout, 1000);
    wait.until(ExpectedConditions.titleContains(pageTitle));
}

public void waitForElementPresence(By locator, int seconds) {
    WebDriverWait wait = new WebDriverWait(driver, seconds);
    wait.until(ExpectedConditions.presenceOfElementLocated(locator));
}

public void jsWaitForPageToLoad(int timeOutInSeconds) {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    String jsCommand = "return document.readyState";

    // Validate readyState before doing any waits
    if (js.executeScript(jsCommand).toString().equals("complete")) {
        return;
    }

    for (int i = 0; i < timeOutInSeconds; i++) {
        TimeManager.waitInSeconds(3);
        if (js.executeScript(jsCommand).toString().equals("complete")) {
            break;
        }
    }
}

   /**
     * Looks for a visible OR invisible element via the provided locator for up
     * to maxWaitTime. Returns as soon as the element is found.
     *
     * @param byLocator
     * @param maxWaitTime - In seconds
     * @return
     *
     */
    public WebElement findElementThatIsPresent(final By byLocator, int maxWaitTime) {
        if (driver == null) {
            nullDriverNullPointerExeption();
        }
        FluentWait<WebDriver> wait = new FluentWait<>(driver).withTimeout(maxWaitTime, java.util.concurrent.TimeUnit.SECONDS)
                .pollingEvery(200, java.util.concurrent.TimeUnit.MILLISECONDS);

        try {
            return wait.until((WebDriver webDriver) -> {
                List<WebElement> elems = driver.findElements(byLocator);
                if (elems.size() > 0) {
                    return elems.get(0);
                } else {
                    return null;
                }
            });
        } catch (Exception e) {
            return null;
        }
    }

Supporting methods:
     /**
     * Gets locator.
     *
     * @param fieldName
     * @return
     */
    public By getBy(String fieldName) {
        try {
            return new Annotations(this.getClass().getDeclaredField(fieldName)).buildBy();
        } catch (NoSuchFieldException e) {
            return null;
        }
    }

A: You can get the HTML of the website with driver.getPageSource(). If the html does not change in a given interval of time this means that the page is done loading. One or two seconds should be enough. If you want to speed things up you can just compare the lenght of the two htmls. If their lenght is equal the htmls should be equal and that means the page is fully loaded. The JavaScript solution did not work for me.

A: The solution is using Implicit Wait which will solve your problems of page load.
WebDriverWait waitForElement = new WebDriverWait(driver, 15);
WebElement element = driver.findElement(By.id("myElement"));
element.click();
wait.until(ExpectedConditions.visibilityOf(element));

A: You can take a screenshot and save the rendered page in a location and you can check the screenshot if the page loaded completely without broken images


text:
Q: Returning to the next instruction following the one stored in Eip register I have written a assembly function that handles an interrupt. I want to return to the instruction following the one that caused the interrupt. Here is my code,
    pushl   %ebp
    movl    %esp,%ebp
    pushal
    movl    %esp, %eax
    pushl   %eax
    pushl   $0
    call    divzero

    addl    $8, %esp        /* add 8 to the stack pointer to skip the two variables*/
    popal
    popl    %ebp            /* restore %ebp */
    popl    %eax            /* pop return address from stack and store in eax */
    add     $4, %eax    /* add 4 to value of eax to get the address of next instruction */
    jmp     %eax

The platform I am coding on is x86 32 bits. I have written comments from my understanding of how the stack works but I am getting invalid opcode interrupt. Here is the stack trace.
exception 6 (invalid opcode) currpid 3 (Main process)
CS EFC0008 eip 1028D4
eflags 10297
register dump:
eax 001028CC (1059020)
ecx 0EFC8FFC (251432956)
edx 00000000 (0)
ebx 00121000 (1183744)
esp 0EFC8FB8 (251432888)
ebp 0EFC8FB8 (251432888)
esi 00000000 (0)
edi 00000000 (0)

For reference I am adding my main function here:
process main(void)
{

        asm("int $0");
        kprintf("hello\n");
        int i = 4 / 0; <- Casue of interrupt
        kprintf("hello again\n"); -< The place I want to return to.

}

A: This did the trick for me:
    pushl   %ebp
    movl    %esp,%ebp
    pushal
    movl    %esp, %eax
    pushl   %eax
    pushl   $0
    call    divzero

    addl    $8, %esp        /* add 8 to the stack pointer to skip the two variables*/
    popal                   /* resotre the flags */
    addl    $4, 4(%ebp)     /* add 4 to the return address */
    popl    %ebp            /* restore %ebp */
    iret                    /* return from the function */


text:
Q: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
    public ActionResult PopulateFromDB(string sidx, string sord, int page, int rows)
    {
        var context = new NerdDinnerEntities();
        var jsonData = new
        {
            total = 1,
            page = page,
            sord =sord,
            records = context.Authors.Count(),
            rows = (from n in context.Authors
                    select new
                    { AuthorId = n.AuthorId ,
                        cell = new string[] { n.AuthorId.ToString(), n.Name.ToString(), n.Location.ToString() }
                    }).ToList()
        };
        return Json(jsonData, JsonRequestBehavior.AllowGet);
    }

I am writting ToList or Toarray is it not working the error comes :
    public ActionResult PopulateFromDB(string sidx, string sord, int page, int rows)
    {
        var context = new NerdDinnerEntities();
        var jsonData = new
        {
            total = 1,
            page = page,
            sord =sord,
            records = context.Authors.Count(),
            rows = (from n in context.Authors
                    select new
                    { AuthorId = n.AuthorId ,
                        cell = new string[] { n.AuthorId.ToString(), n.Name.ToString(), n.Location.ToString() }
                    }).ToList()
        };
        return Json(jsonData,JsonRequestBehavior.AllowGet);
    }

A: You should try SqlFunctions.StringConvert to convert  this, There is no overload for int so you should cast your number to a double or a decimal.
public ActionResult PopulateFromDB(string sidx, string sord, int page, int rows)
{
    var context = new NerdDinnerEntities();
    var jsonData = new
    {
        total = 1,
        page = page,
        sord =sord,
        records = context.Authors.Count(),
        rows = (from n in context.Authors
                select new
                { AuthorId = n.AuthorId ,
                  cell = new string[] { SqlFunctions.StringConvert((double)n.AuthorId), n.Name, n.Location }
                }).ToList()
    };
    return Json(jsonData,JsonRequestBehavior.AllowGet);
}

You are not using LinqToSql Classes, if you were using that your code should work, but as  you mention that you are using LinqToEntity then You should use SqlFunctions.StringConvert to convert to string.

A: From your code I assume your adding a custom property cell for display/storage purposes on the client-side. I would avoid this as your essentially coupling your API call to one particular client. I would suggest you simply return the data required & deal with it at the client-side specifically e.g.
Server
...
select new
{
    Id = n.AuthorId,
    Name = n.Name,
    Location = n.Location
}).ToList();
...

Client
var response = ...
foreach (var author in response)
{
    var cell = new string[] { author.Id.ToString(), author.Name, author.Location };
    // do something with cell
}


text:
Q: Can't complete mvn verify without jersey-container-servle-core I am trying to run mvn verify on my project with 2.22.1 Jersey version.
<dependency>
  <groupId>org.glassfish.jersey.containers</groupId>
  <artifactId>jersey-container-servlet</artifactId>
  <version>2.22.1</version>
  <scope>runtime</scope>
</dependency>

When running mvn verify it says I am using  jersey-container-servle-core and I haven't declared it. According to Jersey notification this dependency in already in  jersey-container-servlet. Any idea?

A: The problem was that I used the "core" dependency in unit test and in web.xml.
In order to solve it I can do either:

*

*Change continar-servlet to compile and then I will have it for test as well. Because container-servlet include "core", it will work on test as well.

*Add jersey-container-servle-core just for test scope or with runtime


text:
Q: How to click on a button which has no fixed class value? But it have a fixed 'data-testid' How to click on a button which has no fixed class value? But it have a fixed 'data-testid'.
Using JS or Python How to achieve that?
document.getElementById("myCheck").click();

A: You can try with querySelector() which allows any valid CSS selector (i.e: attribute selector).
Demo:

function muFunction(){
  alert('Hi');
}

document.querySelector("[data-testid='123']").click();
<button data-testid="123" onclick="muFunction()">My Button</button>


text:
Q: Is it possible to show a database record in GridView spanning in two rows? I have a database record with fields e1 to e14 and v1 to v14 I would like to show them in gridview so each e is in upper row and the correspondent v is in lower row.
Is it possible or should I write  a custom function to display them in this way?

A: Take a look at GridView's Template Field option. Template Field gives you control as to how render the UI. In your case you will create two TR one for Field E and other for V.
This article will give you core concept and you can develop as per your requirement.ASP.NET TemplateFields in Grid view


text:
Q: Kafka offset - external storage vs consumer.committed(partition) I'me trying to use "Consumer external offset management" implementing ConsumerRebalanceListener.
I'm asking : Why does not use for onPartitionsAssigned calling consumer.committed(partition) to get the last committed offset instead of to read it from the same external storage? As I can see - kafka broker maintains itself this offset for each partition.
If we persisted last successfully reading message offset on external storage in @KafkaListener - the value of this offset will be exactly getting by consumer.committed(partition).
Of course we have: enable.auto.commit = false


text:
Q: Is It Possible To Make One Parameter Can Accept Value/Dat from Different Function/Data Type? I have two model dart.
The one is PromoModel and the other one is DealsModel
but the model has a similar structure (but not the same).
I only need one page (details page of promos and deals). So I thought, maybe it would be too redundant to have to create 2 detail pages, which are UI-like they are the same, and only differ from the parameters.
I see a lot of Functions or Classes that accept value/data with data type T. So is it possible to create only one class (UI/Page View) but can accept different Data types (in my case it is List PromoModel and DealsModel)?

A: Yes, you can do that with dart generics
The page code will look something like this
class Page<T> extends StatelessWidget {
List<T> _pageData;
// Add other variable
// Add construtor
  @override
  Widget build(BuildContext context) {
    return Container(
     // Add stuff here
    );
  }
}

Then you can create the page like this
Page<DealsModel>();

But with this approach, depending with the structure of your model, you may need to write some conditional logic in the page to account the differences of the model structure.


text:
Q: How to enable an uwp application to receive notification from the Microsoft store I have a desktop UWP app published on the Microsoft Store and I want to send notifications to users. I did exactly the same thing as described in this question and it didn't work. The Microsoft Store does not show the app in the list for creating a notification. Any suggestion?
Microsoft Store Engagement Services - Dev Center Push Notifications UWP C#

In the App.xaml.cs file:
using Microsoft.Services.Store.Engagement;

public App()
{
    this.InitializeComponent();
    this.Suspending += OnSuspending;

    prcEnableNotification();
}

private async void prcEnableNotification()
{
    StoreServicesEngagementManager manager = StoreServicesEngagementManager.GetDefault();
    await manager.RegisterNotificationChannelAsync();
}

protected override void OnActivated(IActivatedEventArgs args)
{
    base.OnActivated(args);

    if (args is ToastNotificationActivatedEventArgs)
    {
        var toastActivationArgs = args as ToastNotificationActivatedEventArgs;

        StoreServicesEngagementManager engagementManager = StoreServicesEngagementManager.GetDefault();
        string originalArgs = engagementManager.ParseArgumentsAndTrackAppLaunch(toastActivationArgs.Argument);
    }
}