text:
Q: How can I detect when the directory I think I'm in links to a different actual directory? If I am sshed into my Rails server, and I am in /var/www/some_app/current, it's actually a symlink pointing to (say) /var/www/some_app/releases/20201015004444.  If I do a deployment, then current is replaced with a new symlink pointing to (say) /var/www/some_app/releases/20201023010000.
Neither the output of pwd nor the value of $PWD change, however.  And of course my prompt doesn't change.  There is no visible indicator that anything is amiss.  Everything keeps humming along as if everything is great, and if I forget that I need to change to the new symlink, I won't know until something breaks or fails that I forgot to change directory.
How can I easily compare the actual current value of current with my actual current directory?

A: readlink -f . will tell you where you actually are, and
readlink -f $PWD will tell you what the symlink is currently pointing to, even if that's not the directory you're in.
This can be easily wrapped up in a function (which you can trigger automatically if you want):
correct_current_directory() {
  [[ $(readlink -f .) = $(readlink -f $PWD) ]] || echo "Moving $PWD from $(readlink -f .) to $(readlink -f $PWD)" && cd $PWD
}

It does nothing if you are where you think you are, but if your symlink gets moved to another directory it courteously notifies you that it is fixing the problem.  Since it lists both the old and new locations, you know exactly what's going on and can move back in that rare 0.01% of the time when you didn't want to get moved.


text:
Q: What is the gradient of $f(x, y, z) = \sqrt{x^2+y^2+z^2}$? What is the gradient of $f(x, y, z) = \sqrt{x^2+y^2+z^2}$?
I know that $\nabla f = \left\langle\frac{\partial f}{\partial x}, \frac{\partial f}{\partial y}, \frac{\partial f}{\partial z}\right\rangle$ or equivalently $\nabla f = \frac{\partial f}{\partial x}\mathbf{i} + \frac{\partial f}{\partial y}\mathbf{j} + \frac{\partial f}{\partial z}\mathbf{k}$.
Eventually, I am going to evaluate this gradient at a point and then dot it with some given unit vector to find a directional derivative. I think maybe what is troubling me is the radical in $f$. Will I have to use the chain rule in order to find the three partial derivatives?
I tried this:
$$\frac{\partial f}{\partial x} = \frac{1}{2}(x^2 + y^2 + z^2)^{-\frac{1}{2}}2x$$
$$= \frac{x}{\sqrt{x^2 + y^2 + z^2}}$$
That result looks ugly to me. However, if I did that partial derivative correctly, then I think I know what I am doing.

A: $$\nabla \|x\| = \frac{x}{\|x\|} $$
where $x = (x_1,x_2,\ldots, x_n)$ and $\|x\| = \sqrt{x_1^2+x_2^2+\ldots + x_n^2}$.

A: I'm fond of deriving this result as such. Note that $f(\mathbf{r})^2=x^2+y^2+z^2=\mathbf{r}\cdot \mathbf{r}$ by the definition of the dot product. Then the product rule for gradients implies $\nabla (f(\mathbf{r})^2)=2f(r)\nabla f(\mathbf{r})$ and therefore $$\nabla f(\mathbf{r})=\dfrac{\nabla (f(\mathbf{r})^2)}{2f(\mathbf{r})}=\dfrac{\nabla(x^2+y^2+z^2)}{2f(\mathbf{r})}=\dfrac{\langle 2x,2y,2z\rangle}{2f(\mathbf{r})}=\dfrac{\langle x,y,z\rangle}{\sqrt{x^2+y^2+z^2}}$$
In this form, the seemingly 'ugly' components become symmetric. Moreover, note that 1) this is a unit vector, 2) the denominator is just $\mathbf{r}$. So $\nabla f(\mathbf{r})=\dfrac{\mathbf{r}}{\sqrt{x^2+y^2+z^2}}=\dfrac{\mathbf{r}}{|\mathbf{r}|}=\hat{\mathbf{r}},$ i.e. the gradient is always a unit vector pointing outwards from the origin. That seems rather nice to me!

A: So you're asking about what is $\nabla_{\vec{v}}f$ where $f = \sqrt{x^2 + y^2 + z^2}$. First, lets organize the answer:
$\nabla_{\vec{v}}f =
\begin{aligned}
     \begin{bmatrix}
          \frac{\partial f}{\partial x} \\
          \frac{\partial f}{\partial y} \\
          \frac{\partial f}{\partial z}
     \end{bmatrix}
\end{aligned}$ $\cdot \, \vec{v}$
Now, lets solve for
$\frac{\partial f}{ \partial x}$.
$$\frac{\partial}{\partial x}\left(\sqrt{x^2 + \overbrace{y^2 + z^2}^{\mathrm{a\ constant}}}\right)$$
Now, lets start, also just for the sake of space, I'll make this substitution $y^2 + z^2 =c$, so we have
$$
\frac{\partial f }{\partial x}
= \frac{d}{dx}\sqrt{x^2 + c}
$$
so $g(x) = \sqrt{x},\, h(x) = x^2 + c$
I am going to skip some steps.
$$g'(x) = \frac{1}{2\sqrt{x}}, \qquad h'(x) = 2x$$
$$\frac{d}{dx} = g'(h(x)) \bullet  h'(x) \rightarrow \frac{4x}{\sqrt{x^2 \, + \, c }} \rightarrow  \mathbf{\frac{x}{\sqrt{x^2 + y^2 + z^2}}}$$
Then, $$\frac{\partial f}{\partial x} = \frac{x}{\sqrt{x^2 + y^2 + z^2}}, \, \frac{\partial f}{\partial y} = \frac{y}{\sqrt{x^2 + y^2 + z^2}}, \, \frac{\partial f}{\partial z} = \frac{z}{\sqrt{x^2 + y^2 + z^2}}.$$
Okay, so now let's find a directional derivative! But first, let's go to the gradient. say $\vec{v} =
\begin{aligned}
      \begin{bmatrix}
            a \\
            b \\
            c
      \end{bmatrix}
\end{aligned}$
$$\begin{aligned}
       \begin{bmatrix}
       \frac{x}{\sqrt{x^2 + y^2 + z^2}} \\
       \frac{y}{\sqrt{x^2 + y^2 + z^2}} \\
       \frac{z}{\sqrt{x^2 + y^2 + z^2}}
       \end{bmatrix}
            \cdot
       \begin{bmatrix}
       a \\
       b \\
       c \\
       \end{bmatrix}
\end{aligned} =
\frac{xa \,+ \, yb \, + \, zc}{\sqrt{x^2 \, +\,  y^2 \, + \, z^2}}$$
I hope I helped you out on this page.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to update Rickshaw graph without Fixed.Duration I'm trying to create a Real time Graphic with rickshaw but I didn't find how to update the graph without fixed duration as in the example (extensions.html).
I already know how to build my graph with a JSON file, but I don't know how to update the data (only data on the graph, I'd like to  keep my slider as-is) without refreshing the whole page.
Here is my code :

<script>

jQuery.ajax({
  'url': "Mesure.json",
  'success': renderGraph // callback for ajax success
});

