text:
Q: Java Singleton Questions I was thinking about making my code a bit cleaner and started to use
the "Singleton Syntax" to access the "main" class of another package...
Like a Modular System.
Here is my problem:
I have a package "config" and "console". The main classes of the packages are ConfigModule and ConsoleModule both extending the abstract class Module.
Now I want to write the "getInstance()" Method for the Module class. This is how it would look for one class.
private static ConfigModule module;

public static ConfigModule getInstance() {

    if(module == null) {
        module = new ConfigModule();
    }

    return module;
}

The problem is I want to make it for the abstract module class... I thought about using generic but thats much confusing with static methods. So thats what I have worked out so far:
private static T module; //That wont work.. Do you have an idea?

//To return type: If I call ConfigModule.getInstance().custom an ide cant find the method... my mistake?
public static <T extends Module> T getInstance() {

    if(module == null) {
        module = new T; //Nope... not even close.. but how?
    }

    return (T) module; //Its unchecked.. can I check it?
}

I hope you can help me... I googled alot but didnt find a solution.


text:
Q: Move many files around without confusing git's rename detection heuristic I have a git repo of a larger Java codebase (~3000 classes), and I want to apply a large reorganization to the whole codebase which will move many classes to other places, rename them, and adjust the references in other classes accordingly. The actual code transformation is scripted and well-tested and I can run it in a few seconds.
Now when I commit the whole thing, git will show many deleted and new files, as the number of moved files exceeds some rename detection limit. That would make 'git annotate' useless in the future, which I would like to avoid if possible.
How can I do the reorganization, and still keep meaningful file histories?

A: When Git walks from one commit to another and compares the two trees, it puts all the "missing" and "added" files into pairing queues (which then determine how much CPU time and memory is thrown at the problem of dynamically recovering the renames from inexact file matches—exact file matches go very fast and shrink the pairing queue length and hence reduce this upper bound).  The maximum length of the pairing queue is the diff.renameLimit setting.
The default value for this was originally 100, then raised to 200 in 2008 (commit 50705915eae8, Git version 1.5.6), then to 400 in 2011 (commit 92c57e5c1d29, Git version 1.7.5).  It probably deserves another doubling by now, but if your Git is at least 1.7.5, committing 400 such renames at a time will preserve rename-finding across individual commits.
Note, however, that this depends on Git examining adjacent commits, so that there are only 400 such changes in the tree.  If you skip directly from an early version to a late version—as, e.g., happens during git merge, or if you git diff an early tag against a late tag—the number of unpaired file names may be much larger and hence overflow the pairing queues.  The queue lengths for git merge are larger by default but are still not 3000.
You can configure higher rename detection thresholds.  Setting diff.renameLimit to zero means "use the maximum possible": not quite no limit, but as close as Git can get.

redpajama_set_name: RedPajamaStackExchange


text:
Q: import understand (from sciTools) gives ImportError: DLL load failed: %1 is not a valid Win32 application I'm trying to use the Understand api for Python.
import understand

I've already checked

*

*ImportError: DLL load failed: %1 is not a valid Win32 application
and

*

*ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there
but they don't apply to my situation, as I already have the PYTHONPATH environment variable pointing to the correct location of understand.pyd, and also the url for unufficial python APIs does not contain the Understand api for python.
Any suggestion is much appreciated.

A: Installing a 32-bit version of Python and SciTools Understand, fixed the problem.

A: You've installed a 64 bit package for 32 bit Python.


text:
Q: Objective-C Download Manager for iPhone I'm trying to write a library for the iPhone that will only be used internally with my company (at least that is the plan for now), and I'm working on a 'Download Manager'. I can download files without issue, but I would like support for pausing and resuming downloads. Currently I use the NSURLConnection class which supports starting and completely canceling downloads, but I can change that if it turns out that it doesn't support pausing/resuming.
Any ideas?

A: You should check out Erica Sadun's Cookbook on Asynchronous downloads here. If you are download large files (200 mb +), there would most likely be a memory crash in which case you would have the save the files as it is being received. For now though, check out the source code.


text:
Q: Is it ok to use a function to output the text domain name in a wordpress theme I am working on a theme and I want to make it available for translating. I have not been including a text domain on translated text because I don't know what the text domain is going to be yet. I figured, until I can come up with a name for my theme I should just use a function to output my text domain name instead of hard coding it on translated text.
EXAMPLE:
This is the traditional way of adding a text domain:
echo _e('Hello', 'my-theme-name');

my approach is like this:
function text_domain() {
   define('TEXT_DOMAIN', 'my-theme-name', true );
   echo TEXT_DOMAIN;
}

and using like this:
 echo _e('Hello', text_domian());

...and when I do come up with a name for my theme I can just update it in one place instead a bunch of times in every file.
THE QUESTION IS: Is this an ok way to do it and will I encounter problems getting my theme approved by the WordPress theme review team?

A: No, this is not okay. NO NO NO. Here's my favourite Otto quote:

Inside all translation functions, no PHP variables are allowed in the
  strings, for any reason, ever.

Otto explains this in more detail, but the simple way to say it is that translation calls are parsed, not executed . So your variable  (let alone your function) may not be evaluated and the text-domain breaks.
So, you're better off using a unique name like wpse241589 for your textdomain temporarily and do a search and replace once you have a better name.


text:
Q: Class declaration within a function declaration Consider the following example:
#include <iostream>

void foo(class B, B *b);

B *c; //OK

int main(){ }

DEMO
The Standard N4296::3.3.2/7.1 [basic.scope.pdecl]

— for a declaration of the form
class-key attribute-specifier-seqopt identifier;
the identifier is declared to be a class-name in the scope that
  contains the declaration

, but according to N4296:3.3.4/1 [basic.scope.proto]

In a function declaration, or in any function declarator except the
  declarator of a function definition (8.4), names of parameters (if
  supplied) have function prototype scope, which terminates at the end
  of the nearest enclosing function declarator.

So, the class B should have been introduced in the function prototype scope. And the scope of B should have been up to the end of the foo's declarator. But the name is visible in the global scope. Why?

A: You are quoting the wrong bullet in 3.3.2 [basic.scope.pdecl]/p7. The class B in the declaration of foo is not of the form class-key attribute-specifier-seq_opt identifier; - there is no semicolon.
Instead, the second bullet applies:

for an elaborated-type-specifier of the form
class-key identifier
if the elaborated-type-specifier is used in the decl-specifier-seq
  or parameter-declaration-clause of a function defined in namespace
  scope, the identifier is declared as a class-name in the namespace
  that contains the declaration; otherwise, except as a friend
  declaration, the identifier is declared in the smallest namespace or
  block scope that contains the declaration.

Hence, the elaborated-type-specifier class B in your example declares B as a class-name in the namespace containing the declaration of foo - i.e., the global namespace.


text:
Q: magento 1.8 bundle product get 2 highest product price I am trying to create a bundle product here i just show final price as highest 2 product prices.
For example

*

*Product-1 price Rs. 100

*Product-2 price Rs. 200

*Product-3 price Rs. 300

Final price is Rs. 500
For the above  final price = (Product-2 + Product-3) as Rs. 500 /-
How can i show that in bundle products view & list pages.
Thanks in advance...!