// wrap graph creation logic in a function to be used as a callback
function renderGraph(json) {
<!--========================================================================-->
<!--                   COLOR PALETTE FOR DATA IN GRAPHIC                    -->
<!--========================================================================-->

var palette = new Rickshaw.Color.Palette( { scheme: 'spectrum14' } );

<!--========================================================================-->
<!--                     GRAPHIC OF DATA FROM DATABASE                      -->
<!--========================================================================-->

var graph = new Rickshaw.Graph( {
        element: document.getElementById("chart"),
        width: 900,
        height: 500,
        renderer: 'scatterplot',
        stroke: true,
        preserve: true,
        series: [

{
                        color: palette.color(1),
                        data: json[0].data,
                        name: 'Photorésistance 1',
                        opacity: 0.9
                }, {
                        color: palette.color(4),
                        data: json[1].data,
                        name: 'Photorésistance 2',
                        opacity: 0.9
                }, {
                        color: palette.color(8),
                        data: json[2].data,
                        name: 'Photorésistance 3',
                        opacity: 0.9
                }, {
                        color: palette.color(12),
                        data: json[3].data,
                        name: 'Photorésistance 4',
                        opacity: 0.9
                }
        ]
} );

graph.renderer.dotSize=4;
graph.render();

setInterval( function() { graph.update();}, 5000);

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I have to precise that I'm a beginner in php, javascript, Jquery, Ajax and I have no time to follow some class on the internet (this for an internship which ends in 2 weeks).


text:
Q: Finding element by the second class in Selenium Using inspect element, I have one element with two states:

Sometimes the element has the first form, sometimes the last form. I need to find the element when it's in the first state, so I need a way to driver.find_element by the data-original-title class. Is that possible?

A: You can retrieve them by checking whether contains the data-original-title attribute.
Selenium:
driver.find_elements(by=By.XPATH, value="//*[contains(@data-original-title, '')]")

Beautifulsoup:
soup.find_all("span", attrs={"data-original-title": True})

Output:
[]


text:
Q: OLS with multicollinear data and possible polynomial effects - what feature selection techniques would work? I am new to regression modelling, have a dataset (vegetation health over time for ~250 sites) that I would like to model using OLS as a function of 5 continuous variables: light, pollution, humidity, temperature, and precipitation.
I'm particularly interested in the effect pollution has on vegetation health, but its variables are known to be smaller than the other 4, so I hope that by including the other variables in my model I can improve my estimate of the pollution's coefficient.
Looking at the dataset, I have identified several issues:

*

*High multicollinearity between all the variables (e.g. sunny days involve high temperatures, etc.), including between pollution and the other variables.

*Possible polynomial effects - according to laboratory studies, there are potential nonlinear relationships between these independent variables and the vegetation health. In the past these have usually been modelled as quadratic polynomials. However, other studies based on field measurements have yielded perfectly sensible results by fitting only linear variables.

*Non-Gaussian distributions - none of the variables are entirely Gaussian, even after I fit and apply a Box-Cox transformation using scipy.stats.boxcox in Python.

As polynomial terms can introduce further collinearity to the problem, I have decided to model each variable as a set of orthogonal polynomial terms, and to include interaction terms (e.g. "temperature * pollution") in my fit. But this means I have > 20 variables in my model, so to avoid overfitting I need to try simplifying the model through feature selection. I also want to automate this somehow over all ~250 subsets of data I have.
Based on my problem, I have the following questions that I've not been able to find answers to:

*

*What feature selection technique is most robust to multicollinearity?

*Can I throw all 20+ variables (including all polynomial and interaction terms) into a feature selection algorithm and assume a sensible answer will come out?

*As I'm only interested in estimating the effect pollution has on vegetation health, does it necessarily matter if my feature selection returns an interaction term without one of the main variables? (e.g. selecting temperature * pollution but not temperature)? I want my fit to be useful in predicting future vegetation health, but am not necessarily interested in the other variables unless they impact pollution as well.

*I've experimented with using LASSO on my dataset, using sklearn.linear_model.LassoCV. I fed the surviving variables into a normal OLS fit using statsmodels.regression.linear_model.OLS to further scrutinise the fit, and found that several terms that LassoCV had selected were insignificant ($p > 0.05$). Why were these variables chosen by LASSO, and would it still be defensible to include these in my final model to make predictions?

*How alarmed should I be that none of my variables follow a Gaussian distribution? I would switch to using a GLS fit, but none of the supported distributions are perfect fits for my variables either.


text: Q: How can i create an .apk application using matlab code? Is there any possibility of creating a mobile applications (.apk) based on the coding in MATLAB. if there is no option, kindly guide me to create a application of my own in mobile platform.


text:
Q: Validation rule on Picklist value on Global Action I have created a Global Action  'Log a Call Custom'
Here on the Task object I have a Picklist field Subject with four values -
'Please Select
'Option 1'
'Option 2'
'Option 3'
The default is 'Please Select'
I created a validation rule to prevent a user from saving the activity if the value in subject is 'Please Select'
This is my validation rule
ISPICKVAL (Subject, Please Select)
However i am getting a syntax error
Error: Syntax error. Missing ')'
what am i mising?

A: Use Subject= 'Please Select'.
As per documentation 'Subject' field datatype is combobox.
Task Fields doc


text:
Q: Padding for Text() within Column not working? I have a Jetpack Compose composable in a column beginning with a icon, title, textbody and a pager row:
Box(modifier = Modifier
    .fillMaxSize()
    .background(color = TVTheme.colors.blue)
) {

val bigPadding = 334.dp
val smallPadding = 24.dp

    Column(
        verticalArrangement = Arrangement.Bottom,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {

        Image(
            modifier = Modifier
                .requiredSize(164.dp, 28.dp),
            icon = R.drawable.calendar_a_icon
        )

        // title
        val title = "Lorem Ipsum Dolor Sit"
        if (title.isNotEmpty()) {
            Text(
                text = title,
                textAlign = TextAlign.Center,
                modifier = Modifier
                    .padding(top = dimensionResource(id = R.dimen.vertical), start = bigPadding, end = bigPadding)
                    .fillMaxWidth(),
                overflow = TextOverflow.Visible
            )
        }

        // body
        val body = "Lorem ipsum dolor sit. Lorem ipsum dolor sit. Lorem ipsum dolor sit. Lorem ipsum dolor sit."
        if (body.isNotEmpty()) {
            Text(
                text = body,
                textAlign = TextAlign.Center,
                modifier = Modifier
                    .padding(top = dimensionResource(id = R.dimen.vertical), start = bigPadding, end = bigPadding)
                    .fillMaxWidth(),
                overflow = TextOverflow.Visible
            )
        }

        Row(
            modifier = Modifier
                .padding(top = 44.dp, bottom = smallPadding, start = smallPadding, end = smallPadding)
                .fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {

            val text = AnnotatedString.Builder(item.skipButtonText).toAnnotatedString()

            ClickableText(
                maxLines = 1,
                text = "Skip",
                onClick = {
                    skip()
                }
            )

            Pager(
                modifier = Modifier
                    .align(Alignment.CenterVertically),
                index = currentPageIndex,
                pageNumbers = totalPages)
        }
    }
}

which produces this screen:
The left and right paddings for the title and body is set to 334.dp. The example screenshot has a width of 1800 dp and according to proportions the paddings are much more than given 334.dp. That would mean, the width of title and body is 1132.dp ?!:

I tried to make the proportions visible.
How can I apply correct paddings for title and body text composables?


text:
Q: Postgres upsert perform multiple actions _OR_ versioning of events in an "append only" store Background
I am running on postgres 9.5
I have a table with events (in theory, it is, currently, an append only store).
Certain event types can appear only once on a given date. (So currently, we have a partial unique index and an upsert to update the "value" column when a conflict occurs <- so this is why it is not a fully append only store)
The goal: to be able to version the events mostly as an audit of past events - mostly in the sense that these events represent a misinterpretation of the facts and have thus been superseded by corrected events
I have, presently, come up with the notion by which I add a Nullable column with a timestamp to each event (I call it substituted_at). An event that has been superseded will have the timestamp recorded while the newest events will have that column value remain NULL. This should, hopefully, make retrieval of the events easy, for processing, I simply retrieve all events whose substituted_at value is NULL.
Another solution would have been to have moved the superseded events to an auxiliary table, but that didn't strike me as the way to go (comments?)
(Also, I am open to other propositions)
Sub goals:

*

*version events whose type can only appear once per date

*version events whose type can appear multiple times on a given date

*it should be possible to version an event without supplying a replacement event (in effect removing it from the event store for processing)

Question
I would like to center on sub-goal #1.
It would seem that in case of conflict I need to update the substituted_at column with a timestamp and keep all the other values as they are. I would also need to insert a new row with the new data.
It does not seem possible with the ON CONFLICT Clause.
I would obviously like to do this transactionally.
Also the solution should keep in mind that sub-goal #2 cannot rely on an ON CONFLICT clause - since it is alright to have more than one event per type per date.
Also, sub-goal #3 means that there would be times where no replacement would come at all.

As I write these lines, it seems to me that centering on UPSERT to do the heavy lifting is not the robust way I should be heading... Also, in the face of versioning, does the partial unique index make sense anymore?


text:
Q: Do two (or more) apps using GPS share the same location data stream? When an app calls for GPS data, does it activate the GPS call itself and then when another app simultaneously running calls it does it make a separate call? Or when the second app accesses the GPS does it get the data that's already there (or something similar, like a channel is opened in both apps which the GPS system sends all data to each channel when data is available)?
I'm wondering, because if each app only gets control of the GPS half the time it could certainly result in a less effective GPS. So I'm guessing that the iPhone was built with this in mind and the same GPS data would be available to each app, but I don't know if that's what's being done.
Does anyone know the internal workings of GPS on iOS?

A: In iOS, Location Services sits between all the location radios (cellular tower info, nearest wifi, GPS) and the apps, and caches the fused results between getting new information from those radios at a rate determined by the OS for decent battery life versus requested accuracy.  Apps never "control" or talk to the GPS hardware or OS driver directly.  The location information an app gets is time-stamped, so an app can check to see if it's old info or not.

A: I'll preface this with, I'm not an IOS developer, but I'm sure it works much the same was as Android and other GPS APIs.
When an App calls the GPS APIs it's calling an abstraction to the GPS/Location system and receives position information that the system presents.
So in this case when one application asks the OS for Location data, the OS uses a mix of GPS and Wifi data to determine the location of the device. If at the same time another application requests location data, the phone would just use the location data that it has instead of having to turn on the radios again.


text:
Q: magento 1.9.2.2 Display multiple categories on one cms page Im trying to display multiple categories on one cms page
<reference name="content">
<block type="catalog/product_list" name="home.catalog.product.list" category_id="7" template="catalog/product/list.phtml" />
</reference>

from here
it works fine.. but when I tried to display multiple categories, e.g(category='7', category='8'......) in one cms page, its display only one category repeatedly.
how can I make it using this way?
please help.

A: I got it using this.
<reference name="content">
<block type="catalog/product_list" name="home" template="catalog/product/list.phtml">
<action method="setCategoryId"><category_id>2</category_id></action>
<action method="addColumnCountLayoutDepend"><layout>one_column</layout><count>5</count></action>
<block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
<block type="page/html_pager" name="product_list_toolbar_pager"/>
 </block>
<action method="setToolbarBlockName"><name>product_list_toolbar</name><count>5</count></action>
</block>
</reference>

just repeat the block  and change the category_id to what you have and add something on name="home" to name="home.first" every time you add category.

I think this is a wrong way to achieve this, so i will try to get
  deeper on magento environment.


text:
Q: solaris 10 keymap fn and windows keys I have a sparc64 T5220 and I would like to modify my keymap because when I connect with ssh to the sverver/zones from my laptop with FN and Windows Keys.  When I use those keys I got garbage and not the right result: FN+left_arrow = goto the beginning of line (console/shell), FN+right_arrow = goto end of line, etc.
Thx for your help
Yves

A: Have you tried MobaXterm. Its really good as an ssh client and allows a lot of customization.


text:
Q: Disassembling C code and inspecting stack So I have some simple C code that creates a buffer of size 512 bytes:
 #include <sys/types.h>
 #include <netinet/in.h>

 #include <stdio.h>
 #include <ctype.h>

 main(argc, argv)
      char *argv[];
 {
    char line[512];
    gets(line);
 }

Does that mean exactly 512 bytes are allocated to the stack for that buffer? Is there a way in GDB we can disassemble the compiled binary we can see things like

*

*distance between the stack and the return address

*what parmeter gets passed to the 'gets()' function.. such as the address?

I tried stepping through this with GDB but couldn't find ways to inspect things like this

A: You could check out the 'strace' command line tool. It will list out all the internal system calls and the corresponding arguments. It will also give you an idea about how much memory is being allocated.
Please note that you should use gets with caution as it has no check for buffer overrun.
From the man page:
gets() reads a line from stdin into the buffer pointed to by s until either a terminating  newline  or  EOF,  which  it
       replaces with '\0'.  No check for buffer overrun is performed (see BUGS below).

A: You can use printf to show the memory addresses if you want, for example like this:
#include <stdio.h>
int main() {
  char line1[512];
  char line2[512];
  char line3[512];
  printf("line1 ptr: %p\n", line1);
  printf("line2 ptr: %p\n", line2);
  printf("line3 ptr: %p\n", line3);
  long int diff = line3 - line1;
  printf("diff between line3 and line1 : %ld\n", diff);
  return 0;
}

If you run that you will probably see that the memory locations of line1, line2, and line1 have precisely 512 bytes in between, if the compiler has chosen to lay it out in memory in that way.


text:
Q: Comparing two columns in Excel I have data with about 15 different columns and a total of 2400 rows.
The two columns I'm interested in: (Column C = Application Owner & Column D = Application Tester).  I'm trying to see which rows have the same name for both columns.
E.g.
Column C =
Mike
Bob
John
Bob
Adam
Column D =
Mike
Barry
Barry
Barry
Adam
So for this example I would like it to delete the contents of the three middle rows and only show me the first and fifth row because that is what I'm concerned with. Can anyone suggest a function of code or a function in Excel in which I can do this without actually having to go through all of them row by row?
Thanks

A: Add a column with something like =C2=D2 copied down to suit, filter for FALSE in that column and delete rows.

A: In a new Columns you can use =if(C2=D2,"DELETE","") then filter out this new column for DELETE  and delete the values from column C and D or the entire range


text:
Q: Horizontal Asymptote- Limits at Infinity Let $f(x)=\dfrac{4\sin(x)}{x^2+1}$. How would I find the $\lim_\limits{x\to\infty}\bigg(\dfrac{4\sin(x)}{x^2+1}\bigg)$?  I know that $\sin(x)$ oscillates periodically between $1$, and $-1$, so would the limit not exist?

A: It's true that the limit of sin(x) doesn't exist, but look at the denominator. What happens to the overall expression as x gets large? The limit does exist.

A: The oscillations don't matter here since the denominator grows indefinitely. Just note that
$$
0\leq\left|\frac{4\sin(x)}{x^2+1}\right|\leq\frac{4}{x^2+1}
$$
and now use the Squeeze Theorem to conclude that the limit as $x\to\infty$ of your function is $0$.

A: This might give you more intuition about why the oscillation does not really matter:

On the other hand, mathematically,
$$
\left|\frac{4\sin x}{x^2+1}\right|\leq\left|\frac{4}{x^2+1}\right|.
$$

A: We must use something called the squeeze theorem here. First of all, we know that $$-1 \leq \sin(x) \leq 1$$
$$-4 \leq 4\sin(x) \leq 4$$
$$\frac{-4}{x^2+1}\leq \frac{4\sin(x)}{x^2+1} \leq \dfrac{4}{x^2+1}$$
What the squeeze theorem allows is that if the
$\lim_\limits{x\to\infty}\bigg(\dfrac{-4}{x^2+1}\bigg) = \lim_\limits{x\to\infty}\bigg(\dfrac{4}{x^2+1}\bigg)$, then that is also equal to $\lim_\limits{x\to\infty}\bigg(\dfrac{4\sin(x)}{x^2+1}\bigg)$.
$$\lim_\limits{x\to\infty}\bigg(\dfrac{-4}{x^2+1}\bigg) = 0$$
$$\lim_\limits{x\to\infty}\bigg(\frac{4}{x^2+1}\bigg) = 0$$
THUS,
$$\lim_\limits{x\to\infty}\bigg(\dfrac{4\sin(x)}{x^2+1}\bigg) = 0$$

A: $\left|\frac{4\sin(x)}{x^2+1}\right|\le\frac{4}{x^2+1}\rightarrow 0$. So your asymptote is $y=0$


text:
Q: Parsing Android menu XML resource to objects list I can't resolve this problem for 3 days. I have simple XML resource for menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/categoryEditButton"
          android:title="@string/edit"
          android:icon="@drawable/edit" />
    <item android:id="@+id/categoryMoveUpButton"
          android:title="@string/move_up"
          android:icon="@drawable/up" />
    <item android:id="@+id/categoryMoveDownButton"
          android:title="@string/move_down"
          android:icon="@drawable/down" />
    <item android:id="@+id/categoryDeleteButton"
          android:title="@string/delete"
          android:icon="@drawable/trash" />
</menu>

I want to receive List<MenuItem> after parsing of this XML:
public class MenuItem {
    private CharSequence text;
    private Drawable image;
    private int actionTag;

    //... getters and setters ...
}

I need this for non-standard manipulations with MenuItems and can't work with this Resourse with standard methods like:
...

MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.some_menu, menu);

...

Can anybody help me with this? Thanks.

A: This will help:
...

PopupMenu p  = new PopupMenu(this, null);
Menu menu = p.getMenu();
getMenuInflater().inflate(R.menu.some_menu, menu);

//Usage of menu
System.out.println("LOG id: "+ menu.getItem(0).getItemId());
System.out.println("LOG title: "+ menu.getItem(0).getTitle());
System.out.println("LOG icon: "+ menu.getItem(0).getIcon());

...

The creation of a PopupMenu its just a trick to create a Menu object that when inflated will be filled with the information defined on your xml.

A: Thanks Raul.
It don't work for 2.33.
I have found solution Here.
private Menu newMenuInstance(Context context) {
    try {
        Class<?> menuBuilderClass = Class.forName("com.android.internal.view.menu.MenuBuilder");
        Constructor<?> constructor = menuBuilderClass.getDeclaredConstructor(Context.class);
        return (Menu) constructor.newInstance(context);
    } catch (Exception e){
        MyLog.GetMyLog().e(e);
    }
    return null;
}

A: Simple solution: https://gist.github.com/SaifurRahmanMohsin/8c9df2838d9a52830eb9
Menu menu = new MenuBuilder(context);
new MenuInflater(context).inflate(R.menu.my_menu, menu);

and
MenuItem item = menu.getItem(position)

A: You can easily change menu items at runtime.
Update after comment:

*

*Parse XML to get resource IDs and resource types (images, strings, drawables, etc..)

*Access resources via Resources class. Every resource type has different method to access it.


text:
Q: Android lollipop Menu button to Back button rendering If you see the Google Play app , when swiping the menu the menu button convert itself to back button with the finger gradually and nicely, it seems not an animation. can any one help me to achieve this thing ?
Feel free to move/close the post but please be nice to redirect me in any helpful direction.

A: Icon transitions can be implemented using AnimatedStateListDrawable (There's also support for animated vector icons.)
e.g.
 public void setOrAnimatePlusCheckIcon(final ImageView imageView, boolean isCheck,
                                      boolean allowAnimate) {
    if (!hasL()) {
        compatSetOrAnimatePlusCheckIcon(imageView, isCheck, allowAnimate);
        return;
    }

    Drawable drawable = imageView.getDrawable();
    if (!(drawable instanceof AnimatedStateListDrawable)) {
        drawable = mActivity.getResources().getDrawable(R.drawable.add_schedule_fab_icon_anim);
        imageView.setImageDrawable(drawable);
    }
    imageView.setColorFilter(isCheck ?
            mActivity.getResources().getColor(R.color.theme_accent_1) : Color.WHITE);
    if (allowAnimate) {
        imageView.setImageState(isCheck ? STATE_UNCHECKED : STATE_CHECKED, false);
        drawable.jumpToCurrentState();
        imageView.setImageState(isCheck ? STATE_CHECKED : STATE_UNCHECKED, false);
    } else {
        imageView.setImageState(isCheck ? STATE_CHECKED : STATE_UNCHECKED, false);
        drawable.jumpToCurrentState();
    }
}

code from https://github.com/google/iosched


text:
Q: How do you solve EMS Server connection when giving an error when you test? ERROR IMAGE Hey everyone I am having a trouble connecting to the ems server, it gives me a error that goes like this "Could not connect to ems server at "tcp://"localhost:7222"...I am using TIBCO BW5.
"The attempt returned an error"
"java.land.NoClassDefFoundError: com/tibco/tibjms/admin/TibjmsAdmin."
I would appreciate if you can tell me more about the error, and also how to fix it.
Thank You.

A: I belive you have to add tibjms.jar to your bw library.

A: I am assuming, you are trying to connect remote EMS Server, and you do not have EMS installed in your local machine. If that is true, copy tibjms.jar file from tibco\ems\8.2\lib  to tibco\tra\5.9\lib folder in your local machine. Then retry the domain utility.
Hope this helps to solve your problem.


text:
Q: Why this httpClient from Ionic 4 is not working? I tried to use Ionic 4 with Youtube Video Player, but I received this messages:
Follow the link of the repository:
Github

Run ionic serve -l:

It's working well, run using ionic serve.


text:
Q: create a responsive svg with react I want to create an svg that will be easily scaled on whatever width I'll give it. In that svg I have a circle and path with relative paths so I want it to be easily scaleable.
But for some reason the position of x,y are not right.
You can see the image below, the circle has (x,y)=(0,0)
but it is set in the middle.
I assume "viewBox" is causing problems.

jsfiddle link:
https://jsfiddle.net/tzookb/69z2wepo/174297/
code:
const ExclamationIcon = props => (
    <svg {...props} viewBox="0 0 140 140">
      <circle fill="#f66868" cx="70" cy="70" r="70" />
      <g transform="translate(58,30)">
        <path fill="white" d="M 11,56.7 L 9,56.7 L 4.2,13.2 C 4,11.4 4,10 4,9 C 4,7 4.5,4.9 5.6,3.5 C 7,2.2 8.3,1.5 10,1.5 C 11.7,1.5 13,2.2 14.4,3.5 C 15.5,4.9 16,7 16,9 C 16,10 16,11.4 15.8,13.2 z M 10,64 A 6,6 0 1,1 10,76 A 6,6 0 1,1 10,64 z"/>
      </g>
    </svg>
);

class Hello extends React.Component {
  render() {
    return (

        asdas
        <svg className="main">
          <rect x="20" y="20" width="100" height="40" fill="red" />

          <ExclamationIcon width="30" x="0" y="0" />
        </svg>

    );
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

A: Looks like this issue goes away if the height is set on the inner svg. I'm guessing that if the height is not set it automatically takes up all the available height and centres itself. I wish I had a better explanation but this completely stumped me.
JS Fiddle

const ExclamationIcon = props => (
    <svg {...props} viewBox="0 0 140 140">
      <circle fill="#f66868" cx="70" cy="70" r="70" />
      <g transform="translate(58,30)">
        <path fill="white" d="M 11,56.7 L 9,56.7 L 4.2,13.2 C 4,11.4 4,10 4,9 C 4,7 4.5,4.9 5.6,3.5 C 7,2.2 8.3,1.5 10,1.5 C 11.7,1.5 13,2.2 14.4,3.5 C 15.5,4.9 16,7 16,9 C 16,10 16,11.4 15.8,13.2 z M 10,64 A 6,6 0 1,1 10,76 A 6,6 0 1,1 10,64 z"/>
      </g>
    </svg>
);

class Hello extends React.Component {
  render() {
    return (

        asdas
        <svg className="main">
          <rect x="20" y="20" width="100" height="40" fill="red" />

          <ExclamationIcon width="30" height="30" x="0" y="0" />
        </svg>

    );
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);


text:
Q: What is the reason for getting different null values in between pandas and pyspark while we are using left join in both? from pyspark.sql.functions import col, when, count
null_values_count=df.select([count(when(col(c).isNull(), c)).alias(c) for c in df.columns])
display(null_values_count)

This is for pyspark
final_df=pd.merge(df,df_country,on='Country Code',how='left')

final_df.isnull().sum()

This is for pandas
Find the related  images with attachment


text:
Q: Contactless Card like visa Paywave using Magnetic Stripe Data I have a nRF5240 BLE chip which supports NFC Type 2 and Type 4 tag emulation protocol stack.
Is it possible to emulate a Contactless Card like Visa payWave or Mastercard PayPass which has Magnetic Stripe Data on it ?? If yes how?

A: Your scenario is similar to HCE application which runs on phones.  There are certain protocols that dictate how to respond to terminal commands(in hardware terms). If your chip is able to communicate with terminal then you need software to communicate with terminal. When your card is in distance of contactless terminal certain apdu commands sent to card to start a transaction. if you could code correctly you can get almost similar behaviour as PayWave or PayPass application.
During transaction, terminal could send your transaction to verify online then you have to know Issuer(Bank) keys. There is a small chance(offline limits are not exceeded) that you could get offline transaction but you have to know Issuer Certificates(it is based on RSA and dynamic values). This is harder to crack then online transactions, online keys.
Yes you could get your complete PayWave or PayPass card but you could not breach security.


text:
Q: XML parse file from HTTP I have an XML file located at a location such as
http://example.com/test.xml

I'm trying to parse the XML file to use it in my program with xPath like this but it is not working.
Document doc = builder.parse(new File(url));

How can I get the XML file?

A: Try using URLConnection.getInputStream() for getting the handle of XML file.
See the below code, in that I am trying to open an xml file and printing all the description fields:
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class HTTPXMLTest
{
    public static void main(String[] args)
    {
        try {
            new HTTPXMLTest().start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void start() throws Exception
    {
        URL url = new URL("http://localhost:8080/AutoLogin/resource/web.xml");
        URLConnection connection = url.openConnection();

        Document doc = parseXML(connection.getInputStream());
        NodeList descNodes = doc.getElementsByTagName("description");

        for(int i=0; i<descNodes.getLength();i++)
        {
            System.out.println(descNodes.item(i).getTextContent());
        }
    }

    private Document parseXML(InputStream stream)
    throws Exception
    {
        DocumentBuilderFactory objDocumentBuilderFactory = null;
        DocumentBuilder objDocumentBuilder = null;
        Document doc = null;
        try
        {
            objDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
            objDocumentBuilder = objDocumentBuilderFactory.newDocumentBuilder();

            doc = objDocumentBuilder.parse(stream);
        }
        catch(Exception ex)
        {
            throw ex;
        }

        return doc;
    }
}

A: Here is the simple example for getting data form this string "http://www.gettingagile.com/feed/rss2/"
public class MainClassXml {

    public static void main(String args[]) throws URISyntaxException,
            ClientProtocolException, IOException, MalformedURLException {

        String url = "http://www.gettingagile.com/feed/rss2/";
        System.out.println("Url is careated****");
        URL url2 = new URL(url);
        HttpGet httpGet = new HttpGet(url);
        HttpClient httpClient = new DefaultHttpClient();

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity entity = httpResponse.getEntity();
        System.out.println("Entity is*****" + entity);
        try {
            String xmlParseString = EntityUtils.toString(entity);
            System.out.println("This Stirng to be Pasrse***" + xmlParseString);

            HttpURLConnection connection = (HttpURLConnection) url2
                    .openConnection();
            InputStream inputStream = connection.getInputStream();

            DocumentBuilderFactory builderFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder documentBuilder = builderFactory
                    .newDocumentBuilder();
            Document document = documentBuilder.parse(inputStream);
            document.getDocumentElement().normalize();

            System.out.println("Attributes are***" + document.getAttributes());

            NodeList nodeList = document.getElementsByTagName("rss");
            System.out.println("This is firstnode" + nodeList);
            for (int getChild = 0; getChild < nodeList.getLength(); getChild++) {

                Node Listnode = nodeList.item(getChild);
                System.out.println("Into the for loop"
                        + Listnode.getAttributes().getLength());
                Element firstnoderss = (Element) Listnode;
                System.out.println("ListNodes" + Listnode.getAttributes());
                System.out.println("This is node list length"
                        + nodeList.getLength());

                Node Subnode = nodeList.item(getChild);
                System.out.println("This is list node" + Subnode);
                System.out.println("rss attributes***************");
            }

        } catch (Exception exception) {

            System.out.println("Exception is" + exception);

        }
    }

A: Get rid of the new File():
Document doc = builder.parse(url);

A: A little more detail, based on laz answer:
String urlString = "http://example.com/test.xml";
URL url = new URL(urlString);
Document doc = builder.parse(url);

A: It's much easier with a XMLPullParser ... you don't have to deal with this event stuff and can quickly pick up some keywords ... I'm using it too ... only a couple of code lines :)
http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html
Regarding HTTP and files have a look here
Download a file with DefaultHTTPClient and preemptive authentication

A: File fileXml = new File(url);

DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(fileXml);

it should go


text:
Q: EF 5.x Code First Connection String for DbContext Not Working I have a Project that has EF code first Classes and DB context
public partial class MyProjectContext : DbContext
{
    public MyProjectContext()
        : base("name=MyProjectContext")
    {
    }

    public DbSet<Person> Persons { get; set; }

My app.config looks like
<add name="MyProjectContext" connectionString="server=<serverIP>; user id=<userid>; password=<password>; database=<dbName>; pooling=false; Persist Security Info=True " providerName="MySql.Data.MySqlClient" />

I have Reference to this Project1 above in my Web Project, I also have  connection string below in web project
<add name="MyProjectContext" connectionString="server=<serverIP>; user id=<userid>; password=<password>; database=<dbName>; pooling=false; Persist Security Info=True " providerName="MySql.Data.MySqlClient" />

Here is the code that I have throws error
MyProjectContext db = new MyProjectContext();
            Person user = (from q in db. Persons
                            where q.PersonId == 1
                            select q).First();

I get the following Error
{"An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct."}

{"The provider did not return a ProviderManifestToken string."}

If I use MYsql with model first it works with Connector I Have which is 6.6.4.0
I already have a DB created manually, so i do not want to have Initialization for Creating DB. this Code first gives me more control of the classes than having to run the tt file and update the edmx file.

A: You don't need to put in name= at all, as long as the project that contains MyProjectContext also contains that connection string in its App.Config file:
public MyProjectContext() : base("MyProjectContext")

A: I ended up using the EF power Tools that did Reverse Eng inner code first generation, wihc worked. it produced the same Connection string but different DBcontext class with statict method.


text:
Q: sorting char* arrays I have a datastructure
struct record {
    char cont[bufferSize];
    record *next;
};

When I add new records to this structure, I want them to be sorted alphabetically. I made this function, that adds record in the right place (by alphabet) in the linked list:
record *start=NULL, *p, *x;

void recAdd(char*temp) {
        p = new record;
        temp[strlen(temp)] = '\0';
        for (int j=0;j<bufferSize;j++) p->cont[j] = temp[j];
        if (start==NULL) start=p;
        else {
            x=start;
            int c=0;
            while (recComp(x->cont,p->cont) <= 0 && x->next != NULL) {
                    x=x->next;
                    c++;
            }
            if (c == 0) {
                p->next=start;
                start=p;
            }
            else {
                x=start;
                for (int i=0;i<c;i++) x=x->next;
                p->next=x->next;
                x->next=p;
            }
        }
        for (int j=0;j<bufferSize;j++) temp[j] = NULL;
    };

But somehow it doesn't sort things right. What is wrong with my function?

A: Perhaps I'm not answering your question, but why aren't you using the STL?  It will do the sorting for you; you shouldn't have to write sorting routines like this these days.

A: Your code is a mess.  There are a number of problems both semantic and logical, but fundamentaly the logic that decides where to insert new nodes is the most flawed.  Change it to this (note my new code in the else block):
void recAdd(const char*t) {
        char temp[bufferSize];
        strcpy(temp, t);
        p = new record;
        temp[strlen(temp)] = '\0';
        for (int j=0;j<bufferSize;j++) p->cont[j] = temp[j];
        if (start==NULL) { start=p; start->next = 0; }
        else {
            record* x = start;
            record* prev = 0;
            while( x && recComp(x->cont, p->cont) <= 0 )
            {
                prev = x;
                x = x->next;
            }

            // p is a new node. p, x and prev are arranged thusly:
            // prev -> p -> x
            // if prev is null, p is a new head
            // if x is null, p is a new tail
            // otherwise, p is inserted between prev and x

            if( !prev )
            {
                p->next = start;
                start = p;
            }
            else if( !x )
            // note this block and the next one could be combined.
            // done this way for clarity.
            {
                prev->next = p;
                p->next = 0;
            }
            else
            {
                p->next = x;
                prev->next = p;
            }
        }
        for (int j=0;j<bufferSize;j++) temp[j] = NULL;
    };

BUT the fact that you had enough difficulty writing this code that you would ask SO for help in fixing it illustrates an important point:  the best code is code that you never have to write.  You have written both a linked list type structure (bare bones tho it may be) and a sorting algorithm.  Both are flawed, and both have working, tested and efficient versions available as part of the standard C++ libraries.  You should be using them.  Use strings instead of char*s.  Use vectors instead of your linked list.  Use sort instead of your hand rolled sorting algorithm.  Taken together, all your code can be replaced by this:
vector<string> records;

// this for block just populates the vector with random strings
for( int i = 0; i < 10; ++i )
{
    string s;
    for( int j = 0, jx = 3+(rand()/(RAND_MAX/10)); j < jx; ++j )
        s += 'A'-1+(rand()/(RAND_MAX/26));
    cout << s << endl;
    records.push_back(s);
}

sort(records.begin(), records.end());
copy( records.begin(), records.end(), ostream_iterator<string>(cout, " "));

Why hand-roll a bunch of stuff and expose yourself to countless defects when you can use tools that already work and do what you want?

A: Some tips:

*

*use strcmp to compare strings

*prefer using pointers to char inside your struct. This allows you to blindly assign them without copying and it won't waste space inside your struct

*if you really need to copy them use strdup to allocate new strings

*keep track of two current elements instead that just one, this will avoid counting how many you got so far and go through the list twice when you found right position

A: You can make you life here a lot easier if you implement a simple insert sort using STL vector (vector has a member 'insert').
that code will look much cleaner too :)
lookup cplusplus.com for examples there of, you will find it helpful.

A: As others have already suggested, the STL makes life a lot easier. It seems all you need is a sorted container of strings:
#include <iostream>
#include <set>
#include <string>

int main()
{
    std::set<std::string> words;
    words.insert("hello");
    words.insert("beautiful");
    words.insert("world");

    for (std::set<std::string>::const_iterator it = words.begin(); it != words.end(); ++it)
    {
        std::cout << *it << std::endl;
    }
}


text:
Q: Old School RuneScape kingdom management: what's the difference between collecting resources daily and weekly? In Old School RuneScape, I currently have 10 of my 15 Miscellanian subjects collecting herbs and the other 5 collecting maple logs.
I collect my kingdom's produced resources weekly (every seven days), topping up my favor and coffers when I do.
With the same allocation of workers (10 herb, 5 maple), how much more would my kingdom produce if I maintained it daily rather than weekly?

A: Collecting daily will slightly improve (+2-3%) our yields of herbs and logs, but give fewer herb seeds and bird's nests because of unfavorable daily rounding.
We can arrive at this answer quite easily using RuneHQ's excellent Miscellania Management calculator.
To calculate a full week's gathering, we set the calculator with at least 1.2M gold in the coffer, duration of 7 days, and the specified distribution of workers (10 herb gatherers, 5 maple choppers). This returns 410 herbs, 3 herb seeds, 3025 maple logs, and 30 bird's nests.
Repeating the process to get a day's output, we set the calculator with at least 750K gold in the coffer, duration of 1 day, and the same distribution of workers. This gives us a daily output of 60 herbs, 0 herb seeds, 445 maple logs, and 4 bird's nests. Multiplying this by 7 (days in a week) yields 420 herbs, 0 herb seeds, 3115 maple logs, and 28 bird's nests.
Although the herb and maple log yields improve slightly if we collect resources from the kingdom daily, the yields of maple logs and herb seeds, somewhat counterintuitively, decline! This is likely because of unfavorable rounding forced by collecting the resources daily, rather than weekly.

A: Not nearly enough to bother maintaining a daily reap of your crop.
http://services.runescape.com/m=forum/forums.ws?98,99,877,62965146
Posts 9 & 10 on page 1 give a tabled outcome of daily vs weekly workers to answer your question, but reading the whole thing will help understand why.


text:
Q: When "For all $a,b\in \Bbb Z,$ $a^n|b^m$ implies $a|b$""
$m\le n$ if and only if "For all $a,b\in \Bbb Z,$ $a^n|b^m$ implies $a|b$"

I can prove the sufficient condition part, by noting that $a^m|b^m$, which implis $a|b$. But I got stuck on the necessary condition part.
Any suggestion will be appreciated.

A: Hint: $ $ if $\,m> n\,$ then $ (c^m)^n\mid (c^n)^m,\,$ but $\, c^m\nmid c^n\ $ if $\, c > 1$

A: Let $p$ be a prime and $x\in \mathbb{N} $ be such that $p^x |a $ and $p^{x +1}\nmid a.$ Let $y\in \mathbb{N}$ be a such that $p^y |b $ and $p^{y +1}\nmid b.$
Since $a^n | b^m $ we have $$nx \leq  my$$ but since $m\leq n$ therefore $$y\geq x$$ and as consequnce $a|b.$


text:
Q: Turn off eclipse code navigation toolbar I accidentally clicked something, which made this appear:

Now I don't know how to turn it off.

A: This thing called breadcrumbs.
Please take a look to this post How to disable breadcrumbs in Eclipse to disable it


text:
Q: Why does the writer use 'is' twice in a row here? Why does the writer use 'is' twice in a row here?

Either the issuer's place of business where the undertaking is issued is located in a country that has adopted the Convention, or under international conflict of law principles, the law applicable to the undertaking is the law of a country that has adopted the Convention

A: I'll put brackets in to aid your understanding:
"either (the issuer's place of business [where the undertaking is issued] is located in a country) that has adopted the Convention, or under international conflict of law principles, the law applicable to the undertaking is the law of a country that has adopted the Convention"
The first "is" relates to "the undertaking" and the second "is" relates to the "place of business".

A: I think there are some missing commas in the example. Probably just a typo, or perhaps the author thought they'd used too many already. It's a horribly long sentence - a terrible example of English legalese, and it is on the verge of being almost impenetrable.
Here are some extra commas to help break it up a bit into digestible pieces.

Either the issuer's place of business, where the undertaking is
issued, is located in a country that has adopted the Convention, or
under international conflict of law principles, the law applicable to
the undertaking is the law of a country that has adopted the
Convention.

I've read it several times over. Still makes hardly any sense to me, but then I'm not a lawyer, just a simple human;)


text:
Q: Screen off/screen on Broadcast receiver working only once I'm developing my lockscreen. I successfully completed all the work but the main problem now in when I lock the screen my lockscreen works for the first time when I unlock it and lock it again, my lockscreen is not working.
I am not able to find the reason behind it.
My Lockscreen Service
 public class LockscreenService extends Service {
private LinearLayout linearLayout;
private WindowManager.LayoutParams layoutParams;
private WindowManager windowManager;
public static final String mypreference="mypref";
public static final String name4 ="key";
int imname;
SharedPreferences sp;
ImageView img,aimg;
final ArrayList<Bitmap> beforeshuffle = new ArrayList<>(9);
final ArrayList<Bitmap> aftershuffle = new ArrayList<>(9);
ArrayList<Bitmap> smallimages = new ArrayList<Bitmap>(9);
public static final String name1 ="imgkey";
GridView grid;
Bitmap bs;
Bitmap as;
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
BroadcastReceiver screenReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        boolean b = sp.getBoolean(name4, false);

            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF) ||intent.getAction().equals(Intent.ACTION_SCREEN_ON) && linearLayout == null) {
                init();

            }

    }
};
@Override
public void onCreate() {
    super.onCreate();
    sp = getSharedPreferences(mypreference, Context.MODE_PRIVATE);
    IntentFilter intentFilter = new   IntentFilter(Intent.ACTION_SCREEN_OFF);
    registerReceiver(screenReceiver, intentFilter);
    windowManager = ((WindowManager) getSystemService(WINDOW_SERVICE));
    layoutParams = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
            WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                    | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION,
            PixelFormat.TRANSLUCENT);

}
private void init() {

    if (sp.contains(name1)) {
        imname = sp.getInt(name1, 0);

    }
    linearLayout = new LinearLayout(this);
    windowManager.addView(linearLayout, layoutParams);
    ((LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.lockscreen, linearLayout);
    //   View btnClose = linearLayout.findViewById(R.id.button);

String wp="/data/user/0/com.example.user.myapplication/app_wallparerdir/wall.jpg";
Bitmap my = BitmapFactory.decodeFile(wp);
Drawable d = new BitmapDrawable(getResources(), my);
if(imname==1)
{
linearLayout.setBackground(d);
 }
      else {
      //Drawable image =    c.getResources().getDrawable(R.drawable.name_of_image_in_drawableFolder);
  linearLayout.setBackgroundResource(imname);
     }
    img = (ImageView) linearLayout.findViewById(R.id.bs);
    aimg = (ImageView) linearLayout.findViewById(R.id.as);
    grid = (GridView) linearLayout.findViewById(R.id.gridView);
    Globalvariable c=new Globalvariable();
    bs=c.giveBitmap();

    String p="/data/user/0/com.example.user.myapplication/app_imageDir/profile.jpg";
    Toast.makeText(getApplication(),p,Toast.LENGTH_SHORT).show();
    Log.d("path",p);
   String bspath="/data/user/0/com.example.user.myapplication/app_Beforeshuffle/beforeshuffle";

    bs=loadImageFromStorage(bspath);

    // Bitmap bitmap = (Bitmap) i.getParcelableExtra("bitmap");

    //smallimage_Numbers is to tell how many smallimage_s the image should split

    int smallimage_Numbers = 9;

    //Getting the source image to split

    //  ImageView image = (ImageView) findViewById(R.id.source_image);
    // File imgFile = new  File("profile.jpg"

    Bitmap myBitmap = BitmapFactory.decodeFile(p);
    splitImage(myBitmap, smallimage_Numbers);
    View btnClose = linearLayout.findViewById(R.id.button8);
    btnClose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            img.setImageBitmap(bs);
            as=getBitmapFromView(grid);
            aimg.setImageBitmap(as);
            Bitmap a=getBitmapFromView(img);
            Bitmap b=getBitmapFromView(aimg);
            img.setVisibility(View.INVISIBLE);
            aimg.setVisibility(View.INVISIBLE);
            // do something when the corky3 is clicked
            if(b.sameAs(a) ){
            //    Toast.makeText(getApplicationContext(),"CORRECT",Toast.LENGTH_SHORT).show();
                ///Intent service = new Intent(LockscreenService.this, calculator.class);
               // startService(service);
                Intent service = new Intent(LockscreenService.this, caclservice.class);
                startService(service);
               // windowManager.removeView(linearLayout);
               // linearLayout = null;
            }
            else
            {
                Log.d("jhgeiugh","jhgfeug");
               // Toast.makeText(getApplicationContext(),"WRONG",Toast.LENGTH_SHORT).show();
            }

        }
    });
    View btnemergency = linearLayout.findViewById(R.id.button6);
    btnemergency.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("ghfgh","dgd");
            Intent service = new Intent(LockscreenService.this, PopupService.class);
            startService(service);
        //    Toast.makeText(getApplicationContext(),"setted",Toast.LENGTH_SHORT).show();

    }
        });
    View btnforgot = linearLayout.findViewById(R.id.button7);
    btnforgot.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("ghfgh","dgd");
            Intent service = new Intent(LockscreenService.this, Forgotpassservice.class);
            startService(service);
            //            Toast.makeText(getApplicationContext(),"setted",Toast.LENGTH_SHORT).show();

        }
    });
}

My lockscreen shows a picture puzzle to solve then a calculator to type pin no to unlock device. So the calculator Service
 public class caclservice extends Service {
private int[] numericButtons = {R.id.btnZero, R.id.btnOne, R.id.btnTwo, R.id.btnThree, R.id.btnFour, R.id.btnFive, R.id.btnSix, R.id.btnSeven, R.id.btnEight, R.id.btnNine};
private static final String TAG = PopupService.class.getSimpleName();
WindowManager mWindowManager;
QuestionAdapter qa;
View mView; String username;
 TextView ques;
private Session session;
String question;
private TextView txtScreen;
// Represent whether the lastly pressed key is numeric or not
private boolean lastNumeric;
// Represent that current state is in error or not
private boolean stateError=false;
// If true, do not allow to add another DOT
private boolean lastDot;
@Override
public IBinder onBind(Intent intent) {
    return null;
}
@Override
public void onCreate() {
  stateError=false;
   showDialog();

  super.onCreate();
}

   @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    session=new Session(this);
    qa=new QuestionAdapter(this);
    username=session.getusename();
    question=qa.fetchreco(username);

    setNumericOnClickListener();
    return START_STICKY;
    //return super.onStartCommand(intent, flags, startId);
}

private void showDialog() {
   // PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
   // PowerManager.WakeLock mWakeLock = pm.newWakeLock((PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "caclservice");
   // mWakeLock.acquire();
   // mWakeLock.release();

    mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    mView = View.inflate(getApplicationContext(), R.layout.calculator, null);
    mView.setTag(TAG);

    int top = getApplicationContext().getResources().getDisplayMetrics().heightPixels / 2;

    LinearLayout dialog = (LinearLayout) mView.findViewById(R.id.lin);
   // if you want to set params
   //        android.widget.LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) dialog.getLayoutParams();
 //        lp.topMargin = top;
  //        lp.bottomMargin = top;
 //        mView.setLayoutParams(lp);
   txtScreen = (TextView) mView.findViewById(R.id.txtScreen);
    // ques.setText(question);

    // final EditText etMassage = (EditText) mView.findViewById(R.id.ans);
    //etMassage.setText("");
   /* ImageButton imageButtonSend = (ImageButton) mView.findViewById(R.id.imageButtonSendInPopupMessageReceived);
  //        lp = (LayoutParams) imageButton.getLayoutParams();
  //        lp.topMargin = top - 58;
 //        imageButton.setLayoutParams(lp);
    imageButtonSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(!etMassage.getText().toString().equals(""))
            {

                etMassage.setText("");
            }
        }
    });*/

    Button cancel = (Button) mView.findViewById(R.id.cancel);
  //  close.setText("Cancel");
    cancel.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            hidethisDialog();
        }
    });
    Button close = (Button) mView.findViewById(R.id.btnEqual);
    // close.setText("Cancel");
    close.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            String ans = txtScreen.getText().toString();
            if (ans.trim().equals(question.trim())) {

                stateError=true;

                hideDialog();
               // int flags = WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
               // getWindow().addFlags(flags);

            }
        }
    });

    final WindowManager.LayoutParams mLayoutParams = new WindowManager.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT, 0, 0,
            WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                    | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
                //    | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
            PixelFormat.RGBA_8888);

    mView.setVisibility(View.VISIBLE);
    mWindowManager.addView(mView, mLayoutParams);
    mWindowManager.updateViewLayout(mView, mLayoutParams);

}
private void setNumericOnClickListener() {
    // Create a common OnClickListener
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Just append/set the text of clicked button
            Button button = (Button) v;
            if (stateError) {
                // If current state is Error, replace the error message
            txtScreen.setText(button.getText());
                stateError = false;
            } else {
                // If not, already there is a valid expression so append to it
              txtScreen.append(button.getText());
            }
            // Set the flag
            lastNumeric = true;
        }
    };
    // Assign the listener to all the numeric buttons
    for (int id : numericButtons) {
        mView.findViewById(id).setOnClickListener(listener);
    }
}
private void hidethisDialog(){
    if(mView != null && mWindowManager != null){
        mWindowManager.removeView(mView);
        mView = null;

    }
}
private void hideDialog(){
    if(mView != null && mWindowManager != null){
        mWindowManager.removeView(mView);
        mView = null;

        startService(new Intent(this, LockscreenService.class));

/*
 * Notify the system to finalize and collect all objects of the
 * application on exit so that the process running the application can
 * be killed by the system without causing issues. NOTE: If this is set
 * to true then the process will not be killed until all of its threads
 * have closed.
 */
            System.runFinalizersOnExit(true);

/*
 * Force the system to close the application down completely instead of
 * retaining it in the background. The process that runs the application
 * will be killed. The application will be completely created as a new
 * application in a new process if the user starts the application
 * again.
 */
            System.exit(0);
       // stopService(new Intent(ActivityName.this, ServiceClassName.class));
        }
    }