text:
Q: Proof of a proposition regarding recursive definitions (from Terence Tao's Analysis I) I'm currently reading Terence Tao's book Analysis I, and I got stuck on his proposition 2.1.16 about recursive definitions ; actually, I don't understand his (informal) proof of it.
First, here are the five Peano axioms he's using :

Axiom 2.1. $0$ is a natural number.
Axiom 2.2. If $n$ is a natural number, then $n{++}$ is also a natural number.
Axiom 2.3. $0$ is not the successor of any natural number ; i.e., we have $n{++} \ne 0$ for every natural number $n$.
Axiom 2.4. Different natural numbers must have different successors ; i.e., if $n, m$ are natural numbers and $n \ne m$, then $n{++} \ne m{++}$. Equivalently, if $n{++} = m{++}$, then we must have $n=m$.
Axiom 2.5. (Principle of mathematical induction). Let $P(n)$ be any property pertaining to a natural number $n$. Suppose that $P(0)$ is true, and suppose that whenever $P(n)$ is true, $P(n{++})$ is also true. Then $P(n)$ is true for every natural number $n$.

And here is the proposition, and the proof I'm stuck on :

Proposition 2.1.16 (Recursive definitions). Suppose for each natural number $n$, we have some function $f_{n} : \mathbb{N} \rightarrow \mathbb{N}$ from the natural numbers to the natural numbers. Let $c$ be a natural number. Then we can assign a unique natural number $a_{n}$ to each natural number $n$, such that $a_{0} = c$ and $a_{n{++}} = f_{n} (a_{n})$ for each natural number $n$.
Proof. (Informal) We use induction. We first observe that this procedure gives a single value to $a_0$, namely $c$. (None of the other definitions $a_{n{++}}:= f_{n} (a_n)$ will redefine the value of $a_0$, because of Axiom 2.3.) Now suppose inductively that the procedure gives a single value to $a_n$. Then it gives a single value to $a_{n{++}}$, namely $a_{n{++}}:= f_{n} (a_n)$. (None of the other definitions $a_{m{++}}:= f_{m} (a_{m})$ will redefine the value of $a_{n{++}}$, because of Axiome 2.4.) This completes the induction, and so $a_n$ is defined for each natural number $n$, with a single value assigned to each $a_n$.

I don't understand how does that prove anything. I feel like all he's saying is that « all natural numbers are different from each others » ; I don't understand why we couldn't have, for example, $a_0 = a_1 = c$ (for instance, if we consider the Fibonacci sequence : $0, 1, 1, 2, ...$, we have $a_1 = a_2 = 1$).
I actually found another proof of uniqueness on Wikipedia (regarding the Recursion theorem) and I think I understood it, but I really would like to understand Tao's point of view as well.
Finally, shouldn't we prove that such a function exists as well, instead of just supposing it exists ? I found this document which gives a proof for the existence of such a function (at pages 2-3), but I'm a little bit confused about the way they do it: can we really "imagine" or "create" such sets as $S$ and $g$, like they do, and draw conclusions from them? Another thing that disturbs me regarding their approach is that Tao doesn't talk about sets before chapter 3, and the proposition above comes from chapter 2... so the question here is: how could we prove the existence of such functions as the ones described in the recursion theorem without knowing anything about sets and set theory?
So, as you can see... I'm pretty confused about a lot of things. Any help would be greatly appreciated!

A: The proposition states that if we have a countably family of functions
$$\{ f_n \mid f_n : \mathbb{N} \rightarrow \mathbb{N}, n \in \mathbb{N}\}$$
then we can always, by choosing a seed $c \in \mathbb{N}$, use the family to define a unique sequence of natural numbers $\{ a_k \}_{k \in \mathbb{N}}$ given by

*

*$a_0 = c$

*Otherwise, $a_{n++} = f_n(a_n)$
For an example of such a sequence, consider the family where $f_n(x) = x^2 + n$. Let $c = 2$; then we get the sequence
$$ \{ 2, 2^1+1, (2^1+1)^2+2, \ldots \} = \{ 2, 3, 11, 124, \ldots \}$$
The proof of uniqueness relies on Axiom 2.5; the property $P(n)$ is
$P(n)$: For all $n \in \mathbb{N}$, $a_n$ is uniquely defined.
$P(0)$ holds, since there is precisely one clause defining $a_0$.
Now we show that if $P(n)$ is true, then so is $P(n{++})$.
So we must show that $a_{n++}$ is uniquely defined. Axiom 2.3 tells us that we cannot have used the first clause, $a_0 = c$, to define $a_{n++}$, so we must have used the second clause, $a_{n++} = f_n(a_n)$, to define $a_{n++}$. But since $a_n$ is uniquely defined and $f_n$ is a function, the value $a_{n++}$ is also unique. This completes the proof.


text:
Q: Pre-1978 sci-fi novel involving life under an Asian occupation of US Just in case: it's not the "Man in the High Castle"! ;) -- which was published much earlier.
This science fiction story (may have been a novella), from what little I recall, involved the aftermath and description of at least a partial occupation of the US by an Asian nation (not certain if Chinese, Japanese, Korean) and resistance/life under occupation. The technology and setting, I believe, is typical 1970s-era (i.e., no spaceships/laser pistols).
This was very probably published in the 1970s, definitely before 1978, and is a relatively obscure title as I have never seen it anywhere (I might not have recognized it if I saw it though)  - not that I've been looking for it but I read SF a lot and scan titles and lists of sci fi books from different eras frequently). I seem to recall it being a bit grittier and more adult (some sexual content) in tone than a typical sci-fi novel for teens.

A: I think that's probably Arslan (UK title A Wind from Bukhara) by M J Engh, first published in 1976. It's a somewhat improbable novel in which nomadic tribes from central Asia conquer the world (as they did under Genghis Khan), and their leader establishes his world capital in a small town in Illinois. It's certainly grittier and more sexual than a 1970s teen novel would have been.

A: You may be thinking of Not This August by C.M. Kornbluth. It was first published in 1955, but I remember it being republished in the 1980 timeframe (This version, specifically). Ifsdb entry.
The story opens just after the US has surrendered to Russian and Chinese Communist forces. The protagonist is a farmer, and the first part of the book takes place on his farm as the occupying forces begin converting the country over to a socialist government. Eventually, the protagonist takes on a farm hand who is more than he appears.
One memorable bit from the latter part of the book is that it becomes common to hand someone a penny and say "Christmas Eve".

The farm hand turns out to be a refugee from a secret local military base, where the US was building a secret weapon. The refugee had killed everyone on the base to protect it from spies, and has PTSD from the events. Eventually, the farmer and another man begin travelling the country as bums, finding people to reopen the base and generally organizing a rebellion. The sign of the rebellion is handing someone a penny and saying "Christmas Eve".

A: Could it be Heinlein's The Sixth Column aka The Day After Tomorrow?  This features the United States being conquered by "PanAsians".  It's a bit early, 1949, but it's been reprinted so many times.
The resistance discovers an electro-magnetic-gravitational mumbo-jumbo magic that can do pretty much anything the author wants (hey, it's early Heinlein).  They found a religion (the PanAsians allow free religion) and use their techno-magic to appear as genuine prophets.


text:
Q: Как сделать анимированный фон в Python Я делаю простенькую игру в python с использованием библиотеки arcade, где нужно за машину уклоняться от препятствий, и мне нужно сделать анимированный фон(дорогу). Какая команда поможет мне это сделать?
Вот код игры:
import arcade
import random
class Car(arcade.Sprite):
    def update(self):
        self.center_x+=self.change_x
class Game(arcade.Window):
    def __init__(self,width,height,title):
        super().__init__(width,height,title)
        self.bg=arcade.load_texture("Road.png")
        self.car=Car("blue_car.png",1)
        self.car.bottom,self.car.center_x=100,270
    def on_draw(self):
        arcade.draw_texture_rectangle(250,400,500,790,self.bg)
        self.car.draw()
    def update(self,delta_time):
        self.car.update()
    def on_key_press(self, key, modifiers):
        if key==arcade.key.LEFT:
            self.car.change_x=-10
        if key==arcade.key.RIGHT:
            self.car.change_x=10
    def on_key_release(self, key, modifiers):
        if key==arcade.key.LEFT:
            self.car.change_x=0
        if key==arcade.key.RIGHT:
            self.car.change_x=0
window=Game(500,800,"Гонки")
window.run()


text:
Q: Best way to generalize a distribution of data into smaller subsets? Suppose I had a data set as follows:

168.95, 176.83, 178.13, 179.61, 179.44, 172.83, 173.37, 174.06, 174.94, 175.43, 175.73, 175.5, 173.78, 174.06, 172.71, 174.3, 178.38, 178.43, 177.18, 175.34, 176.16, 177.03, 178.2, 178.19, 176.42, 177.4, 178.15, 173.1, 173.4, 174.42, 173.87, 171.85, 172.37, 172.73, 172.28, 173.65, 172.35, 171.66, 172.8, 171.97, 168.56, 168.74, 168.38, 169.78, 169.79, 170.07, 171.57, 169.46, 169.32, 170.3, 154.83, 171.33, 169.61, 170.08, 170.11, 170.22, 172.16, 169.64, 169.86, 170.56, 171.64, 166.91, 167.93, 170.35, 170.56, 168.16, 168.41, 170.54, 168.89, 168.03, 169.28, 169.47, 171.24, 169.15, 170.43, 168.36, 169.19, 168.58, 168.67, 169.19, 167.69, 168.4, 168.27, 167.89, 168.18, 168.91, 168.16, 168.98, 168.79, 166.87, 168.36, 170.22, 168.36, 169.01, 168.45, 168.73, 168.24, 170.12, 169.13, 168.95, 169.06, 168.47, 168.68, 170.22, 170.04, 167.92, 168.38, 168.14, 169.27, 170.31, 168.68, 170.59, 168.95, 170.35, 152.99, 153.69, 156.8, 156.45, 156.03, 156.01, 156.63, 156.68, 155.33, 156.31, 155.65, 154.64, 156.02, 155.94, 154.5, 154.53, 154.81, 156.15, 155.58, 155.55, 154.54, 154.66, 155.09, 155.99, 155.27, 155.11, 155.22, 155.98, 156.04, 153.86, 158.48, 158.34, 158.3, 159.29, 158.4, 158.69, 159.17, 159.13, 158.02, 158.7, 157.94, 158.81, 159.14, 159.1

And another data set as follows:

125.14, 130.07, 130.45, 127.8, 128.12, 128.3, 129.18, 128, 127.84, 128.4, 128.86, 128.95, 128.29, 129.24, 128.33, 127.9, 128.96, 127.96, 128.08, 128.96, 128.6, 129.27, 128.74, 129.82, 129.72, 129.65, 130.12, 129.02, 129.8, 129.5, 129.51, 129.97, 129.95, 130.45, 130.51, 130.51, 129.44, 128.42, 129.33, 128.65, 129.15, 129.71, 128.63, 130.17, 128.96, 127.8, 128.12, 128.3, 129.18, 128, 127.84, 128.4, 128.86, 128.95, 128.29, 129.24, 128.33, 127.9, 128.96, 127.96, 128.08, 128.96, 128.6, 129.27, 128.74, 129.82, 129.72, 129.65, 130.12, 129.02, 129.8, 129.5

If you are not allowed to filter or sort the data, as they correspond to real-world, real-time values, what algorithmic method would you suggest to group the data into the least number of statistically significant groups, that can be used for both data sets (and possibly more)?
My initial idea was to take a global mean, standard deviation and variance, then split the groups into two and take local values for the aforementioned. I would then compare the two values and if they fell below par, the group(s) that failed the comparison would be further split into two. This would keep on going until the standard deviation and variance within the groups was small enough so as to not pose a statistical bias.
If anyone can think of a method that is more computationally efficient and/or mathematically rigorous, I would appreciate it greatly.
Also, I am new to numerical methods in general and would welcome any advice you had in this endeavor.

A: The example you give may be misleading because by eyeball it looks likes the two datasets are already separated into two significantly different groups.
If your question is, what if the two datasets were one big dataset and you needed an algorithm to discover these two groups, then the answer is you want to look up clustering methods. Wikipedia actually has a very nice write up on k-means clustering, which is a good place to start. http://en.wikipedia.org/wiki/K-means_clustering


text:
Q: Possible MAC conflict in ESX I have two virtual machines that are 10.1.1.10 and 10.1.1.20 in an ESX.
I try to access theses machines by another network 192.168.1.0/24.
The problem is that when I can ping one machine, I can not ping the other one. And conversely.
Me -> A : Yes
Me -> B : No
and
Me -> A : No
Me -> B : Yes
The machines have different IP addresses and different MAC addresses.
I can not understand what is happenning right here.
Note : When a machine can not be ping, it can not ping its gateway.
Note 2 : When a machine can not be ping, I can not see any traffic comming whith a tcpdump.
Note 3 : Everything is right regarding the firewalls between my networks.
Could you please help me ?

A: Problem was port-security. Only one MAC address was allowed to use the port. Set to more than one.


text:
Q: Matlab code to minimize multivariate function I have a function of two variables in Matlab and want to minimize the function over those two variables.
I have three datasets, ds1, ds2, and ds3. I define new variables that are indicator functions of a 2-element vector x, and other variables that appear in all of the datasets, varA and varB.
newvar1 = @(x)double(((ds1.varA + 1000).^0.5)/3 - x(1) - x(2)*(ds1.varB).^2 > (ds1.varA.^0.5)/3);
newvar2 = @(x)double(((ds2.varA + 1000).^0.5)/3 - x(1) - x(2)*(ds2.varB).^2 > (ds2.varA.^0.5)/3);
newvar3 = @(x)double(((ds3.varA + 1000).^0.5)/3 - x(1) - x(2)*(ds3.varB).^2 > (ds3.varA.^0.5)/3);
I want to minimize the following function with respect to x. It is the sum of squares of the difference between each new variable and the existing varC in each dataset:
Fcn = @(x) ((mean(ds1.varC, 1) - mean(newvar1(x), 1))^2 + (mean(ds2.varC, 1) - mean(newvar2(x), 1))^2 + (mean(ds3.varC, 1) - mean(newvar3(x), 1))^2);
I use fminsearch to minimize the above function
fminsearch(Fcn, [0.5 3])
but it returns the input values, no matter what I use. Is there something I'm doing that's preventing it from minimizing over all possible values of x?


text: Q: How does the apple website show different content, depending on your internet speed? I would have phrased this question as 'How do websites measure the client internet speed?' or something. But I feel that this is a much more concrete example, and provides the correct context in which the core question occurred to me.


text:
Q: Move worksheet within a workbook to the end With xlwings, I am trying to move a worksheet within a workbook to the end. For example, a workbook contains a collection of the following sheets:
Sheet1, Sheet2, Sheet3
How can I move Sheet1 after Sheet3 in order to get the following order?
Sheet2, Sheet3, Sheet1
If I use ws1.api.Move(Before=ws3.api) with the Before parameter the line works as expected, but it doesn't with the After parameter. See example code:
import xlwings as xw

wb = xw.Book("test.xlsx")

ws1 = wb.sheets['Sheet1']
ws3 = wb.sheets['Sheet3']

ws1.api.Move(After=ws3.api)

A: I found the solution myself, this question is already answered here. You have to add None before the After parameter:
import xlwings as xw

wb = xw.Book("test.xlsx")

ws1 = wb.sheets['Sheet1']
ws3 = wb.sheets['Sheet3']

ws1.api.Move(None, After=ws3.api)
# Or: ws1.api.Move(Before=None, After=ws3.api)

Strictly speaking, the question seems to be more related to pywin32 than to xlwings, because apparently .api  accesses the underlying pywin32 objects, as described here.


text:
Q: Accessing CheckBox in GridView How does one access the CheckBox.Checked value in an ASP.NET GridView? I want to select a bunch a records and then delete them.
What I've tried for testing is just to see if I can make the label change:
<Columns>
    <asp:TemplateField>
        <ItemTemplate>
            <asp:CheckBox ID="CheckBox1" runat="server" />
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

C#
protected void Buttondelete_Click(object sender, EventArgs e)
{
   Label1.Text = "first";

   foreach (GridViewRow item in GridViewDelete.Rows)
   {
       CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
       if (chk != null)
       {
           if (chk.Checked)
           {
               Label1.Text = "second";
           }
       }
    }
}

I only get the "first" to go off.


text:
Q: Modify page number position in svmono class As in the title, I would like to know how I should modify the svmono class in order to have the page number centered down (right now they are on the top left/right of the page).
Any feedback will be most welcome.
Thank you in advance for your time.

A: You have to redefine both the bchap and headings page styles.
\documentclass[envcountsame,envcountchap]{svmono}
\usepackage{kantlipsum}

\makeatletter
\def\ps@bchap{%
  \let\@oddhead\@empty\let\@evenhead\@empty
  \def\@oddfoot{\reset@font\small\hfil\thepage\hfil}%
  \let\@evenfoot\@oddfoot
}

\def\ps@headings{%
  \let\@mkboth\markboth
  \def\@oddfoot{\reset@font\small\hfil\thepage\hfil}%
  \let\@evenfoot\@oddfoot
  \def\@evenhead{\runheadsize\runheadstyle\hfil\leftmark}%
  \def\@oddhead{\runheadsize\runheadstyle\rightmark\hfil}%
  \def\chaptermark##1{%
    \markboth{%
      {\if@chapnum\thechapter\thechapterend\hskip\betweenumberspace\fi ##1}%
    }{%
      {\if@chapnum\thechapter\thechapterend\hskip\betweenumberspace\fi ##1}}%
    }%
  \def\sectionmark##1{%
    \markright{%
      {\ifnum\c@secnumdepth>\z@\thesection\seccounterend\hskip\betweenumberspace\fi ##1}%
    }%
  }%
}
\makeatother
\pagestyle{headings}

\begin{document}

\chapter{Test}

\kant[1-10]

\end{document}


text:
Q: My static map is always empty I declared a static unordered map in a header file as follows:
static boost::unordered_map<KeyAction, sf::Key::Code> WindowKeyMap;

in that same header file, i have a function that fills the map with some values:
static void Initialize(std::string &file)
{
    WindowKeyMap[MoveLeft] = sf::Key::Code::Left;
    WindowKeyMap[MoveRight] = sf::Key::Code::Right;
    WindowKeyMap[MoveUp] = sf::Key::Code::Up;
    WindowKeyMap[MoveDown] = sf::Key::Code::Down;
    std::cout << std::endl << WindowKeyMap.size() << std::endl;
}

Later on in my program, inside a seperate class/function, i attempt to read one of the values:
std::cout << std::endl << WindowKeyMap.size() << std::endl;
auto test2 = WindowKeyMap[MoveRight];

but the map is always empty. The output to the console is always 4 from the initialize routine then 0 from the second cout. I thought static maps were persistent across the program, so I'm a little confused as to how my static map becaomes empty. Can anyone shed some light?
Thanks

A: When you declare your variable in the header like that each compilation unit (*.cpp) gets it's own local static copy. You have to declare it extern
extern boost::unordered_map<KeyAction, sf::Key::Code> WindowKeyMap;

and in one cpp put
boost::unordered_map<KeyAction, sf::Key::Code> WindowKeyMap;

A: Simple: just don't do it. While you can get rid of the initialization and scope as suggested by @Eelke, you will shoot yourself in the foot in the long term... Do you really want to have the hash table accessible by everybody and everywhere? Do you really accept the risk of uncontrollable access to the (apparently important) data? Do you really want to have an untestable global state all across your application? Do you really want to have all the dependencies introduced by <unordered_map> pulled into many translation units of your program? I could continue like that for a while but the point is: Wrap the logic and data into a class and provide the service via an interface. Create the instance of the interface via a factory or dependency container and manage the lifetime of that object explicitly.
Regards,
Paul


text:
Q: Refernce ID's on a query which fetch assoc and result do not work on
$id = $_SESSION['user_id'];

$query1 = mysql_query("SELECT `user_name` FROM `users` WHERE `id` LIKE '$id'");

echo $query1;

if (mysql_num_rows($query1) == 0)
    die ("User not found");
else {
    $username = mysql_result($query1);
    echo $username ;
}

Could someone tell me why i'd keep getting resource ID's and then 'array' echoed out?! I've tried fetch assoc and MySQL fetch and still nothing unfortunately :( I've read through the manual and still no joy!

A: Are you trying to display the value in the "user_name" column? If so, you need a loop that looks like this:
while($row = mysql_fetch_array($query1)) {
    $username = $row['user_name'];
    echo "user_name = " . $username;
}

Place it inside your "else" block, replacing what's currently inside it. The way you did it, your $username variable is getting the Result Set object, not the data inside it.

A: You can use mysql_result, but you have to specify the row number as a second parameter
mysql_result($query1, 0);

http://www.php.net/manual/en/function.mysql-result.php
Or you can do...
$id = $_SESSION['user_id'];

$query1 = mysql_query("SELECT `user_name` FROM `users` WHERE `id` LIKE '$id'");

if (mysql_num_rows($query1)==0){
    die ("User not found");
}

while($row = mysql_fetch_array($query1)){
echo $row['user_name'];
}

By the way you do not have to use LIKE, rather = would be good.


text:
Q: Bottom navigation not working. How to resolve this issue? I have made the code to do that it loads fragment on clicking the items in the bottom navigation but when I click on it they don't work. I tried many times to check whats the problem even though Android Studio couldn't find it bu the app isn't working. I don't know whats the issue.
My main activity -
public class MainActivity extends AppCompatActivity {
    BottomNavigationView btm_view;

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

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = manager.beginTransaction();
        fragmentTransaction.add(R.id.container, new Chats());
        fragmentTransaction.commit();

        btm_view = findViewById(R.id.bottom_view);
        btm_view.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                if (item.getItemId() == R.id.camera) {
                    FragmentManager manager = getSupportFragmentManager();
                    FragmentTransaction fragmentTransaction = manager.beginTransaction();
                    fragmentTransaction.add(R.id.container, new Camera());
                    fragmentTransaction.commit();
                } else if (item.getItemId() == R.id.chats) {
                    FragmentManager manager = getSupportFragmentManager();
                    FragmentTransaction fragmentTransaction = manager.beginTransaction();
                    fragmentTransaction.add(R.id.container, new Chats());
                    fragmentTransaction.commit();
                } else if (item.getItemId() == R.id.status) {
                    FragmentManager manager = getSupportFragmentManager();
                    FragmentTransaction fragmentTransaction = manager.beginTransaction();
                    fragmentTransaction.add(R.id.container, new Status());
                    fragmentTransaction.commit();
                } else if (item.getItemId() == R.id.calls) {
                    FragmentManager manager = getSupportFragmentManager();
                    FragmentTransaction fragmentTransaction = manager.beginTransaction();
                    fragmentTransaction.add(R.id.container, new Calls());
                    fragmentTransaction.commit();
                } else if (item.getItemId() == R.id.settings) {
                    FragmentManager manager = getSupportFragmentManager();
                    FragmentTransaction fragmentTransaction = manager.beginTransaction();
                    fragmentTransaction.add(R.id.container, new Settings());
                    fragmentTransaction.commit();
                }

                return false;
            }
        });
    }
}