@Override
public void onDestroy() {
    super.onDestroy();
}

I Call this in activity to lock screen
Intent service = new Intent(getApplicationContext(), LockscreenService.class);
    getApplication().startService(service);

A: If Broadcast Receiver not working then you can make a Service that run background continuously and watching that screen is off/on.
like this:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
isScreenOn = pm.isScreenOn();

     if (isScreenOn) {

         //Screen is on
     }
     else
     {
        //Screen is off
     }


text:
Q: react native gradlew assembleRelease failed to execute appt First stacktrace:

I am trying to produce an apk to my project but it always fail and produce the errors in the pictures
Please Help
Second stacktrace:

A: I think you can try by use Android Studio open android project inside react native  and clean so build by Android Studio. This way work for me. I just can use gradle build command after update/reinstall Android Studio


text:
Q: Is it possible to get singleton mentions by stanford-nlp software? We want to detect the mentions in our data by using the stanford-nlp coref annotator. It seems that the coref annotator does not create singleton chains (i.e. chains with only one mention) by default. Is it possible to configure the annotator so that the resulting annotation contains the signleton chains in addition to the non-singleton ones.
Thank you.

A: Depending on how you define entities, you can use the POS tagger or the phrase chunker to get the outstanding "1-member" coref chains.


text:
Q: doing multiple tasks on jQuery toggle I've 3 divs side by side.
By default 2 is hidden.
The center div is displayed.
What I want:

*

*Clicking on the top-right of the center div will display the right div and the center div will make some space sliding left of its original space.

*I want the same for the left div. Clicking the top-left side of the center div will display the left div pushing the center div a little to the right of its original space.

*Also when clicked on the top-left of the center div when the right div is open the right div will disappear.
Same goes for the left-div.
I'm using jQuery UI's toggle method. Everything is working except the no:3
I can show you the jQuery code I have.
$(document).ready(function(){
var state = true;
$('#contact-screw').click(function(){
    $('#about-box').hide();
    $('#content-box').css('float', 'left');
    if (state) {
        $('#content-box').css('float', 'left');
    } else {
        $('#content-box').css('float', 'none');
    }
    state = !state;
    $('#contact-box').toggle('explode', 'slow');
});
$('#about-screw').click(function(){
    $('#contact-box').hide();
    $('#content-box').css('float', 'left');
    if (state) {
        $('#content-box').css('float', 'left');
    } else {
        $('#content-box').css('float', 'none');
    }
    state = !state;
    $('#about-box').toggle('explode', 'slow');
});
});


text:
Q: #each works on ul/li but not on tbody/tr I have the following data that I am rendering twice in the same HTML file.
{ clients: [
    {_id:1234,'Client Name':'Mr Ed Voice Coaching','POC Name':'Mr Ed','POC Email':'Horse@Mr.Ed','POC TelNo':12345678},
    {_id:1234,'Client Name':'Mr Ed Voice Coaching','POC Name':'Mr Ed','POC Email':'Horse@Mr.Ed','POC TelNo':12345678}
]}