one of my fragments -
public class Chats extends Fragment {

    public Chats() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_chats, container, false);
    }
}

A: *

*At first use replace(R.id.container, fragment) instead of add.

*Optimise Code

Utilise setOnNavigationItemSelectedListener. Try this way

Set a listener that will be notified when a bottom navigation item is
  selected.

btm_view.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
        openFragment(Camera.newInstance());
      }

      public void openFragment(Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.container, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
      }
      BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener =
          new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) {
              switch (item.getItemId()) {
                case R.id.camera:
                  openFragment(Camera.newInstance());
                  return true;
                case R.id.chats:
                  openFragment(Chats.newInstance());
                  return true;
                case R.id.status:
                  openFragment(Status.newInstance());
                  return true;
                case R.id.calls:
                  openFragment(Calls.newInstance());
                  return true;
                case R.id.settings:
                  openFragment(Settings.newInstance());
                  return true;
              }
              return false;
            }
          };
    }

Your Chats Fragment will be
public class Chats extends Fragment {

    public Chats() {
        // Required empty public constructor
    }

    public static Chats newInstance() {
    Chats fragment = new Chats();
    return fragment;
   }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_chats, container, false);
    }
}

A: Try this way
BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener =
  new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) {
      switch (item.getItemId()) {
        case R.id.chats:
          openFragment(Chat.newInstance());
          return true;
        case R.id.camera:
          openFragment(Camera.newInstance());
          return true;
        case R.id.status:
          openFragment(Status.newInstance("", ""));
          return true;
      }
      return false;
    }
  };


text:
Q: Lifetime of multiple instances of an object / design pattern help I am new to programming and am having difficulty with understanding object lifetime / instantiation.
I have a windows from with a datagridview and a panel.
The datagridview has a checkbox column and a list of names which is populated from a database.
The panel has a few text boxes (e.g. name, age, favourite sports team) and a 'save changes' button.
The idea is that when the user selects a person in the datagridview by checking the appropriate checkbox then the panel shows the relevant data for that person (name, age, fav sports team) by pulling the data from a database. If the user would like to update the person's details they can do so by typing in the textboxes and then clicking the 'save changes' button. All quite simple so far.
The way I have designed this is to have a 'panel' class and to create an instance when the user checks a checkbox.
(NB - the reason I have created a 'panel' class is that I intend to replicate the datagridview and panel on other tabpages within my form and thought it would be useful to have a generic 'panel' class that I could re-use.)
My code looks a bit like this:
If CheckBoxClicked Then
Dim UpdatePanel As New UpdatePanel(MyForm.NameTextBox, MyForm.AgeTextBox, MyForm.FavSportTeamTextBox, MyForm.SaveButton)
UpdatePanel.GetData()
...