It works fine when rendered as LIs and SPANs within a UL.

    {{#each clients}}

      {{_id}},
      {{'Client Name'}},
      {{'POC Name'}},
      {{'POC Email'}},
      {{'POC TelNo'}}

    {{/each}}

However, it fails to render when used within a TBODY as TRs containing TDs.

    {{#each clients}}

      {{_id}}
      {{'Client Name'}}
      {{'POC Name'}}
      {{'POC Email'}}
      {{'POC TelNo'}}

    {{/each}}

I cannot find a problem when tested in http://tryhandlebarsjs.com/


text:
Q: Proper procedure for python package collections in Nixos I am interested in a reliable and robust procedure for collecting python package and dependencies for the Psychopy library into a single collection or environment to make a self-contained and maintainable installation. As well it would be good to have some general recommendations on the recommended way to do this since googling Nixos and Python yields a number of approaches, some of which use poorly documented function e.g. myEnvFun
Psychopy is a python package used for psychology experiments. It has several dependencies, most of which are python packages, but not all (e.g. AVbin); and most of which are in the nixos package collection, but not all (pyo and py-parallel).
My goal would be to be able to get all the needed pieces together and have a functioning psychopy environment with a single installation request. I have figured out how to get psychopy installed, but the path's don't play nicely.
For example if the following is saved as ~/pkg/psychopy/default.nix
let
  pkgs = import <nixpkgs> {};
in
{stdenv ? pkgs.stdenv, python ? pkgs.python, fetchurl ? pkgs.fetchurl}:

with pkgs;
buildPythonPackage {
  name = "psychopy";

  src = fetchurl {
    url = http://sourceforge.net/projects/psychpy/files/PsychoPy/PsychoPy-1.82.02.zip;
    md5 = "52309280bdca4408970aab0952c674e4";
  };

  buildInputs = [
    python27
  ];
}

One can run nix-env -f ~/pkg/ -iA psychopy and Psychopy will be installed, but it will not be easily useable because the path to the psychopy library is not seen by any system wide python2 installation, or even the python version that is installed as part of the build inputs.
This leads to the following questions that though they are specifically about psychopy would apply more generally to python and Nixos.

*

*Is the recommend practice to install python packages that exist in the nixos expression collections (e.g. numpy and scipy) once as system or user wide packages or with each particular experimental library?

*If one wishes to bundle together a python collection with more than one library outside the nixos expression channel (e.g. psychopy and pyo and pyparallel) what is the recommended procedure? And how does this change if some non-python software is required, e.g. in this case AVbin (which actually has installation instructions that refers to paths that are not standard in Nixos to my understanding, i.e. /usr/lib)?

*Can some discussion of handling paths in Python with the context of Nixos be shared?

A: myEnvFun is deprecated, where did you read about it?
Answers:

*

*It's recommended to create environments with nix-shell, you should be able to run it inside ~/pkg/psychopy/ and get $PYTHONPATH populated.
The idea behind Nix is not to have any global sets of packages, but rather environments for each need.

*By just declaring AVBin as build dependency it should be enough. Note that your users will need to install Nix. If you want to avoid that, you'll need to write a wrapper that will do something similar to nix-shell.

*There isn't much going on here. All Nix packages are build in isolated chroots. Nix has a concept called setup hooks, which are executed for each package in the dependency tree. So for Python packages https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/interpreters/python/2.7/setup-hook.sh#L15 is called in order to populate $PYTHONPATH. For command line programs we then wrap the resulting script with $PYTHONPATH hardcoded.
For discussion it's best to join Freenode IRC channel #nixos


text:
Q: How does race day work? I dominated the 'battle machine' race day but I can't figure out what to do next to proceed. The next level is locked.

A: You need to go to the small events before going to the big events. Small events are events that opens after you unlock the big events (such as the skull icon on top of the BATTLE MACHINE or the weird circle thing below the BATTLE MACHINE, you need to play several events like that in order to unlock the next big event)


text:
Q: multicolumn and multirow for divided differences is there a package that will automate the typesetting of the triangular table used to calculate the coefficients used in Newton's divided differences algorithm? but in a table like the following image

A: With TikZ it is fairly easy to create something that computes the entries. This answer defines such a pic. All you need to say is
\begin{tikzpicture}
 \pic{difftable={0,1,3,5}{3,2,4,-1}};
\end{tikzpicture}

where the first list contains the xi and the second the fi.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning,patterns}
\usepackage{eqparbox}
\newbox\eqnodebox
\tikzset{equal size/.style={execute at begin
    node={\setbox\eqnodebox=\hbox\bgroup},
    execute at end node={\egroup\eqmakebox[#1][c]{\copy\eqnodebox}}},
    equal size/.default=A,}
\newcounter{difftable}
\makeatletter
\pgfmathdeclarefunction{Dim}{1}{%
\begingroup%
\pgfutil@tempcnta0%
\@for\pgfutil@tempa:=#1\do{\advance\pgfutil@tempcnta1}%
\edef\pgfmathresult{\the\pgfutil@tempcnta}%
\pgfmathsmuggle\pgfmathresult\endgroup%
}
\pgfmathdeclarefunction{diffquots}{2}{%
\begingroup%
\pgfutil@tempcnta1%
\pgfmathtruncatemacro{\pgfutil@tempa}{min(Dim("#1"),Dim("#2"))}%\typeout{dim=\pgfutil@tempa}%
\pgfutil@loop
\pgfmathsetmacro{\pgfutil@tempb}{{#1}[\the\pgfutil@tempcnta]-{#1}[\the\numexpr\pgfutil@tempcnta-1]}%
\pgfmathsetmacro{\pgfutil@tempc}{{#2}[\the\pgfutil@tempcnta]-{#2}[\the\numexpr\pgfutil@tempcnta-1]}%
\ifdim\pgfutil@tempc pt=0pt\relax
\tikzerror{You asked me to divide by zero. Terminating.}%
\fi
\pgfmathsetmacro{\pgfutil@tempd}{\pgfutil@tempb/\pgfutil@tempc}%
\pgfmathsetmacro{\pgfutil@tempe}{{#2}[\the\pgfutil@tempcnta]/2+{#2}[\the\numexpr\pgfutil@tempcnta-1]/2}%
\ifnum\pgfutil@tempcnta=1\relax
\edef\pgfutil@tempf{\pgfutil@tempd}%
\edef\pgfutil@tempg{\pgfutil@tempe}%
\else
\edef\pgfutil@tempf{\pgfutil@tempf,\pgfutil@tempd}%
\edef\pgfutil@tempg{\pgfutil@tempg,\pgfutil@tempe}%
\fi
\advance\pgfutil@tempcnta1%
\ifnum\pgfutil@tempcnta<\the\numexpr\pgfutil@tempa-1%
\pgfutil@repeat
\edef\pgfmathresult{"\pgfutil@tempf","\pgfutil@tempg"}%
\pgfmathsmuggle\pgfmathresult\endgroup%
}%
\makeatother
\tikzset{result/.style={draw,text height=1em,text depth=0.35ex,
 inner xsep=0.5ex,align=center,equal size=\pgfkeysvalueof{/tikz/difftable/id}-#1},
 pics/difftable/.style 2 args={code={\stepcounter{difftable}
   \tikzset{difftable/id=\number\value{difftable}}
   \node[result=1] (xi-1) {$x_i$}; %
   \path foreach \X [count=\Y] in {#1}
    {node[result=1,below={-\pgflinewidth} of xi-\Y,alias=xi-last]
      (xi-\the\numexpr\Y+1)   {\pgfmathprintnumber{\X}}};
   %
   \node[result=2,right={-\pgflinewidth} of xi-1] (fi-1) {$f(x_i)$};
   \path foreach \X [count=\Y] in {#2}
    {node[result=2,below={-\pgflinewidth} of fi-\Y,alias=fi-last] (fi-\the\numexpr\Y+1)
    {\pgfmathprintnumber{\X}}};
   %
   \pgfmathsetmacro{\myresultA}{diffquots("#1","#2")}
   \pgfmathsetmacro{\lstdfi}{{\myresultA}[0]}
   \pgfmathsetmacro{\lstdxi}{{\myresultA}[1]}
   \node[result=3,right={-\pgflinewidth} of fi-1] (dfi-1) {$DD1$};
   \path foreach \X [count=\Y starting from 2] in \lstdfi
    {node[result=3,alias=dfi-last]  (dfi-\Y) at
    (dfi-1|-fi-\Y.south east)  {\pgfmathprintnumber{\X}}};
   %
   \pgfmathsetmacro{\myresultB}{diffquots("\lstdfi","\lstdxi")}
   \pgfmathsetmacro{\lstddfi}{{\myresultB}[0]}
   \pgfmathsetmacro{\lstddxi}{{\myresultB}[1]}
   \node[result=4,right={-\pgflinewidth} of dfi-1] (ddfi-1) {$DD2$};
   \path foreach \X [count=\Y starting from 2] in \lstddfi
    {node[result=4,alias=ddfi-last]  (ddfi-\Y) at
    (ddfi-1|-dfi-\Y.south east)  {\pgfmathprintnumber{\X}}};
   %
   \pgfmathsetmacro{\myresultC}{diffquots("\lstddfi","\lstddxi")}
   \pgfmathsetmacro{\lstdddfi}{{\myresultC}[0]}
   \pgfmathsetmacro{\lstdddxi}{{\myresultC}[1]}
   \node[result=5,right={-\pgflinewidth} of ddfi-1] (dddfi-1) {$DD3$};
   \path foreach \X [count=\Y starting from 2] in \lstdddfi
    {node[result=5,alias=dddfi-last]  (dddfi-\Y) at
    (dddfi-1|-ddfi-\Y.south east)  {\pgfmathprintnumber{\X}}};
   %
   \path[pattern=north east lines] (fi-2.north east)
    foreach \X in {d,dd,ddd}
    {|- (\X fi-2.north east) }
    |- cycle
    (fi-last.south east)
    foreach \X in {d,dd,ddd}
    {|- (\X fi-last.south east) }
    |- cycle;
   \draw[thick] (xi-1.north west) rectangle (xi-last.south-|dddfi-1.east);
   }},
   difftable/.cd,id/.initial=0}
\begin{document}
\begin{tikzpicture}
 \pic{difftable={0,1,3,5}{3,2,4,-1}};
\end{tikzpicture}
\bigskip

\begin{tikzpicture}
 \pic{difftable={0,1,3,5}{2,5,-3,1}};
\end{tikzpicture}

\end{document}


text:
Q: Need to run a query that returns data for every hour even if it doesn't exist I tried searching for something similar but couldn't quite pinpoint the problem.
Currently working in Oracle 11g
I have a table, let's call it TEST_DATA, with columns "SITE", "DAY", "TIME" AND "TEMPERATURE", that holds average temperature data for a specific site at a specific day and time, and it will not contain data for every hour of every day. At the moment, let's say I only have this data:
TEST DATA:

What I need, is to build a view or a query, that returns a set of results for every day and every hour, even if it's not in the TEST_DATA table (returning 0 in that case), which would return a result similar to:
SITE | DAY | TIME | TEMPERATURE
Home |   1 |    0 |           0
Home |   1 |    1 |           0
Home |   1 |    2 |           0
Home |   1 |    3 |          15
Home |   1 |    4 |           0
Home |   1 |    5 |          23
Home |   1 |    6 |           0
Home |   1 |    7 |           0
Home |   1 |    8 |           0
Home |   1 |    9 |           0
Home |   1 |   10 |           0
...  | ... |  ... |         ...

Does anyone have any idea how I could go about doing this using SQL?
I tried having a table with 24*31 entries and day/time columns, making a row for each day/time pair, but haven't figured out a way to get this working as I want.
I want to try and avoid to make this last table with that many rows for each of the possible sites, since I'm working with over 2000 different sites, which would make the table over a million rows long.
I appreciate any help on the matter.
EDIT:
Thanks to @Gordon Linoff's answer, I was able to adapt to my table and got the results exactly as I wanted them. The query ended up being:
SELECT s.SITE, d.DAY, d.TIME, td.TEMPERATURE
FROM (SELECT DISTINCT SITE FROM TEST_DATA) s CROSS JOIN
     (SELECT * FROM TEST_DAY_TIME) d LEFT JOIN
     TEST_DATA td
ON td.SITE = s.SITE AND td.DAY = d.DAY AND td.TIME = d.TIME
ORDER BY d.DAY, d.TIME;

The other table was something like this, all the way to 31.
TEST_DAY_TIME

A: Generate all the rows and then use left join to bring in the values. This is the basic idea:
select s.site, d.date, h.time, t.temperature
from (select distinct site from t) s cross join
     (select distinct day from t) d cross join
     (select 0 as time from dual union all select 1 from dual union all . . .
      select 23 from dual) h left join
     t
     on t.site = s.site and t.day = d.date and t.time = h.time;

Of course, you will get duplicates if a day/time combination appears multiple times in the original table.

A: You need to create some time data then outer join to your data so you have the basis of the empty times.
This can be done with a simple use of connect by as the following.  This will use 1/1/17 as the start date and give you 1 hour increments for the next 100 days.
select to_date('01-jan-17','dd-mon-yy') + numtodsinterval(level,'HOUR') as date_by_hour
    from dual
    connect by level <= 24*100;

You then can put your data and this data together via an outer join like the following...
WITH time_data as
    (select to_date('01-jan-17','dd-mon-yy') + numtodsinterval(level,'HOUR') as date_by_hour
    from dual
    connect by level <= 24*100),
     test_data(site, day, time, temp) as
    (select 'HOME', 1, 3, 50 from dual union all
     select 'HOME', 1, 4, 51 from dual union all
     select 'HOME', 1, 7, 55 from dual union all
     select 'HOME', 1, 12, 60 from dual)
select NVL(test_data.site,'HOME') as site, time_data.date_by_hour, NVL(test_data.temp,0) as temp
  from time_data
    left outer join test_data on (time_data.date_by_hour =
                      to_date('01-jan-17','dd-mon-yy')+numtodsinterval(test_data.day-1,'DAY')+numtodsinterval(test_data.time,'HOUR')
                    AND test_data.site = 'HOME')
order by time_data.date_by_hour;

Another point, I would suggest that you store your date/time data as a DATE and not simply a number day and number time.


text:
Q: Create an error log file in php I want an error log file attached to my application I have developed. My application is made in php mysql and I need that whatever error is found it should be displayed in a .txt file with full explanation like what is the error in which line number like that. I have no Idea how can I get that.
Can anyone help me creating this and changes do I have to make to get those error in my application. My server is an IIS server.

A: First we have to see types of errors in PHP:
Notices: These are non-critical errors which PHP encounters while running a script. For example, a variable accessibility before it is declared.
Warnings: The are more serious errors. For example, using include()without the existence of the file.
Fatal Errors: These errors are critical errors. For example, creating an object of a non-existent class. These errors terminate the script's execution immediately. These are intimated to the users.
Now, the process of Catching these 3 types of errors
//Setting for the PHP Error Handler
set_error_handler( call_back function or class );

//Setting for the PHP Exceptions Error Handler
set_exception_handler(call_back function or class);

//Setting for the PHP Fatal Error
register_shutdown_function(call_back function or class);

Whatever the function or class is described by user for tracing the error the following command is used:
 $debug = debug_backtrace();

 print_r($debug);

If you print the debug then it will show you the running process and file name, line number of the error.


text:
Q: JQuery load event I want to run a function when elements of a certain class are loaded and clicked... so something like:
$(".blah").on("load,click", function() {
    // do stuff
})

but it seems that the load event is not an event (maybe?). What's the best way to get the function to run on click and on load?

A: You could trigger the click on document ready:
$(document).ready(function() {
   $('.blah').click(function() {
       // handle click event
   });
   $('.blah').trigger('click');
});

From the jQuery documentation for load:

The load event is sent to an element when it and all sub-elements have
been completely loaded. This event can be sent to any element
associated with a URL: images, scripts, frames, iframes, and the
window object.

A: Actually there is a load event. You code don't work because you need comma between events. It should be like this: "load click".
But I think you need a click be triggered only after the element is loaded, so it should be like this:
$(".blah").load(function() {
    $(this).bind("click", function() {
        // do stuff
    })
})

Note that if you are loading images it may not work
Caveats of the load event when used with images:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache

http://api.jquery.com/load-event/


text:
Q: How to create static strings from types at compile time I have a bunch of types that have a name. (They have more features, but for the sake of this discussion only the name is relevant.) These types and their names are setup at compile-time using a macro:
#define DEFINE_FOO(Foo_)                        \
    struct Foo_ : public foo_base<Foo_> {       \
      static char const* name() {return #Foo_;} \
    }

The types are then combined in compile-time lists (classic simple recursive compile-time lists), from which I need to create the list's name by concatenating the names of its objects:
template<class Foo, class Tail = nil>
struct foo_list {
  static std::string name_list() {return Foo::name() + "-" + Tail::name();}
};
template<class Foo>
struct foo_list<Foo,nil> {
  static std::string name_list() {return Foo::name();}
};

The code is boiled down here to the point where it might contain errors, but in practice this works pretty well.
Except that it creates and then copies around rather long strings at runtime which represent types that actually are well-known at compile-time. Since this is a rather performance-sensitive piece of code that runs on embedded devices, I'd like to change this so that

*

*the list's string is ideally created at compile-time, or, if there's no way to do that, once at runtime, and

*I only need to copy around a pointer to a C string, since, according to #1, the strings are fixed in memory.

*This compiles with C++03, which we're stuck with right now.

How can I do this?
(In case this enlarges the arsenal of dirty tricks employable for this: The names of the foo objects are only ever created and read by code, and only the foo_list name strings are expected to be human-readable.)

A: You probably want to look at boost's mpl::string. Example to follow once my coffee has kicked in...
EDIT: So coffee has kicked in... :)
#include <iostream>

#include <boost/mpl/bool.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/string.hpp>
#include <boost/mpl/vector.hpp>

namespace mpl = boost::mpl;

struct foo
{
  typedef mpl::string<'foo'> name;
};

struct bar
{
  typedef mpl::string<'bar'> name;
};

struct gah
{
  typedef mpl::string<'gah'> name;
};

namespace aux
{

template <typename string_type, typename It, typename End>
struct name_concat
{
  typedef typename mpl::insert_range<string_type, typename mpl::end<string_type>::type, typename mpl::deref<It>::type::name>::type base;
  typedef typename aux::name_concat<base, typename mpl::next<It>::type, End>::name name;
};

template <typename string_type, typename End>
struct name_concat<string_type, End, End>
{
  typedef string_type name;
};

}

template <typename ...Types>
struct type_list
{
  typedef mpl::string<> base;
  typedef mpl::vector<Types...> type_seq;
  typedef typename aux::name_concat<base, typename mpl::begin<type_seq>::type, typename mpl::end<type_seq>::type>::name name;
};

int main(void)
{
  typedef typename type_list<foo, bar, gah>::name tlist_name;
  std::cout << mpl::c_str<tlist_name>::value << std::endl;
}

I'm sure you are more than competent enough to tweak the above for your situation. NOTE: you will have to ignore the multi-character constant warnings...
Couple of more caveats: the multi-character constant passed to mpl::string cannot be more than 4 characters, so, some how it has to be chunked (or constructed of individual characters), so a long string could be, mpl::string<'this', ' is ', 'a lo', 'ng s', 'trin', 'g'> If this is cannot be done, then the above will not work.. :/

A: I came up with following solution:
Type is generated as:
const char foo_str [] = "foo";
struct X
{
    static const char *name() { return foo_str; }
    enum{ name_size = sizeof(foo_str) };
};

Keypoint here is that we know length of its name at compile time. That allow us to calculate total length of names in typelist:
template<typename list>
struct sum_size
{
    enum
    {
       value = list::head::name_size - 1 +
               sum_size<typename list::tail>::value
    };
};
template<>
struct sum_size<nil>
{
    enum { value = 0 };
};

Knowing total length at compile time, we can allocate static buffer of appropriate size for concatenation of strings - so there will be no any dynamic allocations:
static char result[sum_size<list>::value + 1];

That buffer should be filled at runtime, but only once, and that operation is pretty cheap (much faster than previous solution with dynamic allocation of strings and their concatenation in recursion):
template<typename list>
const char *concate_names()
{
    static char result[sum_size<list>::value + 1];
    static bool calculated = false;
    if(!calculated)
    {
        fill_string<list>::call(result);
        calculated = true;
    }
    return result;
}

Here is full code:
Live Demo on Coliru
#include <algorithm>
#include <iostream>
using namespace std;

/****************************************************/

#define TYPE(X) \
const char X ## _str [] = #X; \
struct X \
{ \
    static const char *name() { return X ## _str; }  \
    enum{ name_size = sizeof(X ## _str) }; \
}; \
/**/

/****************************************************/

struct nil {};

template<typename Head, typename Tail = nil>
struct List
{
    typedef Head head;
    typedef Tail tail;
};

/****************************************************/

template<typename list>
struct sum_size
{
    enum { value = list::head::name_size - 1 + sum_size<typename list::tail>::value };
};
template<>
struct sum_size<nil>
{
    enum { value = 0 };
};

/****************************************************/

template<typename list>
struct fill_string
{
    static void call(char *out)
    {
        typedef typename list::head current;
        const char *first = current::name();
        fill_string<typename list::tail>::call
        (
            copy(first, first + current::name_size - 1, out)
        );
    }
};

template<>
struct fill_string<nil>
{
    static void call(char *out)
    {
        *out = 0;
    }
};

/****************************************************/

template<typename list>
const char *concate_names()
{
    static char result[sum_size<list>::value + 1];
    static bool calculated = false;
    if(!calculated)
    {
        fill_string<list>::call(result);
        calculated = true;
    }
    return result;
}

/****************************************************/

TYPE(foo)
TYPE(bar)
TYPE(baz)

typedef List<foo, List<bar, List<baz> > > foo_list;

int main()
{
    cout << concate_names<foo_list>() << endl;
}

Output is:
foobarbaz

P.S. How do you use concatenated string? Maybe we don't need to generate concatenated string at all, reducing data space requirement.
For example if you just need to print string - then
template<typename list>
void print();

will be sufficient. But downside is that while decreasing data size - that could lead to increased size of code.

A: *

*You could make the string  static and you only have to construct the string once at runtime and only when it is needed.

*Then you return a const reference of them so that there wouldn't be any unnecessary copying.

Example:
template<class Foo, class Tail = nil>
struct foo_list {
  static const std::string& name_list() {
     static std::string names = Foo::name() + std::string("-") + Tail::name();
     return names;
  }
};

template<class Foo>
struct foo_list<Foo,nil> {
  static const std::string& name_list() {
     static std::string names = Foo::name();
     return names;
  }
};

Might not be the exact code that you'll write, but I think that gives you the point. Also, you could return a const char* by doing names.c_str().

A: You can consider using an external build step instead of an in-language solution. For example, you could write a tool based on Clang to parse the relevant files and create the T::name implementations automatically in another TU. Then integrate it into your build script.

A: If we could assume that your only requirement is to actually stream the names of the classes - meaning you don't need the concatenated strings at other places as a whole - you could simply defer streaming but still benefit from meta-programming (as Evgeny already pointed out).
While this solution doesn't satisfy your requirement #1 (one concatenated string), I'd still like to point out a solution for other readers.
Instead of going through a compile-time list of types, the idea is to build a sequence of addresses from all T::name() functions and pass that into a streaming function when needed. This is possible because variables with external linkage can be used as template non-type arguments. Your mileage may vary in terms of data and code size of course, but unless you are in a high-performance environment I expect this approach to be at least equally suitable as no additional strings have to be created at runtime.
Note that I deliberately used variadic templates (not available in C++03) because it's much more readable and simpler to reason about.
"Fiddle" available here.
#include <ostream>
#include <boost/core/ref.hpp>
#include <boost/bind.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/for_each.hpp>

namespace mpl = boost::mpl;

template<typename>
class foo_base
{};

#define DECLARE_FOO(Foo_) \
    struct Foo_ : public foo_base<Foo_> { \
        static char const* name() {return #Foo_;} \
    };

// our own integral constant because mpl::integral_c would have to be specialized anyway
template<typename T, T Value>
struct simple_integral_c
{
    operator T() const { return Value; }
};

template<typename T, T ...Values>
struct ic_tuple : mpl::vector<simple_integral_c<T, Values>...>
{};

typedef const char*(*NameFunction)();

template <NameFunction ...Functions>
struct function_list : ic_tuple<NameFunction, Functions...>
{};

template <typename ...Types>
struct function_of_list : function_list<&Types::name...>
{};

struct print_type
{
    void operator ()(std::ostream& os, NameFunction name)
    {
        if (nth++)
            os << "-";
        os << name();
    }

    print_type(): nth(0) {}

private:
    int nth;
};

// streaming function
template<NameFunction ...Functions>
std::ostream& operator <<(std::ostream& os, function_list<Functions...>)
{
    mpl::for_each<function_list<Functions...>>(
        boost::bind<void>(print_type(), boost::ref(os), _1)
    );

    return os;
}

These days with C++14 one would probably write the solution with a powerful library like hana, see this hana fiddle.


text:
Q: regular expression for "def" I'm trying to find a regular expression for "def"
it should work as following:
def h():
def f(a=1):
def g(a=-2):
def x(_sad,sda_,m=+3, n=-2):

cases it don't work:
def (m, x=y)

what I did:
^def\s\w+\((\w\,)*(\w+=?\+?\-?\d+\,)*(\w)*\):$

However, it doesn't pass the case "def f(a=1):" and "def g(a=-2):"
Where I did wrong??
My object here is to fulfill these cases:
def h():
def f(a=1):
def g(a=-2):
def x(_sad,sda_,m=+3, n=-2):

and not fulfill these cases:
    def (m, x=y)

A: Just for fun
\s*def\s+[^\(]+\([^\)]*(?:(?:\([^\)]*?\))[^\)]*)*\):

Regex demo
Explanation:
^: Start of string or start of line depending on multiline mode
\s: "whitespace character": space, tab, newline, carriage return, vertical tab sample
+: One or more sample
\w: "word character": ASCII letter, digit or underscore sample
*: Zero or more times sample
Input:
def h():
def f(a=1):
def g(a=-2):
def x(_sad,sda_,m=+3, n=-2):
def (m, x=y)
def name(database_name):
    def name(name1, name2):
        def name(name1, attr=value):
    def name(name1, default='', length=default, **value):
    def name(name1, default='', length=(0, 999), **kwargs):

Match all except def (m, x=y)


text:
Q: linux how to find out which program connect to remote port See the output below:
tcp   0   0   192.168.2.222:35774   192.168.3.200:9090   TIME_WAIT

On  Linux I want to find out which program connects to  192.168.3.200:9090, how can I achieve this?

A: you can do netstat -anp.
You'll need to sudo or be root to see the process information.
tcp   0   0   0.0.0.0:22   0.0.0.0:*   LISTEN   665/sshd

A: netstat -avnp | egrep '^tcp' | fgrep '192.168.3.200:9090'

A: I think
# lsof -Pnl +M -i4 // Listens on all IPV4 Ports

or
# netstat -ntp

are the commands you are searching for.
Then try to use fgrep to find the line. (in your case: fgrep '192.168.3.200:9090')
--> netstat -ntp | fgrep '192.168.3.200:9090'


text:
Q: No service worker in navigator on iOS Safari 11.3 I'm trying register a service worker for my app on iOS Safari version 11.3 (that added service workers) but there is no service worker object present in the navigator. Here is what navigator looks like:

I also tried running the app on OSX Safari 11.3 with the same results. What could I be missing here? If it is relevant I am using the default create react app service worker registration file, which doesn't do anything right now because there is no service worker in the navigator object.
Thanks!

A: Service Worker can only work on Https and localhost sites. If navigator does not have serviceWorker, please check