When the user clicks the SaveButton the data is updated to the database and I have a display message (simple textbox) which says "Update successful" and displays for 5 seconds before hiding itself.
Here is the problem:
Suppose a user checks a checkbox, reviews the data and does not make any changes, and then checks another checkbox and decides to update the data by clicking the 'save changes' button. What happens is that the "Update successful" message is displayed twice.
I think this is because every time the user checks a checkbox an instance of UpdatePanel is created. If a I select five different people using the checkboxes and then hit 'save changes' I get five "Update successful" messages.
I am not sure how to overcome this. It feels like each time a checkbox is clicked I need to check if an instance of UpdatePanel exists and then destroy it. I tried using UpdatePanel = Nothing and also investigated IDisposable and GC.Collect() but with no luck.
My questions are:

*

*How can I ensure that only one
    instance of the panel is created?

*If I create multiple instances of
        the same object with the same name
        do they all sit in memory or does
        the 'computer' only retain a
        reference to the most recently
        created? (Is there not a name
        conflict?)

*Have I gone down the
        wrong track with my deisgn pattern
        and use of the 'panel' class?

Thanks

A: Make sure you are checking whether there were any changes or not before updating the db. Probably any time user reviews a data you have something that adds single update. It would be easier to answer if you post more code as your explanations are not very clear and it is difficult to say where the problem is without seeing most of the code involved.

*

*Use the singleton pattern

*It depends on how you creating them. Object created in the method scope is marked to deletion and waits for GC to collect him. If you have your objects stored inside some variable of your WinForm it will keep them from GC. So by default object is dying but you can make it live longer. Also note that GC time is not determined and you never know when GC will do it`s work and destroy the objects.

*Its not clear what was done, so if you post the code Ill be able to answer this.


text:
Q: S3FS inside LXC containers mounted by the host I'm currently using several LXC containers to isolate other users' programs from the host system. The rootfs of each container uses a union file system and a few mount-binds from the host and everything is working correctly.
Now I want to be able to use S3FS to mount an S3 bucket on the host and mount-bind it into a directory on the rootfs of each container. It needs to be mounted by the host because I don't want any of the users in the container to see the aws secret key. This appears to work fine (I am able to see the files in the s3fs mount in the correct place), but once I am inside the container, the s3fs files are no longer visible.
It is visible if it is mounted from inside the container, but again I need it mounted from the host.
Is there a particular setting that I need to configure to get this to work properly, or is it just not possible due to FUSE?

A: You need to bind mount before starting the container. The problem you're currently experiencing is caused by bind mounting after the container has already started. Alternatively, just restart the container.


text:
Q: Trying to attach a save script in unity, serialization not working Hi trying to attach a simple save script into a GameObject (cube) in unity. everything looks fine ( no errors) except for the Serialize part(says 'no overload for method 'Serialize' takes 1 arguments) . can anyone guide me on this?. here is the example of the code. thanks a lot!
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class SavingTheGame : MonoBehaviour {

    public void OnTriggerEnter (Collider collider)
    {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Create(Application.persistentDataPath + "/SaveGame.dat");

           bf.Serialize(file);
            file.Close();
    }
}

A: You are not serializing anything, you need to supply the object you would like to serialize
public void OnTriggerEnter (Collider collider)
{
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/SaveGame.dat");

       // Change here
       var obj = "This Will Be Serialized";
       bf.Serialize(file, obj);

       file.Close();
}

BinaryFormatter.Serialize requires 2 parameters, stream and object
You can follow a nice tutorial on using BinaryFormatter in Unity for saving/loading here: https://gamedevelopment.tutsplus.com/tutorials/how-to-save-and-load-your-players-progress-in-unity--cms-20934


text:
Q: HttpPost, HttpClient The target server failed to respond I cannot connect to my server using HttpClient when Posting, it works fine with get, and works fine with post to other servers (such as google), any ideas?
I am NOT using android.
The server responds fine when accessing it by browser.
As it is probably a server config issue, i do not have full access to the server, it is a hosted webserver, however i have access to the cpanel
private static String GetURL(String inUrl, String post) {
    String inputLine = "";
    try {
        if (!inUrl.contains("http")) {
            throw new Exception("Invalid URL");
        } else {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(inUrl);
            httpPost.addHeader("Accept-Charset", "UTF-8");
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");

            //create post
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("req", post));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = client.execute(httpPost);
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            inputLine = in.readLine();
            in.close();

        }
    }catch (Exception ex) {
        inputLine = "" + Comms.ERROR_COULD_NOT_REACH_SERVER;
        Log.writeLog("Could Not Reach Server: \"" + inUrl + "\"");
        ex.printStackTrace();
    }

    return inputLine;
}

org.apache.http.NoHttpResponseException: The target server failed to respond
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:95)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:62)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:254)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:289)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:252)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader(ManagedClientConnectionImpl.java:191)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:300)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:127)
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:715)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:520)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at Comms.GetURL(Comms.java:87)
at Comms.sendCommand(Comms.java:64)
at Comms.main(Comms.java:43)


text:
Q: Preference Panes no longer open after Big Sur update. Library/PreferencePanes is now completely empty After upgrading to Big Sur, none of the System Preferences panes open. A little hunting around online steered me to the folder, Library/PreferencePanes, which is now completely empty. So I guess there's just nothing to open. On the advice of Apple Support, I've tried reinstalling Big Sur in the hope that it would restore everything, but still nothing. The folder remains empty. I've tried multiple restarts and clearing NVRAM. Weirdly, when I open Timemachine and search for old copies of Library/PreferencePanes to restore, the folder is empty even before the upgrade, back in the good old days when the panes still opened. I'm stuck. Any ideas would be great. Thanks!

A: Make sure you look at the right preference panes folder. There are three of them:

*

*/System/Library/PreferencePanes This folder includes all the panes which are shipped with macOS. It definitely should not be empty.

*/Library/PreferencePanes Here you can install third-party panes which should be available for all users of your Mac.

*/Users/yourusername/Library/PreferencePanes Here you can install third-party panes which should be available just for "your" user.

Use Finder and select "Go to" – "Go to folder..." and enter one of the path names. Finder will then show you wether it is empty. The last two can be empty, but the first one not.
If the first one isn't empty, try to add another admin user using the steps in this answer and see if this user can open the preference panes.
If it is empty, you should try to install the system again, checking the disk first by booting into recovery mode. Press Command-R during startup to do this.

A: This is a rare situation where the three sets of files are correct, yet the app won't run for a user.
To triage this I would do the following:

*

*Make a good full backup - check your important files and do a restore of one or several to be sure you can get workable files from the backup.

*Make a new user on the mac - this will be challenging without the User Preference Pane and involves recovery mode options so this is optional. You might have luck starting in safe mode for your hardware type or trying to remove the /var/db/.AppleSetupDone file and restarting.

*Erase the Mac and install Big Sur (or whatever OS you want).

If you can't get preference panes up after an erase, you either didn't erase all the content or have a hardware / download problem. If it works, then you can decide to restore files from the user account as needed from backup.


text:
Q: why MS Access2013 is giving "you must enter a value in 'Desc' field" when there is a value already? I'm new to MS Access and Sharepoint. I've a requirement to link to a sharepoint list within Access (2013) and Insert new record in this linked table (the table which gets created in the Access when we link the sharepoint list). The linked table has multivalued columns. So I'm using the recordset approach to run the INSERT query. Below is what I'm doing.
Option Compare Database
Sub Insert_Query()

Dim dbs As DAO.Database
Dim rs_parent As DAO.Recordset2
Dim rs_child As DAO.Recordset2

Set dbs = CurrentDb
Set rs_parent = dbs.OpenRecordset("TABLENAME")

With rs_parent
.AddNew
![T1] = "test_title"
![W1] = "test_w"
![P1] = "Low"
![A1] = "saleem, Shaik"
![Desc] = "test description"        'LongText type field 'Required Field

Set rs_child = rs_parent![Assigned To].Value
With rs_child
rs_child.AddNew
rs_child!Value = 3160
rs_child.Update
rs_child.Close
End With
rs_parent.Update   'Getting run time error 3314(You must enter a value in  'Desc' Field) on this line

rs_parent.Close

End With

End Sub

I've tried changing rs_parent![Desc] to rs_parent.Fields("Desc") and rs_parent.Fiedls(7)---> 7 is the item number in that collection, but all of them are giving the same error.
Any idea what could be the reason for the error and how to fix it please? Feel free to ask me if you need any further information.
Edit: The above error comes only when I execute the procedure when Access is 'online with Sharepoint'. But The same code works just fine if I convert the TABLENAME  into a local table and execute the procedure.


text:
Q: CSS animations are not working when added by Javascript I am trying to make a burger Icon button.
When you click it, the top and bottom lines are supposed to move to the left, and the middle one is supposed to disappear, but when I click it nothing happens. I've already turned on the JavaScript in the browser and that didn't work. I thought it was the code editor so I downloaded atom (I usually use VS code) but that didn't work also.

const menuBtn = document.querySelector('.menu-btn');
let menuOpen = false;
menuBtn.addEventListener('click', () => {
    if(!menuOpen){
        menuBtn.classList.add('open');
        menuOpen = true;
    } else {
        menuBtn.classList.remove('open');
        menuOpen = false;
    }
});
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box
}

body {
    background: #272727;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}

.menu-btn {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 80px;
    height: 80px;
    cursor: pointer;
    transition: all .5s ease-in-out;
    border: 3px solid #fff
}

.menu-btn__burger {
    width: 50px;
    height: 6px;
    background: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgb(255, 101, 47, .2);
    transition: all .5s ease-in-out;
}

.menu-btn__burger::before,
.menu-btn__burger::after {
    content: '';
    position: absolute;
    width: 50px;
    height: 6px;
    background: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(255,201,47,.2);
    transition: all .5s ease-in-out;
}

.menu-btn__burger::before {
    transform: translateY(-16px);
}

.menu-btn__burger::after {
    transform: translateY(16px);
}

/* ANIMATION */
.menu-btn.open .menu-btn__burger {
    transform: translateX( -50px);
    background: transparent;
    box-shadow: none;
}

A: It worked just fine as it was... but you could shorten it with one-liner:

const menuBtn = document.querySelector('.menu-btn');
let menuOpen = false;
menuBtn.addEventListener('click', () => {
    menuBtn.classList.toggle("open", menuOpen = !menuOpen)
});
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box
}

body {
    background: #272727;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}

.menu-btn {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 80px;
    height: 80px;
    cursor: pointer;
    transition: all .5s ease-in-out;
    border: 3px solid #fff
}

.menu-btn__burger {
    width: 50px;
    height: 6px;
    background: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgb(255, 101, 47, .2);
    transition: all .5s ease-in-out;
}

.menu-btn.open
{
  background-color: green;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS hamburger Animation</title>
    <link rel="stylesheet" href="style.css">

A: Your code is Already Fine. It works well. Maybe you forget to refresh the window :)
Also, if you didn't knew already, you could use elem.classList.toggle("class") instead of if-else condition.

const menuBtn = document.querySelector('.menu-btn');
let menuOpen = false;
menuBtn.addEventListener('click', () => {
    menuBtn.classList.toggle("open");
    menuOpen = !menuOpen;
});
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box
}

body {
    background: #272727;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}

.menu-btn {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 80px;
    height: 80px;
    cursor: pointer;
    transition: all .5s ease-in-out;
    border: 3px solid #fff
}

.menu-btn__burger {
    width: 50px;
    height: 6px;
    background: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgb(255, 101, 47, .2);
    transition: all .5s ease-in-out;
}

.menu-btn__burger::before,
.menu-btn__burger::after {
    content: '';
    position: absolute;
    width: 50px;
    height: 6px;
    background: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(255,201,47,.2);
    transition: all .5s ease-in-out;
}

.menu-btn__burger::before {
    transform: translateY(-16px);
}

.menu-btn__burger::after {
    transform: translateY(16px);
}

/* ANIMATION */
.menu-btn.open .menu-btn__burger {
    transform: translateX( -50px);
    background: transparent;
    box-shadow: none;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS hamburger Animation</title>
    <link rel="stylesheet" href="style.css">


text:
Q: Mac OS - Swift - Get screen containing the dock I would like to get the screen containing the dock and the menubar.
Is there a way to do this?
I've check Apple documentation about NSScreen but couldn't find any information about that.
Thanks!

A: Actually, the answer was, as @Willeke suggested, in the documentation of NSScreen.screens (see:
https://developer.apple.com/documentation/appkit/nsscreen/1388393-screens).
The screen considered as main (with the menubar) is the one with index 0.
It is not the same as NSScreen.main which is the screen with the current active window.


text:
Q: How to Load a bunch of images Stored in server into android app We want to load images which are stored in PHP server into our android app.
We have stored image urls in mysql db and we are able to fetch them all in an ArrayList imgNames but we are not able to set them into the gridview .
We also have to maintain the aspect ratio of the image because its a painting image that we waant to show and we cannot show it in static square blocks .
This is our code in which we fetch the image urls from the server -- >
    public class fragmentShopall extends Fragment{

        public JSONObject jsonResponse;
        public JSONArray jsonMainNode;
        public ListView mListView;
        public ArrayList<String> mylist,imgNames ;
        public ArrayAdapter<String> dataAdapter;
        public GridView grid;
        public ListView list;
         public fragmentShopall(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragmentshopall, container, false);
        grid=(GridView) rootView.findViewById(R.id.gridView1);
        list = (ListView) rootView.findViewById(R.id.listView1);

        testAsynch MyTask= new testAsynch();
        MyTask.execute();

        return rootView;
    }

    class testAsynch extends AsyncTask<Void,Integer,String>
    {
        String readFeed;
        JSONObject json;
        StringBuilder builder = new StringBuilder();

        protected void onPreExecute(){

                Log.d("PreExceute","On pre Exceute......");
        }

      protected String doInBackground(Void...arg0) {

        Log.d("DoINBackGround","On doInBackground...");
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();

        // domain intentionally obfuscated for security reasons
        //HttpGet httpGet = new HttpGet("http://innobytes.in/webservices/category");
        HttpGet httpGet = new HttpGet("http://10.0.2.2/pratik/category");
        httpGet.setHeader("content-type", "application/json; charset=UTF-8");
        try
        {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
              }
            } else {
                Log.d("onProgressUpdate","Failed to download file..........");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
        return builder.toString();

    }

        @SuppressWarnings("null")
        protected void onPostExecute(String result) {
                // NOTE: You can call UI Element here.
            String autcElement = null;
            String img;

    String url="http://innobytes.in/artsgallery.in/productpic/";
    imgNames = new ArrayList<String>();
    mylist = new ArrayList<String>();
        try{
            readFeed = result;

            JSONArray jsonarray = new JSONArray(readFeed);

            System.out.println("OKAY_8!!");
            //*********** Process each JSON Node ***********//*

            int lengthJsonArr = jsonarray.length();

        for (int i = 0; i < lengthJsonArr; i++)
            {

            System.out.println("OKAY_9!!");
        //****** Get Object for each JSON node. ***********//*
            JSONObject jsonChildNode = jsonarray.getJSONObject(i);
            autcElement = jsonChildNode.optString("tbimageurl").toString();
            imgNames.add(autcElement);
            img=url+autcElement;
            mylist.add(img);
            System.out.println(""+img);

            System.out.print(" Hi....  "+mylist.get(i));

//Picasso.with(getActivity()).load("http://innobytes.in/artsgallery.in/productpic/"+autcElement).into((Target) list);

            }

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

            // Close progress dialog
        }
      }
    }

What would be the best possible solution to get the images using the urls that we fetched and display them all while maintaining their aspect ratio maybe like Pinterest or Flickr  ?

A: Instead of downloading each and every image you can use LazyList Loading mechanism
Basically lazy list loading is lazy loading of images from sd-card or from server using urls. It is like on demand loading images.
Images can be cached to local sd-card or phone memory. Url is considered the key. If the key is present in sd-card, display images from sd-card else display image by downloading from server and cache the same to location of your choice. The cache limit can set. You can also choose your own location to cache images. Cache can also be cleared.
Instead of user waiting to download large images and then displaying lazy list, loads images on demand. Since images are cached you can display images offline.

A: firstly create bean for initializing your value's
like that
public class Beanclassname {

    private String mediaImageUrl;

    public String getMediaImageUrl() {
        return mediaImageUrl;
    }
    public void setMediaImageUrl(String mediaImageUrl) {
        this.mediaImageUrl = mediaImageUrl;
    }
}

now put values in bean and atlast add it in arraylist and do setadapter
like that
bean.setMediaImageUrl(jsonChildNode.getString("key"));
arraylist.add(bean);
_adapter = new adapter(this, arraylist);
                        gridview.setAdapter(_adapter);
                        _adapter.notifyDataSetChanged();

now in your adapter use lazy imageloader to display image

A: You can also use Android Image Loader library.
Check this - https://github.com/nostra13/Android-Universal-Image-Loader
Advantages of using this library -

*

*Multithread image loading

*Image caching in memory and/or on device's file system (or SD card)


text:
Q: Универсальная настройка ajax запросов есть приличное количество функций с ajax запросами которые содержат в себе повторяющиеся действия, к примеру следующая функция отправляет отзыв о товаре на сервер, перед отправкой вызывается bodyCover(); $(btn).addClass('disabled'); Progress.start(); и после получения ответа сервера bodyCover(); $(btn).removeClass('disabled'); Progress.complete();
bodyCover накладывает невидимой блок поверх сайта чтобы за время запроса пользователь не смог манипулирвать сайтом, второй метод дизейблит кнопку формы, третий создаёт и завршает бегущую линию прогресса в самом верху сайта (как на ютуб). Так вот эти 3 метода расположны во многих функциях и мне хотелось бы узнать как лучше создать универсальную мини систему чтобы это всё выполнялось автоматически во всех аякс запросах без повтора кода.
function addReview(form, btn) {
bodyCover(); $(btn).addClass('disabled'); Progress.start();

$.ajax({
    ...
    success: function(data) {
        bodyCover(); $(btn).removeClass('disabled'); Progress.complete();
    }
})

}


text:
Q: how to open web page in chrome browser by default in android I try to open my web page as default in chrome  how could i do it .
MyCode Is:
       try {
            Intent i = new Intent("android.intent.action.VIEW");
            i.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.example.webviewdemo.MainActivity"));
            i.addCategory("android.intent.category.LAUNCHER");
            i.setData(Uri.parse(url));
            startActivity(i);
        }
        catch(ActivityNotFoundException e)
        {
             //exception raised
            e.printStackTrace();
            // Chrome is probably not installed
        }

When I run this activity not found exception shown error

A: Try this instead,
internetIntent.setComponent(new ComponentName("com.android.chrome","com.android.browser.BrowserActivity"));
internetIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);


text:
Q: What is the default redirect code in lighttpd's mod_redirect? 301 or 302? What is the default redirect code in lighttpd's mod_redirect? HTTP Status 301 (moved permanently) or 302 (found / temporarily moved)?

A: Never mind.  I found the answer: 301 redirect, as I had expected.
http://redmine.lighttpd.net/projects/lighttpd/repository/revisions/1580/diff/trunk/src/mod_redirect.c (line 195)


text:
Q: facebook users who r not my friends but using the app The new Facebook graph api has divided friends into Friends & Invitable_friends .
me/friends/ returns my friends who are using the app while me/invitable_friends/ returns only the list of my friends who are not using the app.
But in my app,a user may interact with random users too who may not be on his friend list.
So how do i get user data for those who are using the app but are not on my friend list.
Thanks.

A: I went through the same issue and solved it like that: when a user starts your app by default you ask for permission to access his public profile information, which includes real ID, name and some other. You simply store the user data (id, name, etc.)in a database. This way you keep track of all the people using your app and they can interact with each other.
JavaScript Example:
window.fbAsyncInit = function () {
    FB._https = true;
    console.log('here');
    FB.init({ appId: 'xxxxxxxxxxxxxxxx', cookie: true, xfbml: true, oauth: true, version : 'v2.0'});
    Login();
};
function Login() {
    FB.login(function(response) {
            if (response.authResponse){
            checkUser();
            }
            else{
                console.log('User cancelled login or did not fully authorize.');
            }
        }
    );
}
function checkUser() {
FB.api('/me', function(response) {
    $.ajax({
        type: "get",
        url: "cgi-bin/checkUser.cgi",
        cache: false,
        data: {"user_name" : response.name, "u_id" : response.id, "link" : response.link},
        success: function() //onSuccess,
        {
            console.log("user " + response.name + " checked!");
        },
        error: function()
        {
            console.log("Error with server connection on user checking");
        }
    });
});
}

I don't know in what language you are writing the app but I believe that in every language you should call the "login" function, which asks the user for permissions and basically gets access to info.

A: To get details of users who are using the app but are not your friends,call the following

graph.facebook.com/v2.0/
?ids={comma-separated-ids}&access_token=app_access_token&fields=name,picture

access_token is a must else graph-api returns following error-
The global ID xyz is not allowed. Please use the application specific ID instead.
This will work for all users who have authenticated the app no matter their authentication date,but for any non-app user graph-api returns above error message.


text:
Q: How to create floating button with SliverAppbar and add ListView in Flutter? Any idea to create a page with a floating button with Container, ListView using SilverAppBar in Flutter?
I follow this step How can I put a card into a sliver app bar? it works but cannot add Container below.

A: NestedScrollView solved my problem.


text:
Q: Apache SSL passphrase with p12 file We have a p12 (PKCS#12) <my_ssl_key_file.p12> file for SSL Certificate Key file requiring a passphrase. However, referencing it in the apache directive like so does not work:
<VirtualHost *:443>
    ...
    ...
    SSLCertificateKeyFile /path/to/my_ssl_key_file.p12
    ...
</VirtualHost>

I can get around by converting the p12 file using openssl pkcs12 with the passphrase like so:
$openssl pkcs12 -in my_ssl_key_file.p12 -out my_ssl_key_file.key

and changing the directive to reference the new my_ssl_key_file.key
but this seems counterintuitive to strip the P12 encryption. Is there a way to directly reference the P12 file instead? Perhaps my approach is the wrong approach?

A: PKCS12 is not supported by SSLCertificateKeyFile.
From the doc, PEM is the required format. And the private key should be protected by a passphrase.
Note that the PKCS12 is used to hold the certificate and the certificate chain and the private key as well.


text:
Q: How to save the WindRose plot result as summary table?  library("openair")
 library("plyr")

I have the following the line code and I need to summarize the result from the WindRose plot in compass values (i.e. N=1000,NE-6859,W=9585,etc). The function is based on the package openair. I do not know how to extract from the plot, the frecuency values for each wind direction paddle.
windRose(viento,"WS_ms_Avg","WindDir",type="mes", paddle=FALSE,layout=c(3,4))

A: Is this what you're looking for?
tmp_1 <- windRose(mydata)

head(tmp_1$data)

##                           default Interval1 Interval2 Interval3 Interval4
## 1 01 January 1998 to 23 June 2005 0.9918888  4.560834  6.322132  6.838161
## 2 01 January 1998 to 23 June 2005 0.4665894  2.679027  4.344535  5.113944
## 3 01 January 1998 to 23 June 2005 0.4264195  2.479722  4.339900  4.956354
## 4 01 January 1998 to 23 June 2005 0.5561993  2.399382  3.589031  4.018540
## 5 01 January 1998 to 23 June 2005 0.6056392  2.717652  4.105060  4.863654
## 6 01 January 1998 to 23 June 2005 0.7122441  3.797605  7.341831 10.246427
##    wd calm panel.fun mean.wd freqs
## 1  30  0.1      4.49  -118.3  4426
## 2  60  0.1      4.49  -118.3  3310
## 3  90  0.1      4.49  -118.3  3208
## 4 120  0.1      4.49  -118.3  2601
## 5 150  0.1      4.49  -118.3  3148
## 6 180  0.1      4.49  -118.3  6632

tmp_2 <- windRose(mydata, type="year")

head(tmp_2$data)

##   year Interval1 Interval2 Interval3 Interval4  wd calm panel.fun mean.wd
## 1 1998 1.5962554  6.204993  7.057129  7.093135  30  0.2      4.38  -110.4
## 2 1998 0.5160826  3.300528  4.176668  4.200672  60  0.2      4.38  -110.4
## 3 1998 0.2760442  1.500240  2.472396  2.652424  90  0.2      4.38  -110.4
## 4 1998 0.5160826  2.244359  3.192511  3.480557 120  0.2      4.38  -110.4
## 5 1998 0.7561210  2.568411  3.552568  3.972636 150  0.2      4.38  -110.4
## 6 1998 0.9481517  3.984638  7.333173  9.841575 180  0.2      4.38  -110.4
##   freqs
## 1   591
## 2   350
## 3   221
## 4   290
## 5   331
## 6   820


text:
Q: Moodle Error writing to database I am getting Error writing to database in moodle:
Code:
if (is_siteadmin()) {
class addschedule_form extends moodleform {
function definition () {
  $mform =& $this->_form;
  $mform->addElement('text', 'id', 'Enter ID:');
  $mform->setType('id', PARAM_TEXT);
  $this->add_action_buttons(true, 'submit');
   }
   }

  $ti_form = new addschedule_form();
  $ti_form->get_data();
  if ($ti_form->is_cancelled()) {redirect('index.php');}
  if ($recs = $ti_form->get_data()) {
  $deleteit = $DB -> delete_records('DELETE * FROM `mdl_schedules` WHERE id = ' . $recs -> id . '');
  redirect('schedule.php');
   }
   }
else {  }
$ti_form->display();

What could be the reason? Any reference or help will be much appreciated.
Regards

A: The syntax is
$DB->delete_records('schedules', array('id' => $recs->id));

You might want to keep this open in a tab for reference - https://docs.moodle.org/dev/Data_manipulation_API


text:
Q: 3D Arrays not working public static String[] getWords(int cat, int diff) {
    String topic[][][] = new String[3][3][3];
    switch(cat){
        case 0:
            topic[0][0][0] = "Paris";
            topic[0][0][1] = "London";
            topic[0][0][2] = "Sydney";
            diff = 0;
            topic[0][1][0] = "Toronto";
            topic[0][1][1] = "Florida";
            topic[0][1][2] = "Frankfurt";
            diff = 1;
            topic[0][2][0] = "Barcelona";
            topic[0][2][1] = "Vancouver";
            topic[0][2][2] = "Zimbabwe";
            diff = 2;
        case 1:
            topic[1][0][0] = "Halo";
            topic[1][0][1] = "Fifa";
            topic[1][0][2] = "GTA";
            diff = 0;
            topic[1][1][0] = "Skyrim";
            topic[1][1][1] = "HITMAN";
            topic[1][1][2] = "Batman";
            diff =1;
            topic[1][2][0] = "Minecraft";
            topic[1][2][1] = "Zombieville";
            topic[1][2][2] = "BoderLands";
            diff =2;
        case 2:
            topic[2][0][0] = "Acura";
            topic[2][0][1] = "Audi";
            topic[2][0][2] = "Bmw";
            diff = 0;
            topic[2][1][0] = "Bentley";
            topic[2][1][1] = "Buggati";
            topic[2][1][2] = "Honda";
            diff = 1;
            topic[2][2][0] = "Lamborghini";
            topic[2][2][1] = "Rolls-Royce";
            topic[2][2][2] = "Mercedes";
            diff = 2;
    }
    return topic[cat][diff];
}

So this my method with the 3d arrays and i want to know if i did it right, and also if i call it in the main method will it work?? I used switch statement since someone recommended me it, i'm really new to java, as u can see
This is for the game Hangman

A: No, it won't. Your switch does not contain any break; statements, therefore after it meets the first case which evaluates to true, it will then perform all statements after that until the end of the switch, or until you break; or return something.
Additionally, the calls to:
diff = 0;
// ...
diff = 1;
// ...
diff = 2;

Are redundant, as the assigned value is never used.
So it should be:
switch(cat)
{
    case 0:
        topic[0][0][0] = "Paris";
        topic[0][0][1] = "London";
        topic[0][0][2] = "Sydney";

        topic[0][1][0] = "Toronto";
        topic[0][1][1] = "Florida";
        topic[0][1][2] = "Frankfurt";

        topic[0][2][0] = "Barcelona";
        topic[0][2][1] = "Vancouver";
        topic[0][2][2] = "Zimbabwe";
        break;
    case 1:
        topic[1][0][0] = "Halo";
        topic[1][0][1] = "Fifa";
        topic[1][0][2] = "GTA";

        topic[1][1][0] = "Skyrim";
        topic[1][1][1] = "HITMAN";
        topic[1][1][2] = "Batman";

        topic[1][2][0] = "Minecraft";
        topic[1][2][1] = "Zombieville";
        topic[1][2][2] = "BoderLands";
        break;
    case 2:
        topic[2][0][0] = "Acura";
        topic[2][0][1] = "Audi";
        topic[2][0][2] = "Bmw";

        topic[2][1][0] = "Bentley";
        topic[2][1][1] = "Buggati";
        topic[2][1][2] = "Honda";

        topic[2][2][0] = "Lamborghini";
        topic[2][2][1] = "Rolls-Royce";
        topic[2][2][2] = "Mercedes";
        break;
}

A: you need a break; in between cases. It'll just simply go through every case since there's no breaks. Well every case if it's case 1, and 2&3 if it's 2, and just 3.
So 3 is the only one that'd break properly, because since it's the last you don't need one.!


text:
Q: Laravel - The PUT method is not supported for this route. Supported methods: GET, HEAD I am working on a web application using Laravel-5.8. In the CRUD, I was able to Create and View records. However, I have problem with Update and delete.
Controller
class HrHolidayGroupsController extends Controller
{

public function index()
{
    $userCompany = Auth::user()->company_id;
    abort_unless(\Gate::allows('holiday_group_access'), 403);
    if (auth()->user()->isAdmin()) {
        $groups = HrHolidayGroup::all();
    } else {
        $groups = HrHolidayGroup::where('company_id', $userCompany)->get();
    }
    return view('hr.holiday_groups.index')->with('groups', $groups);
}

public function create()
{
    $userCompany = Auth::user()->company_id;
    abort_unless(\Gate::allows('holiday_group_create'), 403);
    return view('hr.holiday_groups.create');
}
public function store(StoreHolidayGroupRequest $request)
{
    abort_unless(\Gate::allows('holiday_group_create'), 403);

    $group = HrHolidayGroup::create([
        'group_name'         => $request->group_name,
        'description'       => $request->description,
        'company_id'        => Auth::user()->company_id,
        'created_by'        => Auth::user()->id,
        'created_at'        => date("Y-m-d H:i:s"),
        'is_active'         => 1,
    ]);
    Session::flash('success', 'Holiday Group is created successfully');
    return redirect()->route('hr.holiday_groups.index');
}
    public function show($id)
    {
        abort_unless(\Gate::allows('holiday_group_show'), 403);
        return view('hr.holiday_groups.show', ['group' => HrHolidayGroup::findOrFail($id)]);
    }

public function edit($id)
{
    $userCompany = Auth::user()->company_id;

    abort_unless(\Gate::allows('holiday_group_edit'), 403);
    $group = HrHolidayGroup::where('id', $id)->first();
    return view('hr.holiday_groups.edit')->with('group', $group);
}

public function update(UpdateHolidayGroupRequest $request, $id)
{

    abort_unless(\Gate::allows('holiday_group_edit'), 403);

    $group = HrHolidayGroup::find($id);
    $group->group_name = $request->group_name;
    $group->description = $request->description;
    $group->company_id = Auth::user()->company_id;
    $group->updated_by = Auth::user()->id;
    $group->updated_at = date("Y-m-d H:i:s");
    $group->is_active = 1;
    $group->save();
    Session::flash('success', 'Holiday Group is updated successfully');
    return redirect()->route('hr.holiday_groups.index');
}

public function destroy(Request $request, $id)
{
    $group = HrHolidayGroup::find($id);
    $group->delete();
    Session::flash('success', 'Holiday Group deleted successfully.');
    return redirect()->route('hr.holiday_groups.index');
}

routes/web.php
Route::group(['prefix' => 'hr', 'as' => 'hr.', 'namespace' => 'Hr', 'middleware' => ['auth']], function () {

Route::resource('holiday_groups', 'HrHolidayGroupsController');
});

index.php

  @foreach($groups as $key => $group)

     {{$key+1}}

      {{$group->group_name ?? '' }}

      {{ $group->description ?? '' }}

       @can('holiday_group_show')
    id) }}">
       { trans('global.view') }}

        @endcan
        @can('holiday_group_edit')
    id) }}">
        {{ trans('global.edit') }}

        @endcan
        @can('holiday_group_delete')
    id }}" data-original-title="Close">
     span style="color:white;">{{ trans('global.delete') }}

        @endcan

id }}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

Delete Holiday Group

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
           ×
          </button>

         <form action="{{route('hr.holiday_groups.destroy',['id'=>$group->id])}}" method="post">
         {{ csrf_field() }}

Are you sure you want to delete this Holiday Group?

{{ $group->group_name }}

         </form>

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-danger">Delete</button>

  @endforeach

I started using Laravel about five months ago, and I need to complete this project in a short time. The problem I have is that, when I click on save button in the edit/update form I got this error:

The PUT method is not supported for this route. Supported methods: GET, HEAD

Initially, the error was:

The POST method is not supported for this route.

This is the my code for the edit form:
edit.blade.php

<form  action="{{route('hr.holiday_groups.edit', ['id'=>$group->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">

        {{ csrf_field() }}

   <input type="hidden" name="_method" value="PUT">

                                        Group Name*

                                            <input  type="text" name="group_name" placeholder="Enter group name here" class="form-control" value="{{old('group_name',$group->group_name)}}" required data-validation-required-message="This field is required">

                                        Description

                                            <textarea rows="2" name="description" class="form-control" placeholder="Enter Description here" value="{{old('description',$group->description)}}">{{old('description',$group->group_name)}}</textarea>

                   <button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
                <button type="button" onclick="window.location.href='{{route('hr.holiday_groups.index')}}'" class="btn btn-default">Cancel</button>

</form>

I added @method('PUT') to the code, but the error is still there. How do I resolve this issue?
Thank you

A: The edit route is for showing the edit form. It isn't for processing it; that would be what update is for. Send you form to:
route('hr.holiday_groups.update', ['holiday_group' => $group->id])


text:
Q: LoaderLock Error I'm facing a problem for connecting to my database .I wanna connect to one of my sqlserver's DB and I use SqlConnection but when I open my database connection there's an error with this title "LoaderLock was detected" and this message :
"Attempting managed execution inside OS Loader lock. Do not attempt to run managed code inside a DllMain or image initialization function since doing so can cause the application to hang."
and here's the code :
{
    SqlConnection sc = new SqlConnection("Data Source=.;Initial Catalog=DB1;Integrated Security=True");
    SqlCommand scom = new SqlCommand(@"insert into t1 values(2,'Daniel')", sc);
    sc.Open();
    scom.ExecuteNonQuery();
    sc.Close();
}

Please help me through this problem,what am I missing here ? and what should I do?


text:
Q: Get client's IP address from load balance server by X-Forwarded-For I have MVC application on load balance server and I want to set real client's IP address. I added "X-Forwarded-For" on custom header and use c#.net code as below to get IP address but it return null. Please help me how I can check or how I can do. Thank you.
Add custom header :
Response.AddHeader("X-Forwarded-For", "client1, proxy1, proxy2");

c#.net code :
string IP_REMOTE_ADDR = string.Empty;
string IP_HTTP_X_FORWARDED_FOR = string.Empty;
string RETURN_IP = string.Empty;

IP_REMOTE_ADDR = string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]) ? "" : System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
IP_HTTP_X_FORWARDED_FOR = string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) ? "" : System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (IP_HTTP_X_FORWARDED_FOR != "")
{
    RETURN_IP = IP_HTTP_X_FORWARDED_FOR;
    if (RETURN_IP.Contains(","))
    {
        RETURN_IP = RETURN_IP.Split(',')[0];
    }
}
else
{
    if(IP_REMOTE_ADDR != "")
    {
        RETURN_IP = IP_REMOTE_ADDR;
    }
    else
    {
        RETURN_IP = "";
    }
}

return RETURN_IP;


text:
Q: Canonical commutation relations in Light-cone gauge It seems that when trying to identify the physical degrees of freedom for the string some authors$^1$ use:
$$ q^-=\frac{1}{\ell}\int_0^{\ell} X^-(\tau,\sigma)d\sigma$$
Then, the commutation relation is
$$[q-,p^+]=-i$$
Other authors$^2$ choose the constant part of $X^-=x_0^- + f(\tau,\sigma)$
so the commutation relation is
$$[x_0^- ,p^+]=-i$$
You can think that this is just a free choice, however everybody uses the same hamiltonian
$$H=2\alpha' p^+p^-$$ Of course, $p^-$ is an integral but my point is that the same $H$ cannot work for both cases.
Because in the second case the equation of motion for $x_0^-$ leads to $$\dot{x_0^-} =0$$
which is expected($x_0^-$ is constant as pointed out in $^2$).
But in the first case it would be $q^-=$constant which is wrong, or there must be something I am missing here.
In short, my questions are:
Why this is happening?
Why some people use $[q-,p^+]=-i$ and others use $[x_0^- ,p^+]=-i$?
RELATION BETWEEN $q^-$ and $x^-_0$
I am going to use eq. (12.98) in Zwiebach's book.
$$ X^-(\tau,\sigma)=x^- _0 +\sqrt{2\alpha'}\alpha^-_0 \tau + oscillators$$
Since the oscillators will not contribute anything, integration leads
$$ q^-=\frac{1}{\ell}\int_0^{\ell} X^-(\tau,\sigma)d\sigma=x^- _0 +\sqrt{2\alpha'}\alpha^-_0 \ \tau$$

$^1$ Sundermeyer; Constrained Dynamics, Lecture Notes in Physics; page 220; also see this post.
also see Ralph Blumenhagen, Dieter Lust and Stefan Theisen; Basic Concepts of String Theory; pages 24 and 44.
$^2$ Zwiebach; A first course in String Theory, 2nd edition; 2009; page 238

A: Comments to the question (v3):

*

*The $X^-$ coordinate has (a part from a zero mode) been integrated out in the light-cone (LC) formalism. The above mentioned LC Hamiltonian cannot fully address questions about the $X^-$ coordinate.

*To get the well-known expansion of $X^-$ as a sum of zero and oscillator modes including the sought-for $\alpha^-_0$ mode term, one has to go back to the full string formulation prior to the LC reduction, cf. e.g. my Phys.SE answer here. By doing this, one may show that the $\alpha^-_0$ mode term indeed appears in the expansion of $X^-$ as it should.


text:
Q: Easiest way to pass a javascript array or its values to a servlet using jQuery's ajax() function I have a Javascript array. I want to pass it's data to a servlet using the ajax() method of jQuery.
What is the easiest way to do this. The index values i.e. the i in array[i] are not in order, they are numbers that have meaning themselves, hence I cannot simply loop through and create a GET queryString, or so I believe.
Maybe I should be converting the JavaScript array to a JSON Object and sending that to the server ??
I am stumped on this one.

A: try this :
$.post('your page', {data : yourjavascriptarray}, function() {

});


text:
Q: On Google login redirect to https://myaccount.google.com/ when multiple Google account is logged in at the same time in browser - Laravel I  am tired with Google login, when single Gmail account logged in browser everything fine, but when two or more Gmail account logged in browser then login successfully but redirect in the google account setting (url:https://myaccount.google.com), here is my controller code. I want to redirect to back page.
public function redirect()
    {
        return Socialite::driver('google')->redirect();
    }

    public function callback()
    {
            $googleUser = Socialite::driver('google')->user();
            $existUser = User::where('email',$googleUser->email)->first();

            if($existUser) {
                Auth::loginUsingId($existUser->id);
            }
            else {
                $user = new User;
                $user->first_name = $googleUser->name;
                $user->email = $googleUser->email;
                $user->google_id = $googleUser->id;
                $user->password = bcrypt(rand(1,10));
                $user->save();
                Auth::loginUsingId($user->id);
            }
                return back();
        }

Redirect to this page, I want to redirect back page

A: This happens because of return back(); since your server is redirecting back to Google through the HTTP Referer header. This header is unreliable, please do not use it.
Instead, before login with google, save the current URL in the user session and after the login callback, redirect to that URL. In this way, you will be able to bring the user back to the original page.


text:
Q: How to execute gdb breakpoint commands in batch mode? I'm trying to use gdb non-interactively - i.e. printing something on every specified breakpoint.
$ cat script.gdb
set pagination off
catch syscall
commands
bt
c
end
# It's a hack to get backtraces only on call not on return - Linux and x86_64 specific.
# For sake of this question it can be removed, it will just output more.
condition $bpnum $rax == -38

The problem - non-interactive try with batch mode:
$ gdb /bin/true -batch -x script.gdb
Catchpoint 1 (any syscall)
Catchpoint 2 (syscall 'fork' [57])

Catchpoint 1 (call to syscall brk), 0x00007ffff7df2f9c in brk () from /lib64/ld-linux-x86-64.so.2

However if I would run it interactively:
$ gdb /bin/true -x script.gdb
GNU gdb (GDB) 8.1

...

Reading symbols from /bin/true...
(no debugging symbols found)...done.
Catchpoint 1 (any syscall)
Catchpoint 2 (syscall 'fork' [57])
(gdb) run
Starting program: /usr/bin/true

Catchpoint 1 (call to syscall brk), 0x00007ffff7df2f9c in brk () from /lib64/ld-linux-x86-64.so.2
#0  0x00007ffff7df2f9c in brk () from /lib64/ld-linux-x86-64.so.2
#1  0x00007ffff7df2488 in _dl_sysdep_start () from /lib64/ld-linux-x86-64.so.2
#2  0x00007ffff7ddcbc1 in _dl_start () from /lib64/ld-linux-x86-64.so.2
#3  0x00007ffff7ddc178 in _start () from /lib64/ld-linux-x86-64.so.2
#4  0x0000000000000001 in ?? ()
#5  0x00007fffffffe2a5 in ?? ()
#6  0x0000000000000000 in ?? ()

...

Catchpoint 1 (call to syscall exit_group), 0x00007ffff7ad7529 in _exit () from /lib64/libc.so.6
#0  0x00007ffff7ad7529 in _exit () from /lib64/libc.so.6
#1  0x00007ffff7a50a2b in __run_exit_handlers () from /lib64/libc.so.6
#2  0x00007ffff7a50ab5 in exit () from /lib64/libc.so.6
#3  0x000000000040132d in ?? ()
#4  0x00007ffff7a39c05 in __libc_start_main () from /lib64/libc.so.6
#5  0x0000000000401406 in ?? ()
[Inferior 1 (process 35434) exited normally]
(gdb) quit

Then it works as intended - breakpoint commands are executed.
Adding additional -ex c to the non-interactive command will just add another line of Catchpoint 1 ..., but still no backtrace.
Man page and Debugging with GDB is not helpful.
I guess that there has to be some command that would just wait until it's over or maybe a setting somewhere like the pagination one.
I know that I could use something akin to an expect script, but I would like to avoid it. Something like this works:
echo 'run
quit' | gdb /bin/true -x script.gdb

A: Adding run to the end of your script produces the result you want (at least it does when using GNU gdb (GDB) Fedora 8.1-15.fc28).

Something like this works:
echo 'run
quit' | gdb /bin/true -x script.gdb

It works or you want it to work?
The quit part is redundant -- GDB will quit once it reaches the end of script. And the echo run part doesn't work because in batch mode GDB will not read its standard input.


text:
Q: excel/vba - find fist and last occurrence of a particular value in a column So if I have a column such as:
    A1
1   Apple
2   Apple
3   Apple
4   Oj
5   Oj
6   Oj
7   Oj
8   Pear
9   Pear

How could I return the values 1 & 3 for Apple, 4 & 7 for OJ, etc?

A: Formula-wise you can use MATCH functions, e.g. for first Apple position
=MATCH("Apple",A1:A9,0)
for last
=MATCH(2,INDEX(1/(A1:A9="Apple"),0))
or if the fruit are sorted as per your example (or merely grouped) you can get the last by adding the number of apples to the first -1
so with first MATCH function in C1 that would be
=COUNTIF(A1:A9,"Apple")+C1-1


text:
Q: 1st data is officeIn and 2nd data is OfficeOut.. A user can multiple enter in a day.. i want how much time in hh:mm:ss format he stay in office
1476    5   2019-03-18 09:35:06.000
1487    5   2019-03-18 13:19:53.000
1488    5   2019-03-18 13:37:40.000
1495    5   2019-03-18 15:09:38.000
1497    5   2019-03-18 15:18:26.000
1503    5   2019-03-18 17:34:46.000
1504    5   2019-03-18 17:48:23.000
1511    5   2019-03-18 19:14:51.000

A: I used LAGOVER to calculate the time difference and then used ROW_NUMBER to only calculate every second row. Then I select only the rows with a calculated value. This solution is of course quite fragile since it relies on a correct number of rows with no timestamp missing.
SELECT employeeID, time
FROM (
    SELECT employeeID,
        CASE ROW_NUMBER() over (partition by employeeId ORDER BY checktime ASC) MOD 2
        WHEN 1 THEN null
        ELSE TIMEDIFF(checktime, LAG(checktime) over (partition by employeeId ORDER BY checktime ASC))
        END as Time
        FROM table1) t1
WHERE time IS NOT NULL


text:
Q: mysqljs with transactional processing I have the following code in  my CustRepo that is not working, not showing any error log,
var addCustomer = function (customer) {
return new Promise(function (resolve, reject) {
    let sqlString = 'call qins_Customer' + '(' +
        '"' + customer.Name + '"' + ',' +
        '"' + customer.Contact + '"' + ',' +
        '"' + customer.Address + '"' + ',' +
        '"' + customer.EmailAddress + '"' + ',' +
        '"' + customer.CustomerNotes + '"' + ',' +
        '"' + customer.MainTel + '"' + ',' +
        '"' + customer.Tel1 + '"' + ',' +
        '"' + customer.Tel2 + '"' + ',' +
        '@CustomerId'  + ');' +
        'select @CustomerId as CustomerId';
    console.log(sqlString);
    pool.getConnection.beginTransaction(function (err) {
        if (err) {
            console.log('err');
            return reject(err);
        }
        connection.query(sqlString, function (err, CustomerId) {
            console.log(CustomerId);
            let result = CustomerId;
            if (err) {
                    connection.rollback(function (err) {
                    console.log(err);
                    reject(err);
                });
            }
        });

        connection.commit(function (err) {
            if (err) {
                    connection.rollback(function (err) {
                    console.log('rejected');
                    reject(err);
                })
            } else { console.log('committed'); resolve(result); }
        });
    });
 });
}

If I remove the transaction processing and revert to non-transactional,
console.log of sqlString is
call qins_Customer("myCompany","Gary Gulp",
"Node Street Mocha MC229UG","gary@gmail.com","test888",
"01302 336 876",
"0153 2765 453","0134 5625 776",@CustomerId);
select @CustomerId as CustomerId

I get it working and I get table insertion and it produces the scope identity for Customer id (in Sql Server speak). Multiple statements is ON. My CustomerService module has this code
    let addCustomer = customerRepo.addCustomer(customer);
addCustomer
    .then(function (result) {
        resolve(result);
        return result || '-1';
    })
    .catch(function (err) {
        return reject(err);
    })

Any help is greatly appreciated.


text:
Q: How do I keep terraform's remote-exec shell persistent? Good day,
I'm provisioning VMs from a template on vSphere with Terraform. Once the VMs come up, a file provisioner copies local static content (pictures). Once that's done, a remote-exec provisioner does this:
provisioner "remote-exec" {
     inline = [
       "mkdir /home/foo/static",
       "mv /home/foo/logo.jpg /home/foo/static/",
       "echo 'python /home/foo/app.py 2>&1 &' > /home/foo/start_app.sh",
       "chmod u+x /home/foo/start_app.sh",
       "/home/foo/start_app.sh 2>&1",
       "sleep 60"
     ]
}

app.py is a Python Flask project. The code starts and serves content fine .. for roughly 60 seconds. When my sleep timer expires, I suspect the shell spawned by Terraform dies and so does app.py. I tried launching start_app.sh in the background, I tried sudoing it (foreground and background) to no avail. Same behavior. If I start python /home/foo/app.py directly inside the remote-exec block rather than invoking start_app.sh, then TF never exits the shell and my Jenkins build keeps spinning forever.
I don't think it makes any difference, but to be complete my TF VMware plan is applied when Git sends a webhook to Jenkins. Jenkins invokes the TF plan as part of a pipeline stage. Here's the console output from Jenkins:
vsphere_virtual_machine.vm[1]: Provisioning with 'file'...
vsphere_virtual_machine.vm[1]: Provisioning with 'remote-exec'...
vsphere_virtual_machine.vm[1] (remote-exec): Connecting to remote host via SSH...
vsphere_virtual_machine.vm[1] (remote-exec):   Host: 1.1.1.200
vsphere_virtual_machine.vm[1] (remote-exec):   User: foo
vsphere_virtual_machine.vm[1] (remote-exec):   Password: true
vsphere_virtual_machine.vm[1] (remote-exec):   Private key: false
vsphere_virtual_machine.vm[1] (remote-exec):   SSH Agent: false
vsphere_virtual_machine.vm[1] (remote-exec):   Checking Host Key: false
vsphere_virtual_machine.vm[1] (remote-exec): Connected!
vsphere_virtual_machine.vm[1] (remote-exec):  * Serving Flask app "app" (lazy loading)
vsphere_virtual_machine.vm[1] (remote-exec):  * Environment: production
vsphere_virtual_machine.vm[1] (remote-exec):    WARNING: This is a development server. Do not use it in a production deployment.
vsphere_virtual_machine.vm[1] (remote-exec): [2m   Use a production WSGI server inst
vsphere_virtual_machine.vm[1] (remote-exec):  * Debug mode: off
vsphere_virtual_machine.vm[1] (remote-exec):  * Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
vsphere_virtual_machine.vm.1: Still creating... (8m30s elapsed)
vsphere_virtual_machine.vm.0: Still creating... (8m30s elapsed)
vsphere_virtual_machine.vm.1: Still creating... (8m40s elapsed)
vsphere_virtual_machine.vm.0: Still creating... (8m40s elapsed)
vsphere_virtual_machine.vm.1: Still creating... (8m50s elapsed)
vsphere_virtual_machine.vm.0: Still creating... (8m50s elapsed)
vsphere_virtual_machine.vm.1: Still creating... (9m0s elapsed)
vsphere_virtual_machine.vm.0: Still creating... (9m0s elapsed)
vsphere_virtual_machine.vm.1: Still creating... (9m10s elapsed)
vsphere_virtual_machine.vm.0: Still creating... (9m10s elapsed)
vsphere_virtual_machine.vm[0]: Creation complete after 9m15s (ID: 4228d941-a19c-361d-073a-4441cde5973e)

How can I keep the shell spawned by TF persistent after TF's remote-exec is done?

A: OK - I found a really terrible hack. Terraform doesn't run remote-exec anymore, it just pushes my python Flask app and its associated static content using a file provisioner. Inside Jenkins, I have a stage that looks like this:
def remote = [:]
remote.name = "1.1.1.200"
remote.host = "1.1.1.200"
remote.allowAnyHosts = true

node {
    withCredentials([usernamePassword(credentialsId: 'sshUserAccount', passwordVariable: 'password', usernameVariable: 'userName')]) {
        remote.user = userName
        remote.password = password
        stage("SSH Steps Rocks!") {
            try {
              timeout(time: 1, unit: 'MINUTES') {
                sshCommand remote: remote, command: '/home/foo/start_app.sh &'
              }
            } catch (err){
               currentBuild.result = 'SUCCESS'
              }
        }
   }
}

Once the Jenkins SSH thread exits after one minute, my python app keeps running on the remote machine. Yay! It's just for a lab demo, not something I'd consider doing in prod. I'd use custom templates as suggested.


text:
Q: How to remove spinner title? I am using spinner in android action bar and want to display some items.But that spinner background has image.When I add list of item in spinner.By default first value displays near to the image.Is there any way to remove that by default text.
My spinner code is :
    <Spinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:background="@drawable/ic_action_overflow"
            android:entries="@array/spinnerItems"/>

array/spinnerItems :
    <string-array name="spinnerItems">
        <item>item1</item>
        <item>item2</item>
        <item>item3</item>
        <item>item4</item>
    </string-array>

Please find the attached image for reference :

I want to remove the text "item1" displayed near to action overflow image icon.

A:      ArrayAdapter<CharSequence> adapter =new ArrayAdapter<CharSequence>
      (this,android.R.layout.simple_spinner_item){
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView,
      @NonNull ViewGroup parent) {
            // this part is needed for hiding the original view
            View view = super.getView(position, convertView, parent);
            view.setVisibility(View.GONE);
            return view;
        }
    };

A: In layout XML for Spinner use android:prompt=""
 <Spinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:prompt="@string/prompt"
            android:background="@drawable/ic_action_overflow"
            android:entries="@array/spinnerItems"/>

Or
add first item of spinner like
<item>""</item>

and promt string also should be
 <item>""</item>